input
stringlengths
50
13.9k
output_program
stringlengths
5
655k
output_answer
stringlengths
5
655k
split
stringclasses
1 value
dataset
stringclasses
1 value
RedDreamer has an array $a$ consisting of $n$ non-negative integers, and an unlucky integer $T$. Let's denote the misfortune of array $b$ having length $m$ as $f(b)$ — the number of pairs of integers $(i, j)$ such that $1 \le i < j \le m$ and $b_i + b_j = T$. RedDreamer has to paint each element of $a$ into one of two colors, white and black (for each element, the color is chosen independently), and then create two arrays $c$ and $d$ so that all white elements belong to $c$, and all black elements belong to $d$ (it is possible that one of these two arrays becomes empty). RedDreamer wants to paint the elements in such a way that $f(c) + f(d)$ is minimum possible. For example: if $n = 6$, $T = 7$ and $a = [1, 2, 3, 4, 5, 6]$, it is possible to paint the $1$-st, the $4$-th and the $5$-th elements white, and all other elements black. So $c = [1, 4, 5]$, $d = [2, 3, 6]$, and $f(c) + f(d) = 0 + 0 = 0$; if $n = 3$, $T = 6$ and $a = [3, 3, 3]$, it is possible to paint the $1$-st element white, and all other elements black. So $c = [3]$, $d = [3, 3]$, and $f(c) + f(d) = 0 + 1 = 1$. Help RedDreamer to paint the array optimally! -----Input----- The first line contains one integer $t$ ($1 \le t \le 1000$) — the number of test cases. Then $t$ test cases follow. The first line of each test case contains two integers $n$ and $T$ ($1 \le n \le 10^5$, $0 \le T \le 10^9$) — the number of elements in the array and the unlucky integer, respectively. The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($0 \le a_i \le 10^9$) — the elements of the array. The sum of $n$ over all test cases does not exceed $10^5$. -----Output----- For each test case print $n$ integers: $p_1$, $p_2$, ..., $p_n$ (each $p_i$ is either $0$ or $1$) denoting the colors. If $p_i$ is $0$, then $a_i$ is white and belongs to the array $c$, otherwise it is black and belongs to the array $d$. If there are multiple answers that minimize the value of $f(c) + f(d)$, print any of them. -----Example----- Input 2 6 7 1 2 3 4 5 6 3 6 3 3 3 Output 1 0 0 1 1 0 1 0 0
T = int(input()) for test in range(T): n,t = list(map(int,input().split())) a = list(map(int,input().split())) res = [] j=0 for i in a: if(i*2<t): res+=["0"] elif(i*2>t): res+=["1"] else: res.append(["0","1"][j]) j = 1-j print(" ".join(res))
T = int(input()) for test in range(T): n,t = list(map(int,input().split())) a = list(map(int,input().split())) res = [] j=0 for i in a: if(i*2<t): res+=["0"] elif(i*2>t): res+=["1"] else: res.append(["0","1"][j]) j = 1-j print(" ".join(res))
train
APPS_structured
You need to write a function, that returns the first non-repeated character in the given string. For example for string `"test"` function should return `'e'`. For string `"teeter"` function should return `'r'`. If a string contains all unique characters, then return just the first character of the string. Example: for input `"trend"` function should return `'t'` You can assume, that the input string has always non-zero length. If there is no repeating character, return `null` in JS or Java, and `None` in Python.
def first_non_repeated(s): for character in s: if s.count(character) == 1: return character break
def first_non_repeated(s): for character in s: if s.count(character) == 1: return character break
train
APPS_structured
Chef Hari has got a new obsession now: he has started playing chess (read about it here) and he is liking this game very much. Since Hari has spent several months playing chess with his friends, he has now decided to take part in some chess tournament in Cheftown. There are currently two tournaments going on in Cheftown and each tournament has its own entry fee. Due to this economical restriction and his budget, Hari can take part in only one tournament. The entry fee for first tournament is F1 units of money. The structure of tournament is as follows: first there will be group matches and then there will be finals. If Hari reaches in finals and wins it, he'll get R1 units of money. If after reaching in finals, Hari loses, he'll get R2 units of money. If Hari fails to reach in finals, he'll get nothing. The probability of reaching in finals of first tournament for Hari is p1 and probability of winning in finals after reaching is p2. The entry fee for second tournament is F2 units of money. The structure of tournament is as follows: first there will be group matches and then there will be finals. If Hari reaches in finals, he'll immediately get R3 units of money, otherwise he'll get nothing. If after reaching in finals, Hari wins, he'll get R4 units of money. The probability of reaching in finals of second tournament for Hari is p3 and probability of winning in finals after reaching is p4. Now, Hari wants to maximise his profit. He wants to know which tournament he should participate in such that his expected profit is maximised. Help Hari in deciding this. Note: In the tournaments of Cheftown, the game never ends with a draw. So, either Hari wins a game, or he loses. -----Input----- First line of the input contains T, the number of test cases. The description of each test case is as following: First line of each test case contains 6 integers F1, F2, R1, R2, R3 and R4. Next line of each test case contains 4 floating point numbers p1, p2, p3 and p4. Each number has exactly 2 digits after decimal point. -----Output----- For each test case, output a single line having "FIRST" if expected profit of first tournament is maximum or "SECOND" if expected profit of second tournament is maximum or "BOTH" if expected profits of both the tournaments is exactly same. -----Constraints----- - 1 ≤ T ≤ 100 - 1 ≤ F1, F2, R1, R2, R3, R4 ≤ 100 - 0.00 ≤ p1, p2, p3, p4 ≤ 1.00 -----Subtasks----- Subtask#1: 30 points - p1 = p3 and p2 = p4 Subtask#2: 70 points - All usual constraints. -----Example----- Input: 2 30 50 70 10 40 30 0.25 0.10 0.30 0.05 50 36 80 38 65 32 0.55 0.12 0.33 0.54 Output: FIRST SECOND -----Explanation----- In the first case, the expected profit for first tournament is -26.00 and expected profit for second tournament is -37.55. So, first tournament has better expected profit. In the second case, the expected profit for first tournament is -26.328 and expected profit for second tournament is -8.8476. So, second tournament has better expected profit.
def f(): f1,f2,r1,r2,r3,r4=list(map(int,input().split())) p1,p2,p3,p4=list(map(float,input().split())) e1 = p1*(p2*r1 + (1-p2)*r2) - f1 e2 = p3*(p4*r4 + r3) - f2 #print e1 #print e2 if e1==e2: return "BOTH" if e1>e2: return "FIRST" return "SECOND" t=int(input()) for i in range(t): print(f())
def f(): f1,f2,r1,r2,r3,r4=list(map(int,input().split())) p1,p2,p3,p4=list(map(float,input().split())) e1 = p1*(p2*r1 + (1-p2)*r2) - f1 e2 = p3*(p4*r4 + r3) - f2 #print e1 #print e2 if e1==e2: return "BOTH" if e1>e2: return "FIRST" return "SECOND" t=int(input()) for i in range(t): print(f())
train
APPS_structured
## Task Complete the function that receives an array of strings (`arr`) as an argument and returns all the valid Roman numerals. Basic Roman numerals are denoted as: ``` I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 ``` For the purposes of this kata we will consider valid only the numbers in range 0 - 5000 (both exclusive) since numbers >= 5000 were written in a different way (you had to place a heavy bar over the numeral that meant it was multiplied with 1000). There are other ways of tackling this problem but the easiest is probably writing a Regular Expression. ### Let's break the problem down: To match a set of characters `/[1-9]/`(single digits) you should take into consideration the Roman numbers `I, II, III, IV, V, VI, VII, VIII, IX`. This could be done by testing with `/IX|IV|V?I{0,3}/`. This part `/I{0,3}/` matches `I, II or III` but we have a `V` appearing 0 or 1 times because of the `?` so `/V?I{0,3}/` would match `I,II,III,V,VI,VII or VIII`. However there is one flaw with this. Do you see it? It is the fact that it would also match an empty string `""` because of the {0,3}. In order to pass the tests you will have to **filter out the empty strings** as well. So the entire part matches `I to IX`(inclusive) but what about larger digits? Use the same logic for the digit in the tens place and the hundreds place. Be sure to wrap each part (units, tens, hundreds, thousands) in a pair of braces `(IX|IV|V?I{0,3})` and for the digit in the thousands place the logic is pretty straight forward, you just have to match `M` 0 to 4 times (since 5000 is not included). Wrap everything up with `^` and `$` to make sure you match the entire string (^ matches from the beginning of the string, while $ denotes the end, meaning there is nothing after that sign. ## Examples ``` ["I", "IIV", "IVI", "IX", "XII", "MCD"] ==> ["I", "IX", "XII", "MCD"] ["MMMMCMXCIX", "MMDCXLIV", "MMCIX", "CLD", "LCD"]) ==> ["MMMMCMXCIX", "MMDCXLIV", "MMCIX"] ``` Good luck!
import re def valid_romans(arr): return [num for num in arr if num and re.match(r'^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$', num)]
import re def valid_romans(arr): return [num for num in arr if num and re.match(r'^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$', num)]
train
APPS_structured
In this Kata, you will be given an array of numbers and a number `n`, and your task will be to determine if `any` array elements, when summed (or taken individually), are divisible by `n`. For example: * `solve([1,3,4,7,6],9) == true`, because `3 + 6` is divisible by `9` * `solve([1,2,3,4,5],10) == true` for similar reasons. * `solve([8,5,3,9],7) == true`, because `7` evenly divides `5 + 9` * but `solve([8,5,3],7) == false`. All numbers in the array will be greater than `0`. More examples in the test cases. Good luck! If you like this Kata, please try: [Simple division](https://www.codewars.com/kata/59ec2d112332430ce9000005) [Divisor harmony](https://www.codewars.com/kata/59bf97cd4f98a8b1cd00007e)
solve=lambda a,n:any(sum(c)%n<1for r in range(len(a))for c in __import__('itertools').combinations(a,r+1))
solve=lambda a,n:any(sum(c)%n<1for r in range(len(a))for c in __import__('itertools').combinations(a,r+1))
train
APPS_structured
Create a program that will take in a string as input and, if there are duplicates of more than two alphabetical characters in the string, returns the string with all the extra characters in a bracket. For example, the input "aaaabbcdefffffffg" should return "aa[aa]bbcdeff[fffff]g" Please also ensure that the input is a string, and return "Please enter a valid string" if it is not.
def string_parse(string): if type(string)!=str:return "Please enter a valid string" try: out=string[:2] temp='' for i in string[2:]: if i==out[-1]==out[-2]: temp+=i else: if temp!='':out+='['+temp+']' out+=i temp='' if temp!='':out+='['+temp+']' return out except: return "Please enter a valid string"
def string_parse(string): if type(string)!=str:return "Please enter a valid string" try: out=string[:2] temp='' for i in string[2:]: if i==out[-1]==out[-2]: temp+=i else: if temp!='':out+='['+temp+']' out+=i temp='' if temp!='':out+='['+temp+']' return out except: return "Please enter a valid string"
train
APPS_structured
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid. Example 1: Input: "()" Output: true Example 2: Input: "()[]{}" Output: true Example 3: Input: "(]" Output: false Example 4: Input: "([)]" Output: false Example 5: Input: "{[]}" Output: true
class Solution: def isValid(self, s): """ :type s: str :rtype: bool """ if len(s)%2 != 0: return(False) stack=[] for i in range(len(s)): stack.append(s[i]) if stack[0] == ')' or stack[0] == ']' or stack[0] == '}': return(False) if stack[-1] == ')' : if stack[-2] =='(': stack.pop() stack.pop() elif stack[-1] == ']' : if stack[-2] =='[': stack.pop() stack.pop() elif stack[-1] == '}': if stack[-2] =='{': stack.pop() stack.pop() if stack == []: return(True) else: return(False)
class Solution: def isValid(self, s): """ :type s: str :rtype: bool """ if len(s)%2 != 0: return(False) stack=[] for i in range(len(s)): stack.append(s[i]) if stack[0] == ')' or stack[0] == ']' or stack[0] == '}': return(False) if stack[-1] == ')' : if stack[-2] =='(': stack.pop() stack.pop() elif stack[-1] == ']' : if stack[-2] =='[': stack.pop() stack.pop() elif stack[-1] == '}': if stack[-2] =='{': stack.pop() stack.pop() if stack == []: return(True) else: return(False)
train
APPS_structured
Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be available for the next player. This continues until all the scores have been chosen. The player with the maximum score wins. Given an array of scores, predict whether player 1 is the winner. You can assume each player plays to maximize his score. Example 1: Input: [1, 5, 2] Output: False Explanation: Initially, player 1 can choose between 1 and 2. If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. Hence, player 1 will never be the winner and you need to return False. Example 2: Input: [1, 5, 233, 7] Output: True Explanation: Player 1 first chooses 1. Then player 2 have to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win. Note: 1 Any scores in the given array are non-negative integers and will not exceed 10,000,000. If the scores of both players are equal, then player 1 is still the winner.
class Solution: def PredictTheWinner(self, nums): cache = {} def whose_turn(i, j): return (len(nums) - (j - i + 1)) % 2 == 0 def traverse(i, j): if (i, j) in cache: return cache[(i, j)] p1_turn = whose_turn(i, j) if i == j: return (nums[i], 0) if p1_turn else (0, nums[i]) if i + 1 == j: winning_move = max(nums[i], nums[j]) losing_move = min(nums[i], nums[j]) cache[(i, j)] = (winning_move, losing_move) if p1_turn else (losing_move, winning_move) return cache[(i, j)] p1_left, p2_left = traverse(i + 1, j) p1_right, p2_right = traverse(i, j - 1) if p1_turn: p1_move = max(p1_left + nums[i], p1_right + nums[j]) p2_move = p2_left if p1_left + nums[i] >= p1_right + nums[j] else p2_right else: p1_move = p1_left if p2_left + nums[i] >= p2_right + nums[j] else p1_right p2_move = max(p2_left + nums[i], p2_right + nums[j]) cache[(i, j)] = (p1_move, p2_move) return cache[(i, j)] p1_final, p2_final = traverse(0, len(nums) - 1) return p1_final >= p2_final
class Solution: def PredictTheWinner(self, nums): cache = {} def whose_turn(i, j): return (len(nums) - (j - i + 1)) % 2 == 0 def traverse(i, j): if (i, j) in cache: return cache[(i, j)] p1_turn = whose_turn(i, j) if i == j: return (nums[i], 0) if p1_turn else (0, nums[i]) if i + 1 == j: winning_move = max(nums[i], nums[j]) losing_move = min(nums[i], nums[j]) cache[(i, j)] = (winning_move, losing_move) if p1_turn else (losing_move, winning_move) return cache[(i, j)] p1_left, p2_left = traverse(i + 1, j) p1_right, p2_right = traverse(i, j - 1) if p1_turn: p1_move = max(p1_left + nums[i], p1_right + nums[j]) p2_move = p2_left if p1_left + nums[i] >= p1_right + nums[j] else p2_right else: p1_move = p1_left if p2_left + nums[i] >= p2_right + nums[j] else p1_right p2_move = max(p2_left + nums[i], p2_right + nums[j]) cache[(i, j)] = (p1_move, p2_move) return cache[(i, j)] p1_final, p2_final = traverse(0, len(nums) - 1) return p1_final >= p2_final
train
APPS_structured
Our football team finished the championship. The result of each match look like "x:y". Results of all matches are recorded in the collection. For example: ```["3:1", "2:2", "0:1", ...]``` Write a function that takes such collection and counts the points of our team in the championship. Rules for counting points for each match: - if x>y - 3 points - if x<y - 0 point - if x=y - 1 point Notes: - there are 10 matches in the championship - 0 <= x <= 4 - 0 <= y <= 4
def points(games): return sum(3 if x > y else 0 if x < y else 1 for x, y in (score.split(":") for score in games))
def points(games): return sum(3 if x > y else 0 if x < y else 1 for x, y in (score.split(":") for score in games))
train
APPS_structured
One day Chef was playing with numbers. He loves Lowest Common Multiple (LCM) too much and he is a very curious guy. He always try to do new things. Now he want to make a large number with it. But he doesn't want to take too many numbers. He is willing to take only three numbers less than or equal to N (not necessarily distinct ) and from those three number he want get the maximum number by taking LCM of the numbers. As he is busy in playing some more tricks of maths, he assign this task to you. -----Input----- First line of input contains an integer t ( t<=1000 ), Number of test cases. t line follows an integer N -----Output----- Print t lines contains a single integer — the maximum possible LCM of three not necessarily distinct positive integers that are not greater than N. -----Constraints----- 1<= N <= 10^6 -----Example----- Input: 2 9 7 Output: 504 210 -----Explanation----- Example case 2. For the last example, we can chose numbers 7, 6, 5 and the LCM of them is 7•6•5 = 210. It is the maximum value we can get.
from fractions import gcd for testCases in range(eval(input())): n = eval(input()) if n == 1: print('1') elif n == 2: print('2') elif n == 3: print('6') else: c = n*(n-1) k = n - 2 while True: if gcd(k,n-1) == 1 and gcd(k,n) == 1: break k -= 1 d = (n-1)*(n - 2) k1 = n - 3 while True: if gcd(k1,n-1) == 1 and gcd(k1,n-2) == 1: break k1 -= 1 print(max(c*k,d*k1))
from fractions import gcd for testCases in range(eval(input())): n = eval(input()) if n == 1: print('1') elif n == 2: print('2') elif n == 3: print('6') else: c = n*(n-1) k = n - 2 while True: if gcd(k,n-1) == 1 and gcd(k,n) == 1: break k -= 1 d = (n-1)*(n - 2) k1 = n - 3 while True: if gcd(k1,n-1) == 1 and gcd(k1,n-2) == 1: break k1 -= 1 print(max(c*k,d*k1))
train
APPS_structured
You have a large electronic screen which can display up to $998244353$ decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of $7$ segments which can be turned on and off to compose different digits. The following picture describes how you can display all $10$ decimal digits: [Image] As you can see, different digits may require different number of segments to be turned on. For example, if you want to display $1$, you have to turn on $2$ segments of the screen, and if you want to display $8$, all $7$ segments of some place to display a digit should be turned on. You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than $n$ segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than $n$ segments. Your program should be able to process $t$ different test cases. -----Input----- The first line contains one integer $t$ ($1 \le t \le 100$) — the number of test cases in the input. Then the test cases follow, each of them is represented by a separate line containing one integer $n$ ($2 \le n \le 10^5$) — the maximum number of segments that can be turned on in the corresponding testcase. It is guaranteed that the sum of $n$ over all test cases in the input does not exceed $10^5$. -----Output----- For each test case, print the greatest integer that can be displayed by turning on no more than $n$ segments of the screen. Note that the answer may not fit in the standard $32$-bit or $64$-bit integral data type. -----Example----- Input 2 3 4 Output 7 11
t=int(input()) for _ in range(t): n=int(input()) if n%2==0: x=n//2 for i in range(x): print(1,end='') else: x=n//2 x-=1 print(7,end='') for i in range(x): print(1,end='') print()
t=int(input()) for _ in range(t): n=int(input()) if n%2==0: x=n//2 for i in range(x): print(1,end='') else: x=n//2 x-=1 print(7,end='') for i in range(x): print(1,end='') print()
train
APPS_structured
In mathematics, a [Diophantine equation](https://en.wikipedia.org/wiki/Diophantine_equation) is a polynomial equation, usually with two or more unknowns, such that only the integer solutions are sought or studied. In this kata we want to find all integers `x, y` (`x >= 0, y >= 0`) solutions of a diophantine equation of the form: #### x^(2) - 4 \* y^(2) = n (where the unknowns are `x` and `y`, and `n` is a given positive number) in decreasing order of the positive xi. If there is no solution return `[]` or `"[]" or ""`. (See "RUN SAMPLE TESTS" for examples of returns). ## Examples: ``` solEquaStr(90005) --> "[[45003, 22501], [9003, 4499], [981, 467], [309, 37]]" solEquaStr(90002) --> "[]" ``` ## Hint: x^(2) - 4 \* y^(2) = (x - 2\*y) \* (x + 2\*y)
import math def sol_equa(n): res = [] for i in range(1, int(math.sqrt(n)) + 1): if n % i == 0: j = n // i if (i + j) % 2 == 0 and (j - i) % 4 == 0: x = (i + j) // 2 y = (j - i) // 4 res.append([x, y]) return res
import math def sol_equa(n): res = [] for i in range(1, int(math.sqrt(n)) + 1): if n % i == 0: j = n // i if (i + j) % 2 == 0 and (j - i) % 4 == 0: x = (i + j) // 2 y = (j - i) // 4 res.append([x, y]) return res
train
APPS_structured
A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules: For 1-byte character, the first bit is a 0, followed by its unicode code. For n-bytes character, the first n-bits are all one's, the n+1 bit is 0, followed by n-1 bytes with most significant 2 bits being 10. This is how the UTF-8 encoding would work: Char. number range | UTF-8 octet sequence (hexadecimal) | (binary) --------------------+--------------------------------------------- 0000 0000-0000 007F | 0xxxxxxx 0000 0080-0000 07FF | 110xxxxx 10xxxxxx 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx Given an array of integers representing the data, return whether it is a valid utf-8 encoding. Note: The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data. Example 1: data = [197, 130, 1], which represents the octet sequence: 11000101 10000010 00000001. Return true. It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character. Example 2: data = [235, 140, 4], which represented the octet sequence: 11101011 10001100 00000100. Return false. The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character. The next byte is a continuation byte which starts with 10 and that's correct. But the second continuation byte does not start with 10, so it is invalid.
class Solution: def validUtf8(self, data): """ :type data: List[int] :rtype: bool """ count=0 for x in data: if count==0: if x>>5==0b110: count=1 elif x>>4==0b1110: count=2 elif x>>3==0b11110: count=3 elif x>>7==1: return False else: if x>>6!=0b10: return False count-=1 return count==0 # class Solution { # public: # bool validUtf8(vector<int>& data) { # int cnt = 0; # for (int d : data) { # if (cnt == 0) { # if ((d >> 5) == 0b110) cnt = 1; # else if ((d >> 4) == 0b1110) cnt = 2; # else if ((d >> 3) == 0b11110) cnt = 3; # else if (d >> 7) return false; # } else { # if ((d >> 6) != 0b10) return false; # --cnt; # } # } # return cnt == 0; # } # };
class Solution: def validUtf8(self, data): """ :type data: List[int] :rtype: bool """ count=0 for x in data: if count==0: if x>>5==0b110: count=1 elif x>>4==0b1110: count=2 elif x>>3==0b11110: count=3 elif x>>7==1: return False else: if x>>6!=0b10: return False count-=1 return count==0 # class Solution { # public: # bool validUtf8(vector<int>& data) { # int cnt = 0; # for (int d : data) { # if (cnt == 0) { # if ((d >> 5) == 0b110) cnt = 1; # else if ((d >> 4) == 0b1110) cnt = 2; # else if ((d >> 3) == 0b11110) cnt = 3; # else if (d >> 7) return false; # } else { # if ((d >> 6) != 0b10) return false; # --cnt; # } # } # return cnt == 0; # } # };
train
APPS_structured
There are n cards of different colours placed in a line, each of them can be either red, green or blue cards. Count the minimum number of cards to withdraw from the line so that no two adjacent cards have the same colour. -----Input----- - The first line of each input contains an integer n— the total number of cards. - The next line of the input contains a string s, which represents the colours of the cards. We'll consider the cards in a line numbered from 1 to n from left to right. Then the $i^t$$^h$ alphabet equals "G", if the $i^t$$^h$ card is green, "R" if the card is red, and "B", if it's blue. -----Output----- - Print a single integer — the answer to the problem. -----Constraints----- - $1 \leq n \leq 50$ -----Sample Input 1:----- 5 RGGBG -----Sample Input 2:----- 5 RRRRR -----Sample Input 3:----- 2 BB -----Sample Output 1:----- 1 -----Sample Output 2:----- 4 -----Sample Output 3:----- 1
# cook your dish here n=int(input()) string1=input() count=0 if(n==1): print(0) else: for i in range(len(string1)-1): if(string1[i+1]==string1[i]): count+=1 print(count)
# cook your dish here n=int(input()) string1=input() count=0 if(n==1): print(0) else: for i in range(len(string1)-1): if(string1[i+1]==string1[i]): count+=1 print(count)
train
APPS_structured
There are N towns on a line running east-west. The towns are numbered 1 through N, in order from west to east. Each point on the line has a one-dimensional coordinate, and a point that is farther east has a greater coordinate value. The coordinate of town i is X_i. You are now at town 1, and you want to visit all the other towns. You have two ways to travel: - Walk on the line. Your fatigue level increases by A each time you travel a distance of 1, regardless of direction. - Teleport to any location of your choice. Your fatigue level increases by B, regardless of the distance covered. Find the minimum possible total increase of your fatigue level when you visit all the towns in these two ways. -----Constraints----- - All input values are integers. - 2≤N≤10^5 - 1≤X_i≤10^9 - For all i(1≤i≤N-1), X_i<X_{i+1}. - 1≤A≤10^9 - 1≤B≤10^9 -----Input----- The input is given from Standard Input in the following format: N A B X_1 X_2 ... X_N -----Output----- Print the minimum possible total increase of your fatigue level when you visit all the towns. -----Sample Input----- 4 2 5 1 2 5 7 -----Sample Output----- 11 From town 1, walk a distance of 1 to town 2, then teleport to town 3, then walk a distance of 2 to town 4. The total increase of your fatigue level in this case is 2×1+5+2×2=11, which is the minimum possible value.
n, a, b = map(int, input().split()) x = list(map(int, input().split())) ans = 0 now = x[0] for xx in x[1:]: ans += min((xx-now)*a, b) now = xx print(ans)
n, a, b = map(int, input().split()) x = list(map(int, input().split())) ans = 0 now = x[0] for xx in x[1:]: ans += min((xx-now)*a, b) now = xx print(ans)
train
APPS_structured
In the spirit of the holidays, Saitama has given Genos two grid paths of length n (a weird gift even by Saitama's standards). A grid path is an ordered sequence of neighbouring squares in an infinite grid. Two squares are neighbouring if they share a side. One example of a grid path is (0, 0) → (0, 1) → (0, 2) → (1, 2) → (1, 1) → (0, 1) → ( - 1, 1). Note that squares in this sequence might be repeated, i.e. path has self intersections. Movement within a grid path is restricted to adjacent squares within the sequence. That is, from the i-th square, one can only move to the (i - 1)-th or (i + 1)-th squares of this path. Note that there is only a single valid move from the first and last squares of a grid path. Also note, that even if there is some j-th square of the path that coincides with the i-th square, only moves to (i - 1)-th and (i + 1)-th squares are available. For example, from the second square in the above sequence, one can only move to either the first or third squares. To ensure that movement is not ambiguous, the two grid paths will not have an alternating sequence of three squares. For example, a contiguous subsequence (0, 0) → (0, 1) → (0, 0) cannot occur in a valid grid path. One marble is placed on the first square of each grid path. Genos wants to get both marbles to the last square of each grid path. However, there is a catch. Whenever he moves one marble, the other marble will copy its movement if possible. For instance, if one marble moves east, then the other marble will try and move east as well. By try, we mean if moving east is a valid move, then the marble will move east. Moving north increases the second coordinate by 1, while moving south decreases it by 1. Similarly, moving east increases first coordinate by 1, while moving west decreases it. Given these two valid grid paths, Genos wants to know if it is possible to move both marbles to the ends of their respective paths. That is, if it is possible to move the marbles such that both marbles rest on the last square of their respective paths. -----Input----- The first line of the input contains a single integer n (2 ≤ n ≤ 1 000 000) — the length of the paths. The second line of the input contains a string consisting of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W') — the first grid path. The characters can be thought of as the sequence of moves needed to traverse the grid path. For example, the example path in the problem statement can be expressed by the string "NNESWW". The third line of the input contains a string of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W') — the second grid path. -----Output----- Print "YES" (without quotes) if it is possible for both marbles to be at the end position at the same time. Print "NO" (without quotes) otherwise. In both cases, the answer is case-insensitive. -----Examples----- Input 7 NNESWW SWSWSW Output YES Input 3 NN SS Output NO -----Note----- In the first sample, the first grid path is the one described in the statement. Moreover, the following sequence of moves will get both marbles to the end: NNESWWSWSW. In the second sample, no sequence of moves can get both marbles to the end.
from time import time opposite = { 'N': 'S', 'S': 'N', 'E': 'W', 'W': 'E' } otr = str.maketrans(opposite) bits = { 'N': 0, 'S': 1, 'E': 2, 'W': 3, } Q = 4294967291 def combine(h, v, q): return (h<<2 | v) % q def combinel(h, v, q, s): return (v*s + h) % q def flip(s): return ''.join(reversed(s.translate(otr))) def solvable(p1, p2): h1 = 0 h2 = 0 s = 1 for i in reversed(list(range(len(p1)))): n1 = bits[p1[i]] n2 = bits[opposite[p2[i]]] h1 = combine(h1, n1, Q) h2 = combinel(h2, n2, Q, s) if h1 == h2 and p1[i:] == flip(p2[i:]): return False s = (s<<2) % Q return True def __starting_point(): n = int(input()) p1 = input() p2 = input() print('YES' if solvable(p1, p2) else 'NO') __starting_point()
from time import time opposite = { 'N': 'S', 'S': 'N', 'E': 'W', 'W': 'E' } otr = str.maketrans(opposite) bits = { 'N': 0, 'S': 1, 'E': 2, 'W': 3, } Q = 4294967291 def combine(h, v, q): return (h<<2 | v) % q def combinel(h, v, q, s): return (v*s + h) % q def flip(s): return ''.join(reversed(s.translate(otr))) def solvable(p1, p2): h1 = 0 h2 = 0 s = 1 for i in reversed(list(range(len(p1)))): n1 = bits[p1[i]] n2 = bits[opposite[p2[i]]] h1 = combine(h1, n1, Q) h2 = combinel(h2, n2, Q, s) if h1 == h2 and p1[i:] == flip(p2[i:]): return False s = (s<<2) % Q return True def __starting_point(): n = int(input()) p1 = input() p2 = input() print('YES' if solvable(p1, p2) else 'NO') __starting_point()
train
APPS_structured
Theory This section does not need to be read and can be skipped, but it does provide some clarity into the inspiration behind the problem. In music theory, a major scale consists of seven notes, or scale degrees, in order (with tonic listed twice for demonstrative purposes): Tonic, the base of the scale and the note the scale is named after (for example, C is the tonic note of the C major scale) Supertonic, 2 semitones (or one tone) above the tonic Mediant, 2 semitones above the supertonic and 4 above the tonic Subdominant, 1 semitone above the median and 5 above the tonic Dominant, 2 semitones above the subdominant and 7 above the tonic Submediant, 2 semitones above the dominant and 9 above the tonic Leading tone, 2 semitones above the mediant and 11 above the tonic Tonic (again!), 1 semitone above the leading tone and 12 semitones (or one octave) above the tonic An octave is an interval of 12 semitones, and the pitch class of a note consists of any note that is some integer number of octaves apart from that note. Notes in the same pitch class sound different but share similar properties. If a note is in a major scale, then any note in that note's pitch class is also in that major scale. Problem Using integers to represent notes, the major scale of an integer note will be an array (or list) of integers that follows the major scale pattern note, note + 2, note + 4, note + 5, note + 7, note + 9, note + 11. For example, the array of integers [1, 3, 5, 6, 8, 10, 12] is the major scale of 1. Secondly, the pitch class of a note will be the set of all integers some multiple of 12 above or below the note. For example, 1, 13, and 25 are all in the same pitch class. Thirdly, an integer note1 is considered to be in the key of an integer note2 if note1, or some integer in note1's pitch class, is in the major scale of note2. More mathematically, an integer note1 is in the key of an integer note2 if there exists an integer i such that note1 + i × 12 is in the major scale of note2. For example, 22 is in the key of of 1 because, even though 22 is not in 1's major scale ([1, 3, 5, 6, 8, 10, 12]), 10 is and is also a multiple of 12 away from 22. Likewise, -21 is also in the key of 1 because -21 + (2 × 12) = 3 and 3 is present in the major scale of 1. An array is in the key of an integer if all its elements are in the key of the integer. Your job is to create a function is_tune that will return whether or not an array (or list) of integers is a tune. An array will be considered a tune if there exists a single integer note all the integers in the array are in the key of. The function will accept an array of integers as its parameter and return True if the array is a tune or False otherwise. Empty and null arrays are not considered to be tunes. Additionally, the function should not change the input array. Examples ```python is_tune([1, 3, 6, 8, 10, 12]) # Returns True, all the elements are in the major scale # of 1 ([1, 3, 5, 6, 8, 10, 12]) and so are in the key of 1. is_tune([1, 3, 6, 8, 10, 12, 13, 15]) # Returns True, 14 and 15 are also in the key of 1 as # they are in the major scale of 13 which is in the pitch class of 1 (13 = 1 + 12 * 1). is_tune([1, 6, 3]) # Returns True, arrays don't need to be sorted. is_tune([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) # Returns False, this array is not in the # key of any integer. is_tune([2, 4, 7, 9, 11, 13]) # Returns True, the array is in the key of 2 (the arrays # don't need to be in the key of 1, just some integer) ```
D_TUNE = {0,2,4,5,7,9,11} def is_tune(notes): return bool(notes) and any({(n-v)%12 for v in notes} <= D_TUNE for n in range (12))
D_TUNE = {0,2,4,5,7,9,11} def is_tune(notes): return bool(notes) and any({(n-v)%12 for v in notes} <= D_TUNE for n in range (12))
train
APPS_structured
Kabir wants to impress Tara by showing her his problem solving skills. He has decided to give the correct answer to the next question which will be asked by his Algorithms teacher. The question asked is: Find the sum of alternate consecutive d$d$ odd numbers from the range L$L$ to R$R$ inclusive. if d$d$ is 3 and L$L$ is 10 and R$R$ is 34, then the odd numbers between 10 and 34 are 11,13,15,17,19,21,23,25,27,29,31,33$11,13,15,17,19,21,23,25,27,29,31,33$, and the d$d$ alternate odd numbers are 11,13,15,23,25,27$11,13,15,23,25,27$. You are a friend of Kabir, help him solve the question. Note:$Note:$ Number of odd number between L$L$ and R$R$ (both inclusive) is a multiple of d$d$. -----Input:----- - First line will contain T$T$, number of test cases. - First line of each test case contains one integer d$d$ . - Second line of each test case contains two space separated integer L$L$ and R$R$. -----Output:----- For each test case, print the sum modulo 1000000007. -----Constraints:----- - 1≤T≤106$1 \leq T \leq 10^6$ - 1≤d≤103$1 \leq d \leq 10^3$ - 1≤L<R≤106$1 \leq L < R \leq 10^6$ -----Sample Input:----- 1 3 10 33 -----Sample Output:----- 114 -----EXPLANATION:----- Sum of alternate odd numbers i.e, 11,13,15,23,25,27 is 114
# cook your dish here t=int(input()) while t>0 : d=int(input()) l,r=map(int,input().split()) if l%2==1 and r%2==1 : num=(r-l)//2+1 elif l%2==1 or r%2==1 : num=(r-l+1)//2 else : num=(r-l)//2 if l%2==0 : l=l+1 if(num%(2*d)==0) : n=num//(2*d) else : n=num//(2*d)+1 init=l*d+ d*(d-1) su=n*init su=su+2*d*d*n*(n-1) print(su%1000000007) t=t-1
# cook your dish here t=int(input()) while t>0 : d=int(input()) l,r=map(int,input().split()) if l%2==1 and r%2==1 : num=(r-l)//2+1 elif l%2==1 or r%2==1 : num=(r-l+1)//2 else : num=(r-l)//2 if l%2==0 : l=l+1 if(num%(2*d)==0) : n=num//(2*d) else : n=num//(2*d)+1 init=l*d+ d*(d-1) su=n*init su=su+2*d*d*n*(n-1) print(su%1000000007) t=t-1
train
APPS_structured
Find the first character that repeats in a String and return that character. ```python first_dup('tweet') => 't' first_dup('like') => None ``` *This is not the same as finding the character that repeats first.* *In that case, an input of 'tweet' would yield 'e'.*
def first_dup(stg): return next((c for c in stg if stg.count(c) > 1), None)
def first_dup(stg): return next((c for c in stg if stg.count(c) > 1), None)
train
APPS_structured
# Description You are required to implement a function `find_nth_occurrence` that returns the index of the nth occurrence of a substring within a string (considering that those substring could overlap each others). If there are less than n occurrences of the substring, return -1. # Example ```python string = "This is an example. Return the nth occurrence of example in this example string." find_nth_occurrence("example", string, 1) == 11 find_nth_occurrence("example", string, 2) == 49 find_nth_occurrence("example", string, 3) == 65 find_nth_occurrence("example", string, 4) == -1 ``` Multiple occurrences of a substring are allowed to overlap, e.g. ```python find_nth_occurrence("TestTest", "TestTestTestTest", 1) == 0 find_nth_occurrence("TestTest", "TestTestTestTest", 2) == 4 find_nth_occurrence("TestTest", "TestTestTestTest", 3) == 8 find_nth_occurrence("TestTest", "TestTestTestTest", 4) == -1 ```
import re def find_nth_occurrence(sb, s, n=1): r = list(re.finditer('(?='+sb+')', s)) return r[n-1].span()[0] if n<=len(r) else -1
import re def find_nth_occurrence(sb, s, n=1): r = list(re.finditer('(?='+sb+')', s)) return r[n-1].span()[0] if n<=len(r) else -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:----- 12 21 123 231 312 1234 2341 3412 4123 -----EXPLANATION:----- No need, else pattern can be decode easily.
for tc in range(int(input())): K = int(input()) S = [str(i) for i in range(1, K + 1)] for i in range(K): print(''.join(S)) S = S[1:] + [S[0]]
for tc in range(int(input())): K = int(input()) S = [str(i) for i in range(1, K + 1)] for i in range(K): print(''.join(S)) S = S[1:] + [S[0]]
train
APPS_structured
Given an array of integers, find the one that appears an odd number of times. There will always be only one integer that appears an odd number of times.
def find_it(seq): for elem in set(seq): if seq.count(elem) % 2 == 1: return elem
def find_it(seq): for elem in set(seq): if seq.count(elem) % 2 == 1: return elem
train
APPS_structured
# Task Given an integer `n`, find the maximal number you can obtain by deleting exactly one digit of the given number. # Example For `n = 152`, the output should be `52`; For `n = 1001`, the output should be `101`. # Input/Output - `[input]` integer `n` Constraints: `10 ≤ n ≤ 1000000.` - `[output]` an integer
from itertools import combinations def delete_digit(n): return max(int(''.join(i)) for i in list(combinations(str(n),len(str(n))-1)))
from itertools import combinations def delete_digit(n): return max(int(''.join(i)) for i in list(combinations(str(n),len(str(n))-1)))
train
APPS_structured
You're a statistics professor and the deadline for submitting your students' grades is tonight at midnight. Each student's grade is determined by their mean score across all of the tests they took this semester. You've decided to automate grade calculation by writing a function `calculate_grade()` that takes a list of test scores as an argument and returns a one character string representing the student's grade calculated as follows: * 90% <= mean score <= 100%: `"A"`, * 80% <= mean score < 90%: `"B"`, * 70% <= mean score < 80%: `"C"`, * 60% <= mean score < 70%: `"D"`, * mean score < 60%: `"F"` For example, `calculate_grade([92, 94, 99])` would return `"A"` since the mean score is `95`, and `calculate_grade([50, 60, 70, 80, 90])` would return `"C"` since the mean score is `70`. Your function should handle an input list of any length greater than zero.
def calculate_grade(scores): s = sum(scores) / len(scores) return 'ABCDF'[(s < 90) + (s < 80) + (s < 70) + (s < 60)]
def calculate_grade(scores): s = sum(scores) / len(scores) return 'ABCDF'[(s < 90) + (s < 80) + (s < 70) + (s < 60)]
train
APPS_structured
You are given a permutation of natural integers from 1 to N, inclusive. Initially, the permutation is 1, 2, 3, ..., N. You are also given M pairs of integers, where the i-th is (Li Ri). In a single turn you can choose any of these pairs (let's say with the index j) and arbitrarily shuffle the elements of our permutation on the positions from Lj to Rj, inclusive (the positions are 1-based). You are not limited in the number of turns and you can pick any pair more than once. The goal is to obtain the permutation P, that is given to you. If it's possible, output "Possible", otherwise output "Impossible" (without quotes). -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains two space separated integers N and M denoting the size of the permutation P and the number of pairs described above. The next line contains N integers - the permutation P. Each of the following M lines contain pair of integers Li and Ri. -----Output----- For each test case, output a single line containing the answer to the corresponding test case. -----Constraints----- - 1 ≤ T ≤ 35 - 1 ≤ N, M ≤ 100000 - 1 ≤ Li ≤ Ri ≤ N -----Example----- Input: 2 7 4 3 1 2 4 5 7 6 1 2 4 4 6 7 2 3 4 2 2 1 3 4 2 4 2 3 Output: Possible Impossible
t=int(input()) for _ in range(t): n,m=list(map(int,input().split())) l=list(map(int,input().split())) k=[] for i in range(m): a,b=list(map(int,input().split())) k.append([a,b]) k.sort() c=[] flag=1 x=k[0][0] y=k[0][1] for i in k[1:]: if i[0]<=y: y=max(y,i[1]) else: c.append([x-1,y-1]) x=i[0] y=i[1] c.append([x-1,y-1]) m=[] j=0 for i in c: while j<i[0]: m.append(l[j]) j+=1 x=l[i[0]:i[1]+1] m+=sorted(x) j=i[1]+1 while j<n: m.append(l[j]) j+=1 if m==sorted(l): print('Possible') else: print('Impossible')
t=int(input()) for _ in range(t): n,m=list(map(int,input().split())) l=list(map(int,input().split())) k=[] for i in range(m): a,b=list(map(int,input().split())) k.append([a,b]) k.sort() c=[] flag=1 x=k[0][0] y=k[0][1] for i in k[1:]: if i[0]<=y: y=max(y,i[1]) else: c.append([x-1,y-1]) x=i[0] y=i[1] c.append([x-1,y-1]) m=[] j=0 for i in c: while j<i[0]: m.append(l[j]) j+=1 x=l[i[0]:i[1]+1] m+=sorted(x) j=i[1]+1 while j<n: m.append(l[j]) j+=1 if m==sorted(l): print('Possible') else: print('Impossible')
train
APPS_structured
This Kata is a continuation of [Part 1](http://www.codewars.com/kata/the-fusc-function-part-1). The `fusc` function is defined recursively as follows: fusc(0) = 0 fusc(1) = 1 fusc(2n) = fusc(n) fusc(2n + 1) = fusc(n) + fusc(n + 1) Your job is to produce the code for the `fusc` function. In this kata, your function will be tested with large values of `n` more than 1000 bits (in JS and PHP: at most 52 bits), so you should be concerned about stack overflow and timeouts. Method suggestion: Imagine that instead of `fusc(n)`, you were to implement `fib(n)`, which returns the n'th Fibonacci number. The function is recursively defined by: ``` 1. fib(0) = 1 2. fib(1) = 1 3. fib(n + 2) = fib(n) + fib(n + 1), if n + 2 > 1 ``` If one translates the above definition directly into a recursive function, the result is not very efficient. One can try memoization, but that requires lots of space and is not necessary. So, first step is to try and find a _tail recursive_ definition. In order to do that we try to write both sides of equation 3) on the same form. Currently, the left side of the equation contains a single term, whereas the right side is the sum of two terms. A first attempt is to add `fib(n + 1)` to both sides of the equation: ``` 3. fib(n + 1) + fib(n + 2) = fib(n) + 2 * fib(n + 1) ``` The two sides of the equation look much more alike, but there is still an essential difference, which is the coefficient of the second term of each side. On the left side of the equation, it is `1` and, on the right, it is `2`. To remedy this, we can introduce a variable `b`: ``` 3. fib(n + 1) + b * fib(n + 2) = b * fib(n) + (b + 1) * fib(n + 1) ``` We notice that the coefficients of the first term are not the same (`1` on the left and `b` on the right), so we introduce a variable `a`: ``` 3. a * fib(n + 1) + b * fib(n + 2) = b * fib(n) + (a + b) * fib(n + 1) ``` Now the two sides have the same form (call it `F`), which we can define as: ```F(a, b, n) = a * fib(n) + b * fib(n + 1)``` In fact, we can write equation 3) as: ``` 3. F(a, b, n + 1) = F(b, a + b, n) ``` We also have, by definition of `F` and `fib`: ``` 4. F(a, b, 0) = a * fib(0) + b * fib(1) = a + b ``` Also, by definition of `F`: ``` 5. fib(n) = F(1, 0, n) ``` The next step is to translate the above into code: ``` def fib(n): def F(a, b, n): if n == 0: return a + b # see 4. above return F(b, a + b, n - 1) # see 3. above return F(1, 0, n) # see 5. above ``` The final step (optional for languages that support tail call optimization) is to replace the tail recursive function `F` with a loop: ``` def fib(n): a, b = 1, 0 # see 5. above while n > 0: a, b, n = b, a + b, n - 1 # see 3. above return a + b . # see 4. above ``` Voila! Now, go do the same with `fusc`.
def fusc(n): a, b = 0, 1 while n: if n & 1: a += b else: b += a n >>= 1 return a
def fusc(n): a, b = 0, 1 while n: if n & 1: a += b else: b += a n >>= 1 return a
train
APPS_structured
Define a method that accepts 2 strings as parameters. The method returns the first string sorted by the second. ```python sort_string("foos", "of") == "oofs" sort_string("string", "gnirts") == "gnirts" sort_string("banana", "abn") == "aaabnn" ``` To elaborate, the second string defines the ordering. It is possible that in the second string characters repeat, so you should remove repeating characters, leaving only the first occurrence. Any character in the first string that does not appear in the second string should be sorted to the end of the result in original order.
def sort_string(s, ordering): dct = {c:-i for i,c in enumerate(reversed(ordering))} return ''.join(sorted(s,key=lambda c:dct.get(c,1)))
def sort_string(s, ordering): dct = {c:-i for i,c in enumerate(reversed(ordering))} return ''.join(sorted(s,key=lambda c:dct.get(c,1)))
train
APPS_structured
Given a number `n` we will define its scORe to be `0 | 1 | 2 | 3 | ... | n`, where `|` is the [bitwise OR operator](https://en.wikipedia.org/wiki/Bitwise_operation#OR). Write a function that takes `n` and finds its scORe. --------------------- | n | scORe n | |---------|-------- | | 0 | 0 | | 1 | 1 | | 49 | 63 | | 1000000 | 1048575 |
from math import log; score=lambda n: 2**int(1+log(n,2))-1 if n else 0
from math import log; score=lambda n: 2**int(1+log(n,2))-1 if n else 0
train
APPS_structured
Chef has many friends, but his best friend is Hemant. They both love to watch anime. In fact, their weekends are meant for that only. Also, Hemant is highly into games, of which Chef is unaware. Hemant once gave a game to Chef and asked him to determine the winner of the game. Since the Chef is busy, and you are also his friend, he asked you to help him. The Game is played between two players, $A$ and $B$. There are $N$ marbles. $A$ and $B$ plays alternately, and $A$ goes first. Each player can choose $1$ marble or $even$ number of marbles in his turn. The player who is not able to choose any marbles loses the game. -----Input:----- - The first line consists of a single integer $T$ denoting the number of test cases. - The Second line contains an integers $N$, denoting the number of marbles. -----Output:----- For each test case, print the name of the player who loses the game. -----Constraints----- - $1 \leq T \leq 10^5$ - $1 \leq N \leq 10^9$ -----Sample Input:----- 3 1 3 7 -----Sample Output:----- B A B
# cook your dish here for _ in range(int(input())): n=int(input()) if(n==1 or n%2==0): print('B') continue elif(n==3): print('A') continue else: if((n-3)%2==0): print('B') else: print('A')
# cook your dish here for _ in range(int(input())): n=int(input()) if(n==1 or n%2==0): print('B') continue elif(n==3): print('A') continue else: if((n-3)%2==0): print('B') else: print('A')
train
APPS_structured
Complete the function which returns the weekday according to the input number: * `1` returns `"Sunday"` * `2` returns `"Monday"` * `3` returns `"Tuesday"` * `4` returns `"Wednesday"` * `5` returns `"Thursday"` * `6` returns `"Friday"` * `7` returns `"Saturday"` * Otherwise returns `"Wrong, please enter a number between 1 and 7"`
def whatday(num): dict={ 2:"Monday", 3:"Tuesday", 4:"Wednesday", 5:"Thursday", 6:"Friday", 7:"Saturday", 1:"Sunday" } return dict.get(num,'Wrong, please enter a number between 1 and 7')
def whatday(num): dict={ 2:"Monday", 3:"Tuesday", 4:"Wednesday", 5:"Thursday", 6:"Friday", 7:"Saturday", 1:"Sunday" } return dict.get(num,'Wrong, please enter a number between 1 and 7')
train
APPS_structured
The chef is trying to decode 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:----- 4 1 2 3 4 -----Sample Output:----- 1 12 3 123 45 6 1234 567 89 10 -----EXPLANATION:----- No need, else pattern can be decode easily.
t = int(input()) for _ in range(t): n = int(input()) count = 1 for i in range(n): for j in range(n-i): print(count,end='') count += 1 print()
t = int(input()) for _ in range(t): n = int(input()) count = 1 for i in range(n): for j in range(n-i): print(count,end='') count += 1 print()
train
APPS_structured
Find the difference between two collections. The difference means that either the character is present in one collection or it is present in other, but not in both. Return a sorted set with difference. The collections can contain any character and can contain duplicates. For instance: A = [a,a,t,e,f,i,j] B = [t,g,g,i,k,f] difference = [a,e,g,j,k]
# return a sorted set with the difference def diff(a, b): output = [] for elem in a: if elem not in b: output.append(elem) for elem in b: if elem not in a: output.append(elem) return sorted(list(set(output)))
# return a sorted set with the difference def diff(a, b): output = [] for elem in a: if elem not in b: output.append(elem) for elem in b: if elem not in a: output.append(elem) return sorted(list(set(output)))
train
APPS_structured
Mobile Display Keystrokes Do you remember the old mobile display keyboards? Do you also remember how inconvenient it was to write on it? Well, here you have to calculate how much keystrokes you have to do for a specific word. This is the layout: Return the amount of keystrokes of input str (! only letters, digits and special characters in lowercase included in layout without whitespaces !) e.g: mobileKeyboard("123") => 3 (1+1+1) mobileKeyboard("abc") => 9 (2+3+4) mobileKeyboard("codewars") => 26 (4+4+2+3+2+2+4+5)
count = {chr(n):2+i%3 for i,n in enumerate(range(ord('a'), ord('s')))} count.update( {chr(n):2+i%3 for i,n in enumerate(range(ord('t'), ord('z')))} ) count.update( {str(n)[-1]:1 for i,n in enumerate(range(1,11))} ) count.update( {'s':5, 'z':5, '*':1, '#':1} ) def mobile_keyboard(s): return sum(count[c] for c in s)
count = {chr(n):2+i%3 for i,n in enumerate(range(ord('a'), ord('s')))} count.update( {chr(n):2+i%3 for i,n in enumerate(range(ord('t'), ord('z')))} ) count.update( {str(n)[-1]:1 for i,n in enumerate(range(1,11))} ) count.update( {'s':5, 'z':5, '*':1, '#':1} ) def mobile_keyboard(s): return sum(count[c] for c in s)
train
APPS_structured
A high school has a strange principal. On the first day, he has his students perform an odd opening day ceremony: There are number of lockers "n" and number of students "n" in the school. The principal asks the first student to go to every locker and open it. Then he has the second student go to every second locker and close it. The third goes to every third locker and, if it is closed, he opens it, and if it is open, he closes it. The fourth student does this to every fourth locker, and so on. After the process is completed with the "n"th student, how many lockers are open? The task is to write a function which gets any number as an input and returns the number of open lockers after last sudent complets his activity. So input of the function is just one number which shows number of lockers and number of students. For example if there are 1000 lockers and 1000 students in school then input is 1000 and function returns number of open lockers after 1000th student completes his action. The given input is always an integer greater than or equal to zero that is why there is no need for validation.
def num_of_open_lockers(n): return int(n ** 0.5) #def num_of_open_lockers_not_opt(n): # nums = [] # for i in xrange(0, n): # nums.append(False) # # for i in xrange(1, n + 1): # for j in xrange(1, n + 1): # if j % i == 0: # nums[j - 1] = not nums[j - 1] # # return nums.count(True)
def num_of_open_lockers(n): return int(n ** 0.5) #def num_of_open_lockers_not_opt(n): # nums = [] # for i in xrange(0, n): # nums.append(False) # # for i in xrange(1, n + 1): # for j in xrange(1, n + 1): # if j % i == 0: # nums[j - 1] = not nums[j - 1] # # return nums.count(True)
train
APPS_structured
This is the hard version of the problem. The difference between the versions is the constraint on $n$ and the required number of operations. You can make hacks only if all versions of the problem are solved. There are two binary strings $a$ and $b$ of length $n$ (a binary string is a string consisting of symbols $0$ and $1$). In an operation, you select a prefix of $a$, and simultaneously invert the bits in the prefix ($0$ changes to $1$ and $1$ changes to $0$) and reverse the order of the bits in the prefix. For example, if $a=001011$ and you select the prefix of length $3$, it becomes $011011$. Then if you select the entire string, it becomes $001001$. Your task is to transform the string $a$ into $b$ in at most $2n$ operations. It can be proved that it is always possible. -----Input----- The first line contains a single integer $t$ ($1\le t\le 1000$)  — the number of test cases. Next $3t$ lines contain descriptions of test cases. The first line of each test case contains a single integer $n$ ($1\le n\le 10^5$)  — the length of the binary strings. The next two lines contain two binary strings $a$ and $b$ of length $n$. It is guaranteed that the sum of $n$ across all test cases does not exceed $10^5$. -----Output----- For each test case, output an integer $k$ ($0\le k\le 2n$), followed by $k$ integers $p_1,\ldots,p_k$ ($1\le p_i\le n$). Here $k$ is the number of operations you use and $p_i$ is the length of the prefix you flip in the $i$-th operation. -----Example----- Input 5 2 01 10 5 01011 11100 2 01 01 10 0110011011 1000110100 1 0 1 Output 3 1 2 1 6 5 2 5 3 1 2 0 9 4 1 2 10 4 1 2 1 5 1 1 -----Note----- In the first test case, we have $01\to 11\to 00\to 10$. In the second test case, we have $01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100$. In the third test case, the strings are already the same. Another solution is to flip the prefix of length $2$, which will leave $a$ unchanged.
import sys input = sys.stdin.readline from collections import deque t=int(input()) for tests in range(t): n=int(input()) a=input().strip() b=input().strip() Q=deque(a) L=[] while Q: L.append(Q.popleft()) if Q: L.append(Q.pop()) ANS=[] for i in range(n): if i%2==0: if L[i]==b[-1-i]: ANS.append(1) else: if L[i]!=b[-1-i]: ANS.append(1) ANS.append(n-i) print(len(ANS),*ANS)
import sys input = sys.stdin.readline from collections import deque t=int(input()) for tests in range(t): n=int(input()) a=input().strip() b=input().strip() Q=deque(a) L=[] while Q: L.append(Q.popleft()) if Q: L.append(Q.pop()) ANS=[] for i in range(n): if i%2==0: if L[i]==b[-1-i]: ANS.append(1) else: if L[i]!=b[-1-i]: ANS.append(1) ANS.append(n-i) print(len(ANS),*ANS)
train
APPS_structured
Find sum of all the numbers that are multiples of 10 and are less than or equal to a given number "N". (quotes for clarity and be careful of integer overflow) -----Input----- Input will start with an integer T the count of test cases, each case will have an integer N. -----Output----- Output each values, on a newline. -----Constraints----- - 1 ≤ T ≤ 10 - 1 ≤ N ≤1000000000 -----Example----- Input: 1 10 Output: 10 -----Explanation----- Example case 1. Only integer that is multiple 10 that is less than or equal to 10 is 10
t=int(input()) while t: n=int(input()) t-=1 r=n/10 r=10*(r*(r+1))/2 print(r)
t=int(input()) while t: n=int(input()) t-=1 r=n/10 r=10*(r*(r+1))/2 print(r)
train
APPS_structured
Imagine two rings with numbers on them. The inner ring spins clockwise (decreasing by 1 each spin) and the outer ring spins counter clockwise (increasing by 1 each spin). We start with both rings aligned on 0 at the top, and on each move we spin each ring one increment. How many moves will it take before both rings show the same number at the top again? The inner ring has integers from 0 to innerMax and the outer ring has integers from 0 to outerMax, where innerMax and outerMax are integers >= 1. ``` e.g. if innerMax is 2 and outerMax is 3 then after 1 move: inner = 2, outer = 1 2 moves: inner = 1, outer = 2 3 moves: inner = 0, outer = 3 4 moves: inner = 2, outer = 0 5 moves: inner = 1, outer = 1 Therefore it takes 5 moves for the two rings to reach the same number Therefore spinningRings(2, 3) = 5 ``` ``` e.g. if innerMax is 3 and outerMax is 2 then after 1 move: inner = 3, outer = 1 2 moves: inner = 2, outer = 2 Therefore it takes 2 moves for the two rings to reach the same number spinningRings(3, 2) = 2 ``` --- for a bigger challenge, check out the [Performance Version](https://www.codewars.com/kata/59b0b7cd2a00d219ab0000c5) of this kata by @Voile
def spinning_rings(inner_max, outer_max): inner, outer = 0, 0 while True: inner -= 1 outer += 1 if inner % (inner_max + 1) == outer % (outer_max + 1): return outer
def spinning_rings(inner_max, outer_max): inner, outer = 0, 0 while True: inner -= 1 outer += 1 if inner % (inner_max + 1) == outer % (outer_max + 1): return outer
train
APPS_structured
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S. Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item. Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
import heapq class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: maxHeap = [] for value, label in zip(values, labels): print((value, label)) heappush(maxHeap, (-value, label)) labelFrequencies = {} maxSum = 0 numChosen = 0 while maxHeap and numChosen < num_wanted: value, label = heappop(maxHeap) value = -value #when you can't use that value if label in labelFrequencies and labelFrequencies[label] >= use_limit: continue if label not in labelFrequencies: labelFrequencies[label] = 0 labelFrequencies[label] += 1 numChosen += 1 maxSum += value return maxSum
import heapq class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: maxHeap = [] for value, label in zip(values, labels): print((value, label)) heappush(maxHeap, (-value, label)) labelFrequencies = {} maxSum = 0 numChosen = 0 while maxHeap and numChosen < num_wanted: value, label = heappop(maxHeap) value = -value #when you can't use that value if label in labelFrequencies and labelFrequencies[label] >= use_limit: continue if label not in labelFrequencies: labelFrequencies[label] = 0 labelFrequencies[label] += 1 numChosen += 1 maxSum += value return maxSum
train
APPS_structured
Sort a linked list in O(n log n) time using constant space complexity. Example 1: Input: 4->2->1->3 Output: 1->2->3->4 Example 2: Input: -1->5->3->4->0 Output: -1->0->3->4->5
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def sortList(self, head): l = [] traverse, traverse2 = head, head while(traverse) != None: l.append(traverse.val) traverse = traverse.next l.sort() for num in l: traverse2.val = num traverse2 = traverse2.next return head
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def sortList(self, head): l = [] traverse, traverse2 = head, head while(traverse) != None: l.append(traverse.val) traverse = traverse.next l.sort() for num in l: traverse2.val = num traverse2 = traverse2.next return head
train
APPS_structured
Due to another of his misbehaved, the primary school's teacher of the young Gauß, Herr J.G. Büttner, to keep the bored and unruly young schoolboy Karl Friedrich Gauss busy for a good long time, while he teaching arithmetic to his mates, assigned him the problem of adding up all the whole numbers from 1 through a given number `n`. Your task is to help the young Carl Friedrich to solve this problem as quickly as you can; so, he can astonish his teacher and rescue his recreation interval. Here's, an example: ``` f(n=100) // returns 5050 ``` It's your duty to verify that n is a valid positive integer number. If not, please, return false (None for Python, null for C#). > **Note:** the goal of this kata is to invite you to think about some 'basic' mathematic formula and how you can do performance optimization on your code. > Advanced - experienced users should try to solve it in one line, without loops, or optimizing the code as much as they can. ----- **Credits:** this kata was inspired by the farzher's kata 'Sum of large ints' . In fact, it can be seen as a sort of prep kata for that one.
def f(n): return int((((n**2)-1) + (1+n))/2) if isinstance(n, int) and n > 0 else None
def f(n): return int((((n**2)-1) + (1+n))/2) if isinstance(n, int) and n > 0 else None
train
APPS_structured
# Largest Rectangle in Background Imagine a photo taken to be used in an advertisement. The background on the left of the motive is whitish and you want to write some text on that background. So you scan the photo with a high resolution scanner and, for each line, count the number of pixels from the left that are sufficiently white and suitable for being written on. Your job is to find the area of the largest text box you can place on those pixels. Example: In the figure below, the whitish background pixels of the scanned photo are represented by asterisks. ``` ********************************* ********* ******* ****** ****** ****** ************** ************** ************** *************** ********************* ``` If you count the pixels on each line from the left you get the list (or array, depending on which language you are using) `[33, 9, 7, 6, 6, 6, 14, 14, 14, 15, 21]`. The largest reactangle that you can place on these pixels has an area of 70, and is represented by the dots in the figure below. ``` ********************************* ********* ******* ****** ****** ****** .............. .............. .............. ..............* ..............******* ``` Write a function that, given a list of the number whitish pixels on each line in the background, returns the area of the largest rectangle that fits on that background.
def largest_rect(histogram): dim = len(histogram) if dim == 0: return 0 max_el = max(histogram) min_el = min(histogram) if max_el == min_el: return dim * max_el area = max_el if max_el > min_el * dim else min_el * dim arr_work = [histogram] while len(arr_work) > 0: h = arr_work.pop() dim = len(h) max_el = max(h) min_el = min(h) if max_el * dim < area: continue if max_el == min_el: if area < dim * max_el: area = dim * max_el continue area = min_el * dim if area < min_el * dim else area split_index = h.index(min_el) if split_index * max_el >= area: arr_work.append(list(reversed(h[:split_index]))) if (dim - 1 - split_index) * max_el >= area: arr_work.append(list(reversed(h[(split_index + 1):]))) return area
def largest_rect(histogram): dim = len(histogram) if dim == 0: return 0 max_el = max(histogram) min_el = min(histogram) if max_el == min_el: return dim * max_el area = max_el if max_el > min_el * dim else min_el * dim arr_work = [histogram] while len(arr_work) > 0: h = arr_work.pop() dim = len(h) max_el = max(h) min_el = min(h) if max_el * dim < area: continue if max_el == min_el: if area < dim * max_el: area = dim * max_el continue area = min_el * dim if area < min_el * dim else area split_index = h.index(min_el) if split_index * max_el >= area: arr_work.append(list(reversed(h[:split_index]))) if (dim - 1 - split_index) * max_el >= area: arr_work.append(list(reversed(h[(split_index + 1):]))) return area
train
APPS_structured
Complete the `greatestProduct` method so that it'll find the greatest product of five consecutive digits in the given string of digits. For example: The input string always has more than five digits. Adapted from Project Euler.
def product(list): p = 1 for i in list: p *= int(i) return p def greatest_product(list): res = [] mul = 1 while len(list)>= 5: res.append(product(list[:5])) list = list[1:] return(max(res))
def product(list): p = 1 for i in list: p *= int(i) return p def greatest_product(list): res = [] mul = 1 while len(list)>= 5: res.append(product(list[:5])) list = list[1:] return(max(res))
train
APPS_structured
While developing a website, you detect that some of the members have troubles logging in. Searching through the code you find that all logins ending with a "\_" make problems. So you want to write a function that takes an array of pairs of login-names and e-mails, and outputs an array of all login-name, e-mails-pairs from the login-names that end with "\_". If you have the input-array: ``` [ [ "foo", "[email protected]" ], [ "bar_", "[email protected]" ] ] ``` it should output ``` [ [ "bar_", "[email protected]" ] ] ``` You *have to* use the *filter*-method which returns each element of the array for which the *filter*-method returns true. ```python https://docs.python.org/3/library/functions.html#filter ```
def search_names(logins): return list(filter(lambda l: l[0].endswith("_"), logins))
def search_names(logins): return list(filter(lambda l: l[0].endswith("_"), logins))
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 new pattern. Help the chef to code this pattern problem. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains of a single line of input, one integer $K$. -----Output:----- For each testcase, output as pattern. -----Constraints----- - $1 \leq T \leq 100$ - $1 \leq K \leq 100$ -----Sample Input:----- 2 2 4 -----Sample Output:----- 2 12 012 12 2 4 34 234 1234 01234 1234 234 34 4 -----EXPLANATION:----- No need, else pattern can be decode easily.
# cook your dish here def gcd(x, y): while y: x, y = y, x % y return x def lcm(x, y): return (x*y)//(gcd(x,y)) abc="abcdefghijklmnopqrstuvwxyz" pi=3.141592653589793238 t = int(input()) for _ in range(t): k = int(input()) k_buf = k*1 n_lines = k + 1 for i in range(n_lines): buf = " "*k for j in range(k,k_buf+1): buf=buf+str(j) k = k - 1 print(buf) for i in range(1,k_buf+1): buf=" "*i for j in range(i,k_buf+1): buf = buf+str(j) print(buf)
# cook your dish here def gcd(x, y): while y: x, y = y, x % y return x def lcm(x, y): return (x*y)//(gcd(x,y)) abc="abcdefghijklmnopqrstuvwxyz" pi=3.141592653589793238 t = int(input()) for _ in range(t): k = int(input()) k_buf = k*1 n_lines = k + 1 for i in range(n_lines): buf = " "*k for j in range(k,k_buf+1): buf=buf+str(j) k = k - 1 print(buf) for i in range(1,k_buf+1): buf=" "*i for j in range(i,k_buf+1): buf = buf+str(j) print(buf)
train
APPS_structured
Implement the StreamChecker class as follows: StreamChecker(words): Constructor, init the data structure with the given words. query(letter): returns true if and only if for some k >= 1, the last k characters queried (in order from oldest to newest, including this letter just queried) spell one of the words in the given list. Example: StreamChecker streamChecker = new StreamChecker(["cd","f","kl"]); // init the dictionary. streamChecker.query('a'); // return false streamChecker.query('b'); // return false streamChecker.query('c'); // return false streamChecker.query('d'); // return true, because 'cd' is in the wordlist streamChecker.query('e'); // return false streamChecker.query('f'); // return true, because 'f' is in the wordlist streamChecker.query('g'); // return false streamChecker.query('h'); // return false streamChecker.query('i'); // return false streamChecker.query('j'); // return false streamChecker.query('k'); // return false streamChecker.query('l'); // return true, because 'kl' is in the wordlist Note: 1 <= words.length <= 2000 1 <= words[i].length <= 2000 Words will only consist of lowercase English letters. Queries will only consist of lowercase English letters. The number of queries is at most 40000.
class TrieNode: def __init__(self): self.nodes = {} self.is_word = False class StreamChecker: def __init__(self, words: List[str]): self.prefix = \"\" self.trienode = TrieNode() for word in words: node = self.trienode for c in word[::-1]: if c not in node.nodes: node.nodes[c] = TrieNode() node = node.nodes[c] node.is_word = True def query(self, letter: str) -> bool: self.prefix += letter node = self.trienode for c in self.prefix[::-1]: if c not in node.nodes: break node = node.nodes[c] if node.is_word: return True return False
class TrieNode: def __init__(self): self.nodes = {} self.is_word = False class StreamChecker: def __init__(self, words: List[str]): self.prefix = \"\" self.trienode = TrieNode() for word in words: node = self.trienode for c in word[::-1]: if c not in node.nodes: node.nodes[c] = TrieNode() node = node.nodes[c] node.is_word = True def query(self, letter: str) -> bool: self.prefix += letter node = self.trienode for c in self.prefix[::-1]: if c not in node.nodes: break node = node.nodes[c] if node.is_word: return True return False
train
APPS_structured
Write a function that takes a string and returns an array of the repeated characters (letters, numbers, whitespace) in the string. If a charater is repeated more than once, only show it once in the result array. Characters should be shown **by the order of their first repetition**. Note that this may be different from the order of first appearance of the character. Characters are case sensitive. For F# return a "char list" ## Examples: ```python remember("apple") => returns ["p"] remember("apPle") => returns [] # no repeats, "p" != "P" remember("pippi") => returns ["p","i"] # show "p" only once remember('Pippi') => returns ["p","i"] # "p" is repeated first ```
from collections import Counter def remember(str_): seen, lst = Counter(), [] for c in str_: if seen[c] == 1: lst.append(c) seen[c] += 1 return lst
from collections import Counter def remember(str_): seen, lst = Counter(), [] for c in str_: if seen[c] == 1: lst.append(c) seen[c] += 1 return lst
train
APPS_structured
You are given a tree with $N$ vertices (numbered $1$ through $N$) and a sequence of integers $A_1, A_2, \ldots, A_N$. You may choose an arbitrary permutation $p_1, p_2, \ldots, p_N$ of the integers $1$ through $N$. Then, for each vertex $i$, you should assign the value $A_{p_i}$ to this vertex. The profit of a path between two vertices $u$ and $v$ is the sum of the values assigned to the vertices on that path (including $u$ and $v$). Let's consider only (undirected) paths that start at a leaf and end at a different leaf. Calculate the maximum possible value of the sum of profits of all such paths. Since this value could be very large, compute it modulo $10^9 + 7$. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains a single integer $N$. - The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$. - Each of the following $N−1$ lines contains two space-separated integers $u$ and $v$ denoting that vertices $u$ and $v$ are connected by an edge. -----Output----- For each test case, print a single line containing one integer — the maximum sum of profits, modulo $10^9 + 7$. -----Constraints----- - $1 \le T \le 1,000$ - $1 \le N \le 300,000$ - $1 \le A_i \le 10^9$ for each valid $i$ - the sum of $N$ over all test cases does not exceed $5 \cdot 10^5$ -----Example Input----- 2 4 1 2 3 4 1 2 2 3 2 4 5 1 2 3 4 5 1 2 2 3 3 4 4 5 -----Example Output----- 24 15 -----Explanation----- Example case 1: $(1, 4, 2, 3)$ is one of the possible permutations that give the optimal answer. Then, the profits of paths between pairs of vertices $(1, 3)$, $(1, 4)$ and $(3, 4)$ are $7$, $8$ and $9$ respectively. Example case 2: Here, any permutation could be chosen.
T = int(input()) M = 10 ** 9 + 7 for _ in range(T): N = int(input()) A = list(map(int, input().split())) if N == 1: print(0) continue B = {} C = {} for i in range(N - 1): u, v = input().split() u = int(u) - 1 v = int(v) - 1 if u not in B: B[u] = [] if v not in B: B[v] = [] B[u].append(v) B[v].append(u) total_leaves = 0 for i in B: if len(B[i]) == 1: total_leaves += 1 S = [0] visited = [False] * N parent = [-1] * N total_visits = [0] * N while len(S) > 0: current = S.pop(len(S) - 1) if visited[current]: p = parent[current] if p != -1: total_visits[p] += total_visits[current] if p not in C: C[p] = {} C[p][current] = total_visits[current] if current not in C: C[current] = {} C[current][p] = total_leaves - C[p][current] else: S.append(current) visited[current] = True for i, j in enumerate(B[current]): if not visited[j]: parent[j] = current S.append(j) if len(B[current]) == 1: total_visits[current] = 1 p = parent[current] if p != -1: if p not in C: C[p] = {} C[p][current] = 1 D = {} for i in C: sum1 = 0 for j in C[i]: sum1 += C[i][j] D[i] = sum1 E = [0] * N for i in C: sum1 = 0 for j in C[i]: D[i] -= C[i][j] sum1 += C[i][j] * D[i] E[i] = sum1 for i, j in enumerate(E): if j == 0: for k in C[i]: E[i] = C[i][k] E.sort() E.reverse() A.sort() A.reverse() E = [x % M for x in E] A = [x % M for x in A] ans = 0 for i, j in zip(E, A): a = i * j a %= M ans += a ans %= M print(ans)
T = int(input()) M = 10 ** 9 + 7 for _ in range(T): N = int(input()) A = list(map(int, input().split())) if N == 1: print(0) continue B = {} C = {} for i in range(N - 1): u, v = input().split() u = int(u) - 1 v = int(v) - 1 if u not in B: B[u] = [] if v not in B: B[v] = [] B[u].append(v) B[v].append(u) total_leaves = 0 for i in B: if len(B[i]) == 1: total_leaves += 1 S = [0] visited = [False] * N parent = [-1] * N total_visits = [0] * N while len(S) > 0: current = S.pop(len(S) - 1) if visited[current]: p = parent[current] if p != -1: total_visits[p] += total_visits[current] if p not in C: C[p] = {} C[p][current] = total_visits[current] if current not in C: C[current] = {} C[current][p] = total_leaves - C[p][current] else: S.append(current) visited[current] = True for i, j in enumerate(B[current]): if not visited[j]: parent[j] = current S.append(j) if len(B[current]) == 1: total_visits[current] = 1 p = parent[current] if p != -1: if p not in C: C[p] = {} C[p][current] = 1 D = {} for i in C: sum1 = 0 for j in C[i]: sum1 += C[i][j] D[i] = sum1 E = [0] * N for i in C: sum1 = 0 for j in C[i]: D[i] -= C[i][j] sum1 += C[i][j] * D[i] E[i] = sum1 for i, j in enumerate(E): if j == 0: for k in C[i]: E[i] = C[i][k] E.sort() E.reverse() A.sort() A.reverse() E = [x % M for x in E] A = [x % M for x in A] ans = 0 for i, j in zip(E, A): a = i * j a %= M ans += a ans %= M print(ans)
train
APPS_structured
Every now and then people in the office moves teams or departments. Depending what people are doing with their time they can become more or less boring. Time to assess the current team. ```if-not:java You will be provided with an object(staff) containing the staff names as keys, and the department they work in as values. ``` ```if:java You will be provided with an array of `Person` objects with each instance containing the name and department for a staff member. ~~~java public class Person { public final String name; // name of the staff member public final String department; // department they work in } ~~~ ``` Each department has a different boredom assessment score, as follows: accounts = 1 finance = 2 canteen = 10 regulation = 3 trading = 6 change = 6 IS = 8 retail = 5 cleaning = 4 pissing about = 25 Depending on the cumulative score of the team, return the appropriate sentiment: <=80: 'kill me now' < 100 & > 80: 'i can handle this' 100 or over: 'party time!!' The Office I - Outed The Office III - Broken Photocopier The Office IV - Find a Meeting Room The Office V - Find a Chair
boredom_scores = { 'accounts': 1, 'finance': 2 , 'canteen': 10 , 'regulation': 3 , 'trading': 6 , 'change': 6, 'IS': 8, 'retail': 5, 'cleaning': 4, 'pissing about': 25, } def boredom(staff): score = sum(map(boredom_scores.get, staff.values())) return ( 'kill me now' if score <= 80 else 'i can handle this' if score < 100 else 'party time!!' )
boredom_scores = { 'accounts': 1, 'finance': 2 , 'canteen': 10 , 'regulation': 3 , 'trading': 6 , 'change': 6, 'IS': 8, 'retail': 5, 'cleaning': 4, 'pissing about': 25, } def boredom(staff): score = sum(map(boredom_scores.get, staff.values())) return ( 'kill me now' if score <= 80 else 'i can handle this' if score < 100 else 'party time!!' )
train
APPS_structured
In this Kata, you will be given an array of strings and your task is to remove all consecutive duplicate letters from each string in the array. For example: * `dup(["abracadabra","allottee","assessee"]) = ["abracadabra","alote","asese"]`. * `dup(["kelless","keenness"]) = ["keles","kenes"]`. Strings will be lowercase only, no spaces. See test cases for more examples. ~~~if:rust For the sake of simplicity you can use the macro 'vec_of_string' to create a Vec with an array of string literals. ~~~ Good luck! If you like this Kata, please try: [Alternate capitalization](https://www.codewars.com/kata/59cfc000aeb2844d16000075) [Vowel consonant lexicon](https://www.codewars.com/kata/59cf8bed1a68b75ffb000026)
from itertools import groupby def dup(array): return list(map(remove_dup, array)) def remove_dup(string): return ''.join(single for single,_ in groupby(string))
from itertools import groupby def dup(array): return list(map(remove_dup, array)) def remove_dup(string): return ''.join(single for single,_ in groupby(string))
train
APPS_structured
The goal is to write a pair of functions the first of which will take a string of binary along with a specification of bits, which will return a numeric, signed complement in two's complement format. The second will do the reverse. It will take in an integer along with a number of bits, and return a binary string. https://en.wikipedia.org/wiki/Two's_complement Thus, to_twos_complement should take the parameters binary = "0000 0001", bits = 8 should return 1. And, binary = "11111111", bits = 8 should return -1 . While, from_twos_complement should return "00000000" from the parameters n = 0, bits = 8 . And, "11111111" from n = -1, bits = 8. You should account for some edge cases.
def to_twos_complement(binary, bits): return int(binary.replace(' ', ''), 2) - (2 ** bits) * binary.startswith('1') def from_twos_complement(n, bits): return '{:0{}b}'.format((n + 2 ** bits) % (2 ** bits), bits)
def to_twos_complement(binary, bits): return int(binary.replace(' ', ''), 2) - (2 ** bits) * binary.startswith('1') def from_twos_complement(n, bits): return '{:0{}b}'.format((n + 2 ** bits) % (2 ** bits), bits)
train
APPS_structured
Sort array by last character Complete the function to sort a given array or list by last character of elements. ```if-not:haskell Element can be an integer or a string. ``` ### Example: ``` ['acvd', 'bcc'] --> ['bcc', 'acvd'] ``` The last characters of the strings are `d` and `c`. As `c` comes before `d`, sorting by last character will give `['bcc', 'acvd']`. If two elements don't differ in the last character, then they should be sorted by the order they come in the array. ```if:haskell Elements will not be empty (but the list may be). ```
def sort_me(arr): return sorted(arr, key=lambda e: str(e)[-1])
def sort_me(arr): return sorted(arr, key=lambda e: str(e)[-1])
train
APPS_structured
Firdavs is living on planet F. There are $N$ cities (numbered $1$ through $N$) on this planet; let's denote the value of city $i$ by $v_i$. Firdavs can travel directly from each city to any other city. When he travels directly from city $x$ to city $y$, he needs to pay $f(x, y) = |v_y-v_x|+y-x$ coins (this number can be negative, in which case he receives $-f(x, y)$ coins). Let's define a simple path from city $x$ to city $y$ with length $k \ge 1$ as a sequence of cities $a_1, a_2, \ldots, a_k$ such that all cities in this sequence are different, $a_1 = x$ and $a_k = y$. The cost of such a path is $\sum_{i=1}^{k-1} f(a_i, a_{i+1})$. You need to answer some queries for Firdavs. In each query, you are given two cities $x$ and $y$, and you need to find the minimum cost of a simple path from city $x$ to city $y$. Then, you need to find the length of the longest simple path from $x$ to $y$ with this cost. -----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 two space-separated integers $N$ and $Q$. - The second line contains $N$ space-separated integers $v_1, v_2, \ldots, v_N$. - The following $Q$ lines describe queries. Each of these lines contains two space-separated integers $x$ and $y$. -----Output----- For each query, print a single line containing two space-separated integers ― the minimum cost and the maximum length. -----Constraints----- - $1 \le T \le 100$ - $1 \le N, Q \le 2 \cdot 10^5$ - $0 \le v_i \le 10^9$ for each valid $i$ - $1 \le x, y \le N$ - the sum of $N$ in all test cases does not exceed $5 \cdot 10^5$ - the sum of $Q$ in all test cases does not exceed $5 \cdot 10^5$ -----Subtasks----- Subtask #1 (30 points): - $1 \le N, Q \le 1,000$ - $v_1 < v_2 < \ldots < v_N$ - the sum of $N$ in all test cases does not exceed $5,000$ - the sum of $Q$ in all test cases does not exceed $5,000$ Subtask #2 (70 points): original constraints -----Example Input----- 2 4 2 4 2 5 7 2 3 3 4 2 1 1 1 2 1 -----Example Output----- 4 3 3 2 -1 2 -----Explanation----- Example case 1: For the first query, there are two paths with cost $4$ from city $2$ to city $3$: - $2 \rightarrow 1 \rightarrow 3$: cost $(|4-2|+1-2)+(|5-4|+3-1) = 4$, length $3$ - $2 \rightarrow 3$: cost $|5-2|+3-2 = 4$, length $2$ All other paths have greater costs, so the minimum cost is $4$. Among these two paths, we want the one with greater length, which is $3$.
for _ in range(int(input())): n,q = [int(a) for a in input().split()] v = list(map(int, input().split())) s = list(range(1, n+1)) index_s = [x for _,x in sorted(zip(v,s))] sorted_v = sorted(v) #print(index_s) #print(sorted_v) for i in range(q): x,y = [int(a) for a in input().split()] check1 = min(x,y) get_index1 = index_s.index(check1) vx = sorted_v[get_index1] check2 = max(x,y) get_index2 = index_s.index(max(x,y)) vy = sorted_v[get_index2] length = get_index2-get_index1 + 1 ans = vy-vx+y-x print(ans, length)
for _ in range(int(input())): n,q = [int(a) for a in input().split()] v = list(map(int, input().split())) s = list(range(1, n+1)) index_s = [x for _,x in sorted(zip(v,s))] sorted_v = sorted(v) #print(index_s) #print(sorted_v) for i in range(q): x,y = [int(a) for a in input().split()] check1 = min(x,y) get_index1 = index_s.index(check1) vx = sorted_v[get_index1] check2 = max(x,y) get_index2 = index_s.index(max(x,y)) vy = sorted_v[get_index2] length = get_index2-get_index1 + 1 ans = vy-vx+y-x print(ans, length)
train
APPS_structured
Simple transposition is a basic and simple cryptography technique. We make 2 rows and put first a letter in the Row 1, the second in the Row 2, third in Row 1 and so on until the end. Then we put the text from Row 2 next to the Row 1 text and thats it. Complete the function that receives a string and encrypt it with this simple transposition. ## Example For example if the text to encrypt is: `"Simple text"`, the 2 rows will be: Row 1 S m l e t Row 2 i p e t x So the result string will be: `"Sml etipetx"`
def simple_transposition(text): text = list(text) row1 = [] row2 = [] for x in range(len(text)): if x%2==0: row1.append(text[x]) else: row2.append(text[x]) result = "".join(row1) + "".join(row2) return result
def simple_transposition(text): text = list(text) row1 = [] row2 = [] for x in range(len(text)): if x%2==0: row1.append(text[x]) else: row2.append(text[x]) result = "".join(row1) + "".join(row2) return result
train
APPS_structured
## Task To charge your mobile phone battery, do you know how much time it takes from 0% to 100%? It depends on your cell phone battery capacity and the power of the charger. A rough calculation method is: ``` 0% --> 85% (fast charge) (battery capacity(mAh) * 85%) / power of the charger(mA) 85% --> 95% (decreasing charge) (battery capacity(mAh) * 10%) / (power of the charger(mA) * 50%) 95% --> 100% (trickle charge) (battery capacity(mAh) * 5%) / (power of the charger(mA) * 20%) ``` For example: Your battery capacity is 1000 mAh and you use a charger 500 mA, to charge your mobile phone battery from 0% to 100% needs time: ``` 0% --> 85% (fast charge) 1.7 (hour) 85% --> 95% (decreasing charge) 0.4 (hour) 95% --> 100% (trickle charge) 0.5 (hour) total times = 1.7 + 0.4 + 0.5 = 2.6 (hour) ``` Complete function `calculateTime` that accepts two arguments `battery` and `charger`, return how many hours can charge the battery from 0% to 100%. The result should be a number, round to 2 decimal places (In Haskell, no need to round it).
#2.55 + def calculate_time(battery,charger): max = 100 time = 0 fast = (battery/charger)*.85 dcharge = (battery/charger) * .2 tcharge = (battery/charger) * .25 if max == 100: time += fast max += -85 if max == 15: time += dcharge max += -10 if max == 5: time += tcharge max += -5 if time == 1.105: return 1.11 return round(time,2)
#2.55 + def calculate_time(battery,charger): max = 100 time = 0 fast = (battery/charger)*.85 dcharge = (battery/charger) * .2 tcharge = (battery/charger) * .25 if max == 100: time += fast max += -85 if max == 15: time += dcharge max += -10 if max == 5: time += tcharge max += -5 if time == 1.105: return 1.11 return round(time,2)
train
APPS_structured
- Input: Integer `n` - Output: String Example: `a(4)` prints as ``` A A A A A A A A ``` `a(8)` prints as ``` A A A A A A A A A A A A A A A A A A ``` `a(12)` prints as ``` A A A A A A A A A A A A A A A A A A A A A A A A A A A A ``` Note: - Each line's length is `2n - 1` - Each line should be concatenate by line break `"\n"` - If `n` is less than `4`, it should return `""` - If `n` is odd, `a(n) = a(n - 1)`, eg `a(5) == a(4); a(9) == a(8)`
def a(n): n = n if n % 2 == 0 else n - 1 width = 2 * n - 1 lines = ["A".center(width)] + [("A" + " "*k + "A").center(width) for k in range(1, n-1, 2)] +\ [" ".join(["A"]*(n//2+1)).center(width)] + [("A" + " "*k + "A").center(width) for k in range(n+1, 2*n-1, 2)] return "\n".join(lines) if n >= 4 else ""
def a(n): n = n if n % 2 == 0 else n - 1 width = 2 * n - 1 lines = ["A".center(width)] + [("A" + " "*k + "A").center(width) for k in range(1, n-1, 2)] +\ [" ".join(["A"]*(n//2+1)).center(width)] + [("A" + " "*k + "A").center(width) for k in range(n+1, 2*n-1, 2)] return "\n".join(lines) if n >= 4 else ""
train
APPS_structured
You are given a sequence $A_1, A_2, \ldots, A_N$. For each valid $i$, the star value of the element $A_i$ is the number of valid indices $j < i$ such that $A_j$ is divisible by $A_i$. Chef is a curious person, so he wants to know the maximum star value in the given sequence. Help him find it. -----Input----- - The first line of the input contains a single integer $T$ which denotes the number of test cases. - The first line of each test case contains a single integer $N$ . - The second line of each test case contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$. -----Output----- For each test case, print a single line containing one integer ― the maximum star value. -----Constraints----- - $1 \le T \le 10$ - $1 \le N \le 10^5$ - $1 \le A_i \le 10^6$ for each valid $i$ - Sum of $N$ over all test cases does not exceed $100,000$. -----Subtasks----- Subtask #1 (20 points): sum of $N$ over all test cases does not exceed $5,000$ Subtask #2 (80 points): original constraints -----Example Input----- 1 7 8 1 28 4 2 6 7 -----Example Output----- 3 -----Explanation----- $A_5 = 2$ divides $4$, $28$ and $8$, so its star value is $3$. There is no element with a higher star value.
import numpy as np import sys for _ in np.arange(int(sys.stdin.readline())): N = int(sys.stdin.readline()) a = np.array(list(map(int, sys.stdin.readline().split()))) b = np.array(a[::-1]) maxx = 0 h = np.array([0]*N) for index, items in enumerate(b): k = 0 if h[N - index - 1] == 0: for i in range(N - index): if a[i] % items == 0: k += 1 h[i] = 1 maxx = max(k - 1, maxx) # print(h) print(maxx)
import numpy as np import sys for _ in np.arange(int(sys.stdin.readline())): N = int(sys.stdin.readline()) a = np.array(list(map(int, sys.stdin.readline().split()))) b = np.array(a[::-1]) maxx = 0 h = np.array([0]*N) for index, items in enumerate(b): k = 0 if h[N - index - 1] == 0: for i in range(N - index): if a[i] % items == 0: k += 1 h[i] = 1 maxx = max(k - 1, maxx) # print(h) print(maxx)
train
APPS_structured
# Background The famous Collatz Sequence is generated with the following rules: * Start with a positive integer `a[0] = n`. * If `a[i]` is even, `a[i+1] = a[i] / 2`. * Otherwise, `a[i+1] = a[i] * 3 + 1`. However, for the purpose of this Kata, I give a **slightly modified definition**: * If `a[i]` is even, `a[i+1] = a[i] / 2`. This step is a step-down, or `D`. * Otherwise, `a[i+1] = (a[i] * 3 + 1) / 2`. This step is a step-up, or `U`. Also, for any starting number, the sequence is generated indefinitely, not ending at 1. # Problem Description For any given starting number, we can record the types of steps(`D` or `U`) from it. For example, if we start with the number 11, the Collatz steps look like this: ``` a[0] = 11 a[1] = (11 * 3 + 1) / 2 = 17 -> U a[2] = (17 * 3 + 1) / 2 = 26 -> U a[3] = 26 / 2 = 13 -> D a[4] = (13 * 3 + 1) / 2 = 20 -> U a[5] = 20 / 2 = 10 -> D a[6] = 10 / 2 = 5 -> D a[7] = (5 * 3 + 1) / 2 = 8 -> U a[8] = 8 / 2 = 4 -> D a[9] = 4 / 2 = 2 -> D a[10] = 2 / 2 = 1 -> D a[11] = (1 * 3 + 1) / 2 = 2 -> U a[12] = 2 / 2 = 1 -> D ... ``` ``` 11 -> 17 -> 26 -> 13 -> 20 -> 10 -> 5 -> 8 -> 4 -> 2 -> 1 -> 2 -> 1 -> ... U U D U D D U D D D U D ``` Based on the steps shown above, the first four Collatz steps of 11 is `UUDU`. Also, 107 is the smallest number over 100 whose Collatz steps start with `UUDU`, and 1003 is the smallest number over 1000 with the property. A special example is the number 1, which can generate any number of `UD`. Find the smallest integer exceeding or equal to `n` whose Collatz steps start with the given string `steps`. # Constraints `1 <= n <= 10 ** 9` `n` is always a valid integer. `1 <= length(steps) <= 25` The string `steps` will entirely consist of `U`s and `D`s. # Examples ```python collatz_steps(1, 'UUDU') == 11 collatz_steps(100, 'UUDU') == 107 collatz_steps(1000, 'UUDU') == 1003 collatz_steps(1, 'UD') == 1 collatz_steps(1, 'UDUD') == 1 collatz_steps(1, 'UDUDUD') == 1 ``` # Hint If you are completely lost, start by answering the following question: * After applying the given steps (e.g. `UUDU`) to an initial number `x`, what fraction do you get? After that, you might want to study about [modular inverse](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse). # Acknowledgement This problem was inspired by [Project Euler #277: A Modified Collatz sequence](https://projecteuler.net/problem=277). If you enjoyed this Kata, please also have a look at [my other Katas](https://www.codewars.com/users/Bubbler/authored)!
def collatz_steps(n, s): while True: x = n ans = '' flag = True for j in range(len(s)): if x%2 == 0: x = x//2 ans += 'D' else: x = (x*3+1)//2 ans += 'U' if ans[j] != s[j]: flag = False break if flag == True: return n else: n += 2**(len(ans)-1)
def collatz_steps(n, s): while True: x = n ans = '' flag = True for j in range(len(s)): if x%2 == 0: x = x//2 ans += 'D' else: x = (x*3+1)//2 ans += 'U' if ans[j] != s[j]: flag = False break if flag == True: return n else: n += 2**(len(ans)-1)
train
APPS_structured
# Description Write a function that accepts the current position of a knight in a chess board, it returns the possible positions that it will end up after 1 move. The resulted should be sorted. ## Example "a1" -> ["b3", "c2"]
def possible_positions(pos): board = [[r+str(c) for c in range(1,9)] for r in "abcdefgh"] x,y = ord(pos[0])-97,int(pos[1])-1 return sorted([board[py][px] for py,px in [(x+2,y+1),(x+2,y-1),(x-2,y+1),(x-2,y-1),(x+1,y+2),(x+1,y-2),(x-1,y+2),(x-1,y-2)] if 0 <= px < 8 and 0 <= py < 8])
def possible_positions(pos): board = [[r+str(c) for c in range(1,9)] for r in "abcdefgh"] x,y = ord(pos[0])-97,int(pos[1])-1 return sorted([board[py][px] for py,px in [(x+2,y+1),(x+2,y-1),(x-2,y+1),(x-2,y-1),(x+1,y+2),(x+1,y-2),(x-1,y+2),(x-1,y-2)] if 0 <= px < 8 and 0 <= py < 8])
train
APPS_structured
Chef is making polygon cakes in his kitchen today! Since the judge panel is very strict, Chef's cakes must be beautiful and have sharp and precise $internal$ angles in arithmetic progression. Given the number of sides, $N$, of the cake Chef is baking today and also the measure of its first angle(smallest angle), $A$, find the measure of the $K^{th}$ angle. -----Input:----- - The first line contains a single integer $T$, the number of test cases. - The next $T$ lines contain three space separated integers $N$, $A$ and $K$, the number of sides of polygon, the first angle and the $K^{th}$ angle respectively. -----Output:----- For each test case, print two space separated integers $X$ and $Y$, such that the $K^{th}$ angle can be written in the form of $X/Y$ and $gcd(X, Y) = 1$ -----Constraints----- - $1 \leq T \leq 50$ - $3 \leq N \leq 1000$ - $1 \leq A \leq 1000000000$ - $1 \leq K \leq N$ - It is guaranteed the answer is always valid. -----Sample Input:----- 1 3 30 2 -----Sample Output:----- 60 1
def gcd(d,s): if s==0: return d else: return gcd(s,d%s) for _ in range(int(input())): n,a,k=[int(x) for x in input().split()] d = (360*(n-2)-2*a*n)*(k-1) s = n*(n-1) k = gcd(d,s) d = d//k s=s//k print(d+s*a,s)
def gcd(d,s): if s==0: return d else: return gcd(s,d%s) for _ in range(int(input())): n,a,k=[int(x) for x in input().split()] d = (360*(n-2)-2*a*n)*(k-1) s = n*(n-1) k = gcd(d,s) d = d//k s=s//k print(d+s*a,s)
train
APPS_structured
Task: Given an array arr of strings complete the function landPerimeter by calculating the total perimeter of all the islands. Each piece of land will be marked with 'X' while the water fields are represented as 'O'. Consider each tile being a perfect 1 x 1piece of land. Some examples for better visualization: ['XOOXO',  'XOOXO',  'OOOXO',  'XXOXO',  'OXOOO'] or should return: "Total land perimeter: 24", while ['XOOO',  'XOXO',  'XOXO',  'OOXX',  'OOOO'] should return: "Total land perimeter: 18" Good luck!
def land_perimeter(arr): a, b = ' '.join(arr), ' '.join(''.join(x) for x in zip(*arr)) p = 4 * a.count('X') - 2 * 'O{}O{}O'.format(a, b).split('X').count('') return 'Total land perimeter: {}'.format(p)
def land_perimeter(arr): a, b = ' '.join(arr), ' '.join(''.join(x) for x in zip(*arr)) p = 4 * a.count('X') - 2 * 'O{}O{}O'.format(a, b).split('X').count('') return 'Total land perimeter: {}'.format(p)
train
APPS_structured
Nauuo is a girl who loves drawing circles. One day she has drawn a circle and wanted to draw a tree on it. The tree is a connected undirected graph consisting of $n$ nodes and $n-1$ edges. The nodes are numbered from $1$ to $n$. Nauuo wants to draw a tree on the circle, the nodes of the tree should be in $n$ distinct points on the circle, and the edges should be straight without crossing each other. "Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges. Nauuo wants to draw the tree using a permutation of $n$ elements. A permutation of $n$ elements is a sequence of integers $p_1,p_2,\ldots,p_n$ in which every integer from $1$ to $n$ appears exactly once. After a permutation is chosen Nauuo draws the $i$-th node in the $p_i$-th point on the circle, then draws the edges connecting the nodes. The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo $998244353$, can you help her? It is obvious that whether a permutation is valid or not does not depend on which $n$ points on the circle are chosen. -----Input----- The first line contains a single integer $n$ ($2\le n\le 2\cdot 10^5$) — the number of nodes in the tree. Each of the next $n-1$ lines contains two integers $u$ and $v$ ($1\le u,v\le n$), denoting there is an edge between $u$ and $v$. It is guaranteed that the given edges form a tree. -----Output----- The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo $998244353$. -----Examples----- Input 4 1 2 1 3 2 4 Output 16 Input 4 1 2 1 3 1 4 Output 24 -----Note----- Example 1 All valid permutations and their spanning trees are as follows. [Image] Here is an example of invalid permutation: the edges $(1,3)$ and $(2,4)$ are crossed. [Image] Example 2 Every permutation leads to a valid tree, so the answer is $4! = 24$.
import math def factorial(n,j): inf=998244353 j[0]=1 j[1]=1 for i in range(2,n+1): j[i]=j[i-1]*i j[i]%=inf return j l1=[0]*(200009) y=factorial(200008,l1) inf=998244353 n=int(input()) l=[0]*(200009) x=1 for i in range(n-1): u,v=input().split() u,v=[int(u),int(v)] l[u]+=1 l[v]+=1 for i in range(len(l)): if l[i]>0: x*=y[l[i]] x%=inf print((n*x)%inf)
import math def factorial(n,j): inf=998244353 j[0]=1 j[1]=1 for i in range(2,n+1): j[i]=j[i-1]*i j[i]%=inf return j l1=[0]*(200009) y=factorial(200008,l1) inf=998244353 n=int(input()) l=[0]*(200009) x=1 for i in range(n-1): u,v=input().split() u,v=[int(u),int(v)] l[u]+=1 l[v]+=1 for i in range(len(l)): if l[i]>0: x*=y[l[i]] x%=inf print((n*x)%inf)
train
APPS_structured
Chef organised a chess tournament, which spanned over $M$ months. There were $N$ players, and player $i$ was rated $R_i$ before the start of the tournament. To see the progress of the players, he noted their rating changes at the end of each month. After the tournament, FIDE asked Chef to find the number of players whose peak rating and peak ranking did not occur in the same month. In other words, Chef was asked to find the ratings and ranking of each player after each of the $M$ months. Then, using this data, he should find the number of players, such that the month in which they achieved their highest rating over all the months, was different from the month in which they achieved their best rank (based on ratings), over all the months. Note that we do not consider the initial rating/ranking, but only the rating and rankings after each of the $M$ months. For a particular player, if there are multiple peak rating or peak ranking months, Chef was to consider the earliest of them. If multiple players had the same rating at the end of some month, they were to be given the same rank. For example, if there were $5$ players, and their ratings at the end of some month were $(2600$, $2590$, $2600$, $2600$ and $2590)$, players $1$, $3$ and $4$ were to be given the first rank, while players $2$ and $5$ should be given the fourth rank. As Chef hates statistics, he asks you, his friend, to help him find this. Can you help Chef? -----Input:----- - The first line contains an integer $T$, the number of test cases. - The first line of each test case contains two space-separated integers $N$ and $M$, the number of players and the number of months that the tournament spanned over. - The second line of each test case contains $N$ space-separated integers, $R_1, R_2, \ldots, R_N$ denoting the initial ratings of the players, i.e., their ratings before the start of the tournament. - The next $N$ lines each contain $M$ space-separated integers. The $j^{th}$ integer of the $i^{th}$ line, $C_{i,j}$ denotes the rating change of the $i^{th}$ player after the $j^{th}$ month. -----Output:----- For each test case, print the number of players whose peak ratings did not occur in the same month as their peak ranking, in a new line. -----Constraints----- - $1 \le T \le 10$ - $1 \le N,M \le 500$ - $1800 \le R_i \le 2800$ - $-20 \le C_{i,j} \le 20$ -----Subtasks----- - 30 points : $1 \leq N,M \leq 50$ - 70 points : Original constraints. -----Sample Input:----- 2 3 3 2500 2500 2520 10 -5 -20 10 15 20 -15 17 13 2 3 2125 2098 -20 10 -10 10 10 -20 -----Sample Output:----- 2 2 -----Explanation:----- Test case 1: - The ratings for player $1$ after each month are: $(2510$, $2505$ and $2485)$, while his rankings are first, third and third, respectively. Thus, his best rating and best ranking occur after the same month, i.e., after the first month. - The ratings for player $2$ after each month are: $(2510$, $2525$ and $2545)$, while his rankings are first, first and first, respectively. His best rating occurs after the third month, while his best ranking occurs after the first month (we consider the first month even though his peak ranking is over all the months, because we consider only the earliest month where he attains the peak ranking). - The ratings for player $3$ after each month are: $(2505$, $2522$ and $2535)$, while his rankings are third, second and second, respectively. His best rating occurs after the third month, while his best ranking occurs after the second month. So there are two players ($2$ and $3$), whose peak ratings did not occur in the same month as their peak ranking, and hence the answer is 2. Test case 2: - The ratings for player $1$ after each month are: $(2105$, $2115$ and $2105)$, while his rankings are second, second and first, respectively. Best rating is after second month, but best ranking is after third month. - The ratings for player $2$ after each month are: $(2108$, $2118$ and $2098)$, while his rankings are first, first and second, respectively. Best rating is after second month, but best ranking is after first month. So there are two players ($1$ and $2$), whose peak ratings did not occur in the same month as their peak ranking, and hence the answer is 2.
# cook your dish here n=int(input()) for k in range(n): lst=input().split() N=int(lst[0]) M=int(lst[1]) rating=[] rating.append(list(map(int,input().split()))) change=[None for i in range(N)] for i in range(N): change[i]=list(map(int,input().split())) for i in range(1,M+1): rating.append([]) for j in range(0, N): rating[i].append(rating[i-1][j] + change[j][i-1]) MaxRating = [] MaxRatingMonth= [] for j in range(N): MaxRating.append(rating[1][j]) MaxRatingMonth.append(1) for i in range(2,M+1): if rating[i][j]>MaxRating[j]: MaxRating[j]=rating[i][j] MaxRatingMonth[j]=i MaxRankingMonth= [] newrating=[] Ranking=[[None for j in range(N)] for i in range(0,M)] for i in range(1,M+1): newrating.append(sorted(rating[i],reverse=True)) for i in range(1,M+1): for j in range(N): Ranking[i-1][j]=(newrating[i-1].index(rating[i][j])+1) MaxRankingMonth= [] MaxRanking=[] for j in range(N): MaxRankingMonth.append(1) MaxRanking.append(Ranking[0][j]) for i in range(2,M+1): if Ranking[i-1][j]<MaxRanking[j]: MaxRanking[j]=Ranking[i-1][j] MaxRankingMonth[j]=i count=0 for i in range(N): if MaxRankingMonth[i]!=MaxRatingMonth[i]: count+=1 print(count)
# cook your dish here n=int(input()) for k in range(n): lst=input().split() N=int(lst[0]) M=int(lst[1]) rating=[] rating.append(list(map(int,input().split()))) change=[None for i in range(N)] for i in range(N): change[i]=list(map(int,input().split())) for i in range(1,M+1): rating.append([]) for j in range(0, N): rating[i].append(rating[i-1][j] + change[j][i-1]) MaxRating = [] MaxRatingMonth= [] for j in range(N): MaxRating.append(rating[1][j]) MaxRatingMonth.append(1) for i in range(2,M+1): if rating[i][j]>MaxRating[j]: MaxRating[j]=rating[i][j] MaxRatingMonth[j]=i MaxRankingMonth= [] newrating=[] Ranking=[[None for j in range(N)] for i in range(0,M)] for i in range(1,M+1): newrating.append(sorted(rating[i],reverse=True)) for i in range(1,M+1): for j in range(N): Ranking[i-1][j]=(newrating[i-1].index(rating[i][j])+1) MaxRankingMonth= [] MaxRanking=[] for j in range(N): MaxRankingMonth.append(1) MaxRanking.append(Ranking[0][j]) for i in range(2,M+1): if Ranking[i-1][j]<MaxRanking[j]: MaxRanking[j]=Ranking[i-1][j] MaxRankingMonth[j]=i count=0 for i in range(N): if MaxRankingMonth[i]!=MaxRatingMonth[i]: count+=1 print(count)
train
APPS_structured
You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. You may assume that you have an infinite number of each kind of coin. Example 1: Input: coins = [1,2,5], amount = 11 Output: 3 Explanation: 11 = 5 + 5 + 1 Example 2: Input: coins = [2], amount = 3 Output: -1 Example 3: Input: coins = [1], amount = 0 Output: 0 Example 4: Input: coins = [1], amount = 1 Output: 1 Example 5: Input: coins = [1], amount = 2 Output: 2 Constraints: 1 <= coins.length <= 12 1 <= coins[i] <= 231 - 1 0 <= amount <= 104
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: coins.sort(reverse = True) count = 0 self.maxcount = float('inf') self.dfs(coins, count, amount) return -1 if self.maxcount == float('inf') else self.maxcount def dfs(self,coins,count,amount): if amount == 0: self.maxcount = min(self.maxcount,count) for i in range(len(coins)): if amount >= coins[i] and count + math.ceil(amount/coins[i])<self.maxcount: self.dfs(coins[i:],count+1,amount-coins[i])
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: coins.sort(reverse = True) count = 0 self.maxcount = float('inf') self.dfs(coins, count, amount) return -1 if self.maxcount == float('inf') else self.maxcount def dfs(self,coins,count,amount): if amount == 0: self.maxcount = min(self.maxcount,count) for i in range(len(coins)): if amount >= coins[i] and count + math.ceil(amount/coins[i])<self.maxcount: self.dfs(coins[i:],count+1,amount-coins[i])
train
APPS_structured
Chef is now a corporate person. He has to attend office regularly. But chef does not want to go to office, rather he wants to stay home and discover different recipes and cook them. In the office where chef works, has two guards who count how many times a person enters into the office building. Though the duty of a guard is 24 hour in a day, but sometimes they fall asleep during their duty and could not track the entry of a person in the office building. But one better thing is that they never fall asleep at the same time. At least one of them remains awake and counts who enters into the office. Now boss of Chef wants to calculate how many times Chef has entered into the building. He asked to the guard and they give him two integers A and B, count of first guard and second guard respectively. Help the boss to count the minimum and maximum number of times Chef could have entered into the office building. -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of the T test cases follows. Each test case consists of a line containing two space separated integers A and B. -----Output----- For each test case, output a single line containing two space separated integers, the minimum and maximum number of times Chef could have entered into the office building. -----Constraints----- - 1 ≤ T ≤ 100 - 0 ≤ A, B ≤ 1000000 -----Example----- Input: 1 19 17 Output: 19 36
# cook your dish here T=int(input()) for i in range(T): a,b=map(int,input().split()) #n=int(input()) print(max(a,b),a+b)
# cook your dish here T=int(input()) for i in range(T): a,b=map(int,input().split()) #n=int(input()) print(max(a,b),a+b)
train
APPS_structured
Snuke has a rooted tree with N+1 vertices. The vertices are numbered 0 through N, and Vertex 0 is the root of the tree. The parent of Vertex i (1 \leq i \leq N) is Vertex p_i. Besides this tree, Snuke also has an box which is initially empty and many marbles, and playing with them. The play begins with placing one marble on some of the vertices, then proceeds as follows: - If there is a marble on Vertex 0, move the marble into the box. - Move each marble from the vertex to its parent (all at once). - For each vertex occupied by two or more marbles, remove all the marbles from the vertex. - If there exists a vertex with some marbles, go to Step 1. Otherwise, end the play. There are 2^{N+1} ways to place marbles on some of the vertices. For each of them, find the number of marbles that will be in the box at the end of the play, and compute the sum of all those numbers modulo 1,000,000,007. -----Constraints----- - 1 \leq N < 2 \times 10^{5} - 0 \leq p_i < i -----Partial Scores----- - In the test set worth 400 points, N < 2{,}000. -----Input----- Input is given from Standard Input in the following format: N p_1 p_2 ... p_{N} -----Output----- Print the answer. -----Sample Input----- 2 0 0 -----Sample Output----- 8 When we place a marble on both Vertex 1 and 2, there will be multiple marbles on Vertex 0 by step 2. In such a case, these marbles will be removed instead of being moved to the box.
# coding: utf-8 # Your code here! import sys read = sys.stdin.read readline = sys.stdin.readline n, = list(map(int, readline().split())) p = [-1] + [*list(map(int, readline().split()))] MOD = 10**9+7 child = [[] for i in range(n+1)] tot = [None for i in range(n+1)] one = [None for i in range(n+1)] dep = [0]*(n+1) p2 = [1]*(n+1) for i in range(n): p2[i+1] = p2[i]*2%MOD for v in range(n,-1,-1): if dep[v]==0: tot[v] = [] one[v] = [] else: child[v].sort(key=lambda i: dep[i]) one[v] = one[child[v][-1]] tot[v] = tot[child[v][-1]] #one_sum = [0]*(dep[v]) #zero_sum = [0]*(dep[v]) child[v].pop() if child[v]: zero = [p2[tot[v][j]]-one[v][j] for j in range(-len(one[child[v][-1]]),0)] for c in child[v]: for j in range(-len(one[c]),0): z = p2[tot[c][j]]-one[c][j] one[v][j] = (one[v][j]*z+zero[j]*one[c][j])%MOD zero[j] = zero[j]*z%MOD tot[v][j] += tot[c][j] tot[v].append(1) one[v].append(1) child[p[v]].append(v) dep[p[v]] = max(dep[p[v]],dep[v]+1) #print(v,tot[v],one[v]) #print("tot",tot[0]) #print("one",one[0]) ans = 0 for i,j in zip(tot[0],one[0]): ans += pow(2,n+1-i,MOD)*j%MOD print((ans%MOD)) #print(sum(tot[0]))
# coding: utf-8 # Your code here! import sys read = sys.stdin.read readline = sys.stdin.readline n, = list(map(int, readline().split())) p = [-1] + [*list(map(int, readline().split()))] MOD = 10**9+7 child = [[] for i in range(n+1)] tot = [None for i in range(n+1)] one = [None for i in range(n+1)] dep = [0]*(n+1) p2 = [1]*(n+1) for i in range(n): p2[i+1] = p2[i]*2%MOD for v in range(n,-1,-1): if dep[v]==0: tot[v] = [] one[v] = [] else: child[v].sort(key=lambda i: dep[i]) one[v] = one[child[v][-1]] tot[v] = tot[child[v][-1]] #one_sum = [0]*(dep[v]) #zero_sum = [0]*(dep[v]) child[v].pop() if child[v]: zero = [p2[tot[v][j]]-one[v][j] for j in range(-len(one[child[v][-1]]),0)] for c in child[v]: for j in range(-len(one[c]),0): z = p2[tot[c][j]]-one[c][j] one[v][j] = (one[v][j]*z+zero[j]*one[c][j])%MOD zero[j] = zero[j]*z%MOD tot[v][j] += tot[c][j] tot[v].append(1) one[v].append(1) child[p[v]].append(v) dep[p[v]] = max(dep[p[v]],dep[v]+1) #print(v,tot[v],one[v]) #print("tot",tot[0]) #print("one",one[0]) ans = 0 for i,j in zip(tot[0],one[0]): ans += pow(2,n+1-i,MOD)*j%MOD print((ans%MOD)) #print(sum(tot[0]))
train
APPS_structured
As you probably know, Fibonacci sequence are the numbers in the following integer sequence: 1, 1, 2, 3, 5, 8, 13... Write a method that takes the index as an argument and returns last digit from fibonacci number. Example: getLastDigit(15) - 610. Your method must return 0 because the last digit of 610 is 0. Fibonacci sequence grows very fast and value can take very big numbers (bigger than integer type can contain), so, please, be careful with overflow. [Hardcore version of this kata](http://www.codewars.com/kata/find-last-fibonacci-digit-hardcore-version), no bruteforce will work here ;)
def get_last_digit(index): a, b = 0, 1 for i in range(index): a, b = b, (a + b) % 10 return a
def get_last_digit(index): a, b = 0, 1 for i in range(index): a, b = b, (a + b) % 10 return a
train
APPS_structured
Numbers $1, 2, 3, \dots n$ (each integer from $1$ to $n$ once) are written on a board. In one operation you can erase any two numbers $a$ and $b$ from the board and write one integer $\frac{a + b}{2}$ rounded up instead. You should perform the given operation $n - 1$ times and make the resulting number that will be left on the board as small as possible. For example, if $n = 4$, the following course of action is optimal: choose $a = 4$ and $b = 2$, so the new number is $3$, and the whiteboard contains $[1, 3, 3]$; choose $a = 3$ and $b = 3$, so the new number is $3$, and the whiteboard contains $[1, 3]$; choose $a = 1$ and $b = 3$, so the new number is $2$, and the whiteboard contains $[2]$. It's easy to see that after $n - 1$ operations, there will be left only one number. Your goal is to minimize it. -----Input----- The first line contains one integer $t$ ($1 \le t \le 1000$) — the number of test cases. The only line of each test case contains one integer $n$ ($2 \le n \le 2 \cdot 10^5$) — the number of integers written on the board initially. It's guaranteed that the total sum of $n$ over test cases doesn't exceed $2 \cdot 10^5$. -----Output----- For each test case, in the first line, print the minimum possible number left on the board after $n - 1$ operations. Each of the next $n - 1$ lines should contain two integers — numbers $a$ and $b$ chosen and erased in each operation. -----Example----- Input 1 4 Output 2 2 4 3 3 3 1
t = int(input()) for _ in range(t): n = int(input()) print(2) print(n-1, n) for i in range(n-2): print(n-2-i, n-i)
t = int(input()) for _ in range(t): n = int(input()) print(2) print(n-1, n) for i in range(n-2): print(n-2-i, n-i)
train
APPS_structured
We are interested in collecting the triples of positive integers ```(a, b, c)``` that fulfill the following equation: ```python a² + b² = c³ ``` The first triple with the lowest values that satisfies the equation we have above is (2, 2 ,2). In effect: ```python 2² + 2² = 2³ 4 + 4 = 8 ``` The first pair of triples that "shares" the same value of ```c``` is: ```(2, 11, 5)``` and ```(5, 10, 5)```. Both triples share the same value of ```c``` is ```c = 5```. ```python Triple (2, 11, 5) Triple(5, 10, 5) 2² + 11² = 5³ 5² + 10² = 5³ 4 + 121 = 125 25 + 100 = 125 ``` So, we say that the value ```c``` has two solutions because there are two triples sharing the same value of ```c```. There are some values of ```c``` with no solutions. The first value of ```c``` that have a surprising number of solutions is ```65``` with ```8``` different triples. In order to avoid duplications you will consider that ```a <= b``` always. Make the function ```find_abc_sumsqcube()```, that may give us the values of c for an specific number of solutions. For that purpose the above required function will receive two arguments, ```c_max``` and ```num_sol```. It is understandable that ```c_max``` will give to our function the upper limit of ```c``` and ```num_sol```, the specific number of solutions. The function will output a sorted list with the values of ```c``` that have a number of solutions equals to ```num_sol``` Let's see some cases: ```python find_abc_sumsqcube(5, 1) == [2] # below or equal to c_max = 5 we have triple the (2, 2, 2) (see above) find_abc_sumsqcube(5, 2) == [5] # now we want the values of ```c ≤ c_max``` with two solutions (see above again) find_abc_sumsqcube(10, 2) == [5, 10] find_abc_sumsqcube(20, 8) == [] # There are no values of c equal and bellow 20 having 8 solutions. ``` Our tests will have the following ranges for our two arguments: ```python 5 ≤ c_max ≤ 1000 1 ≤ num_sol ≤ 10 ``` Happy coding!!
from bisect import bisect_right as bisect RES = [[] for _ in range(11)] for c in range(1,1001): c3 = c**3 nSol = sum( ((c3-a**2)**.5).is_integer() for a in range(1,int((c3//2)**.5+1))) if 0 < nSol < 11: RES[nSol].append(c) def find_abc_sumsqcube(c_max, nSol): return RES[nSol][:bisect(RES[nSol], c_max)]
from bisect import bisect_right as bisect RES = [[] for _ in range(11)] for c in range(1,1001): c3 = c**3 nSol = sum( ((c3-a**2)**.5).is_integer() for a in range(1,int((c3//2)**.5+1))) if 0 < nSol < 11: RES[nSol].append(c) def find_abc_sumsqcube(c_max, nSol): return RES[nSol][:bisect(RES[nSol], c_max)]
train
APPS_structured
This kata requires you to convert minutes (`int`) to hours and minutes in the format `hh:mm` (`string`). If the input is `0` or negative value, then you should return `"00:00"` **Hint:** use the modulo operation to solve this challenge. The modulo operation simply returns the remainder after a division. For example the remainder of 5 / 2 is 1, so 5 modulo 2 is 1. ## Example If the input is `78`, then you should return `"01:18"`, because 78 minutes converts to 1 hour and 18 minutes. Good luck! :D
def time_convert(num): a=num//60 b=num%60 if num<=0: return '00:00' elif 0<num<10: return '00:0'+str(num) elif 10<=num<60: return '00:'+str(num) else: if a<10 and b<10: return "0"+str(a)+':'+"0"+str(b) elif a>=10 and b<10: return str(a)+':'+"0"+str(b) elif a<10 and b>=10: return "0"+str(a)+':'+str(b) elif a>=10 and b>=10: return str(a)+':'+str(b)
def time_convert(num): a=num//60 b=num%60 if num<=0: return '00:00' elif 0<num<10: return '00:0'+str(num) elif 10<=num<60: return '00:'+str(num) else: if a<10 and b<10: return "0"+str(a)+':'+"0"+str(b) elif a>=10 and b<10: return str(a)+':'+"0"+str(b) elif a<10 and b>=10: return "0"+str(a)+':'+str(b) elif a>=10 and b>=10: return str(a)+':'+str(b)
train
APPS_structured
=====Function Descriptions===== group() A group() expression returns one or more subgroups of the match. Code >>> import re >>> m = re.match(r'(\w+)@(\w+)\.(\w+)','[email protected]') >>> m.group(0) # The entire match '[email protected]' >>> m.group(1) # The first parenthesized subgroup. 'username' >>> m.group(2) # The second parenthesized subgroup. 'hackerrank' >>> m.group(3) # The third parenthesized subgroup. 'com' >>> m.group(1,2,3) # Multiple arguments give us a tuple. ('username', 'hackerrank', 'com') groups() A groups() expression returns a tuple containing all the subgroups of the match. Code >>> import re >>> m = re.match(r'(\w+)@(\w+)\.(\w+)','[email protected]') >>> m.groups() ('username', 'hackerrank', 'com') groupdict() A groupdict() expression returns a dictionary containing all the named subgroups of the match, keyed by the subgroup name. Code >>> m = re.match(r'(?P<user>\w+)@(?P<website>\w+)\.(?P<extension>\w+)','[email protected]') >>> m.groupdict() {'website': 'hackerrank', 'user': 'myname', 'extension': 'com'} =====Problem Statement===== You are given a string S. Your task is to find the first occurrence of an alphanumeric character in (read from left to right) that has consecutive repetitions. =====Input Format===== A single line of input containing the string S. =====Constraints===== 0<len(S)<100 =====Output Format===== Print the first occurrence of the repeating character. If there are no repeating characters, print -1.
import re s = input() res = re.search(r'([A-Za-z0-9])\1',s) if res == None: print((-1)) else: print((res.group(1)))
import re s = input() res = re.search(r'([A-Za-z0-9])\1',s) if res == None: print((-1)) else: print((res.group(1)))
train
APPS_structured
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n? Example: Input: 3 Output: 5 Explanation: Given n = 3, there are a total of 5 unique BST's: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
class Solution: def numTrees(self, n): """ :type n: int :rtype: int """ M = [0 for x in range(n)] M[0] = 1 for i in range(1,n): for j in range(1,i): M[i] += M[j-1] * M[i-j-1] M[i] += M[i-1] * 2 return M[n-1]
class Solution: def numTrees(self, n): """ :type n: int :rtype: int """ M = [0 for x in range(n)] M[0] = 1 for i in range(1,n): for j in range(1,i): M[i] += M[j-1] * M[i-j-1] M[i] += M[i-1] * 2 return M[n-1]
train
APPS_structured
We are interested in collecting the sets of six prime numbers, that having a starting prime p, the following values are also primes forming the sextuplet ```[p, p + 4, p + 6, p + 10, p + 12, p + 16]``` The first sextuplet that we find is ```[7, 11, 13, 17, 19, 23]``` The second one is ```[97, 101, 103, 107, 109, 113]``` Given a number ```sum_limit```, you should give the first sextuplet which sum (of its six primes) surpasses the sum_limit value. ```python find_primes_sextuplet(70) == [7, 11, 13, 17, 19, 23] find_primes_sextuplet(600) == [97, 101, 103, 107, 109, 113] ``` Features of the tests: ``` Number Of Tests = 18 10000 < sum_limit < 29700000 ``` If you have solved this kata perhaps you will find easy to solve this one: https://www.codewars.com/kata/primes-with-two-even-and-double-even-jumps/ Enjoy it!!
li = [7,97,16057,19417,43777,1091257,1615837,1954357, 2822707,2839927,3243337,3400207,6005887,6503587, 7187767,7641367,8061997,8741137,10526557,11086837, 11664547,14520547,14812867,14834707,14856757, 16025827,16094707,18916477,19197247] sequences = [[i+j for j in [0,4,6,10,12,16]] for i in li] find_primes_sextuplet=lambda s:next(i for i in sequences if sum(i)>s)
li = [7,97,16057,19417,43777,1091257,1615837,1954357, 2822707,2839927,3243337,3400207,6005887,6503587, 7187767,7641367,8061997,8741137,10526557,11086837, 11664547,14520547,14812867,14834707,14856757, 16025827,16094707,18916477,19197247] sequences = [[i+j for j in [0,4,6,10,12,16]] for i in li] find_primes_sextuplet=lambda s:next(i for i in sequences if sum(i)>s)
train
APPS_structured
The Collatz conjecture (also known as 3n+1 conjecture) is a conjecture that applying the following algorithm to any number we will always eventually reach one: ``` [This is writen in pseudocode] if(number is even) number = number / 2 if(number is odd) number = 3*number + 1 ``` #Task Your task is to make a function ```hotpo``` that takes a positive ```n``` as input and returns the number of times you need to perform this algorithm to get ```n = 1```. #Examples ``` hotpo(1) returns 0 (1 is already 1) hotpo(5) returns 5 5 -> 16 -> 8 -> 4 -> 2 -> 1 hotpo(6) returns 8 6 -> 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 hotpo(23) returns 15 23 -> 70 -> 35 -> 106 -> 53 -> 160 -> 80 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 ``` #References - Collatz conjecture wikipedia page: https://en.wikipedia.org/wiki/Collatz_conjecture
def hotpo(n): if n == 1: return 0 else: return 1 + (hotpo(n * 3 + 1) if n % 2 else hotpo(int(n / 2)))
def hotpo(n): if n == 1: return 0 else: return 1 + (hotpo(n * 3 + 1) if n % 2 else hotpo(int(n / 2)))
train
APPS_structured
Most languages have a `split` function that lets you turn a string like `“hello world”` into an array like`[“hello”, “world”]`. But what if we don't want to lose the separator? Something like `[“hello”, “ world”]`. #### Task: Your job is to implement a function, (`split_without_loss` in Ruby/Crystal, and `splitWithoutLoss` in JavaScript/CoffeeScript), that takes two arguments, `str` (`s` in Python), and `split_p`, and returns the string, split by `split_p`, but with the separator intact. There will be one '|' marker in `split_p`. `str` or `s` will never have a '|' in it. All the text before the marker is moved to the first string of the split, while all the text that is after it is moved to the second one. **Empty strings must be removed from the output, and the input should NOT be modified.** When tests such as `(str = "aaaa", split_p = "|aa")` are entered, do not split the string on overlapping regions. For this example, return `["aa", "aa"]`, not `["aa", "aa", "aa"]`. #### Examples (see example test cases for more): ```python split_without_loss("hello world!", " |") #=> ["hello ", "world!"] split_without_loss("hello world!", "o|rl") #=> ["hello wo", "rld!"] split_without_loss("hello world!", "h|ello world!") #=> ["h", "ello world!"] split_without_loss("hello world! hello world!", " |") #=> ["hello ", "world! ", "hello ", "world!"] split_without_loss("hello world! hello world!", "o|rl") #=> ["hello wo", "rld! hello wo", "rld!"] split_without_loss("hello hello hello", " | ") #=> ["hello ", " hello ", " hello"] split_without_loss(" hello world", " |") #=> [" ", "hello ", "world"] split_without_loss(" hello hello hello", " |") #=> [" ", " ", "hello ", "hello ", "hello"] split_without_loss(" hello hello hello ", " |") #=> [" ", " ", "hello ", "hello ", "hello ", " "] split_without_loss(" hello hello hello", "| ") #=> [" ", " hello", " hello", " hello"] ``` Also check out my other creations — [Identify Case](https://www.codewars.com/kata/identify-case), [Adding Fractions](https://www.codewars.com/kata/adding-fractions), [Random Integers](https://www.codewars.com/kata/random-integers), [Implement String#transpose](https://www.codewars.com/kata/implement-string-number-transpose), [Implement Array#transpose!](https://www.codewars.com/kata/implement-array-number-transpose), [Arrays and Procs #1](https://www.codewars.com/kata/arrays-and-procs-number-1), and [Arrays and Procs #2](https://www.codewars.com/kata/arrays-and-procs-number-2) If you notice any issues/bugs/missing test cases whatsoever, do not hesitate to report an issue or suggestion. Enjoy!
def split_without_loss(s, split_p): to_find = split_p.replace('|','') with_bar = s.replace(to_find,split_p) return [x for x in with_bar.split('|') if x != '']
def split_without_loss(s, split_p): to_find = split_p.replace('|','') with_bar = s.replace(to_find,split_p) return [x for x in with_bar.split('|') if x != '']
train
APPS_structured
You are given an equilateral triangle ΔABC with the side BC being the base. Each side of the triangle is of length L. There are L-1 additional points on each of the sides dividing the sides into equal parts of unit lengths. Points on the sides of the triangle are called major points. Joining these points with lines parallel to the sides of ΔABC will produce some more equilateral triangles. The intersection points of these parallel lines are called minor points. Look at the picture below. It contains - Major points: A, B, C, P1, P2, Q1, Q3, R1, R4, S1, S2, S3 (note that we consider A, B, C as major points as well) - Minor points: Q2, R2, R3 - Equilateral triangles ΔP1Q1Q2, ΔQ2S1S3, etc We consider an equilateral triangle to be valid if - Each of its vertices is either a major or a minor point, and - The distance from its base (the base of a triangle is the side parallel to BC) to BC is less than the distance from the other vertex of the triangle (i.e. opposite vertex that doesn't lie on the base of triangle) to BC. In the figure above, ΔQ2P1P2 is not a valid triangle but ΔQ2R2R3 is a valid triangle. You will be given L, the length of the original triangle ΔABC. You need to find out the number of valid equilateral triangles with side length exactly K. -----Input----- - The first line of the input contains an integer T denoting the number of test cases. The description of each testcase follows. - Each test case has one line containing two space-separated integers: L and K. -----Output----- For each testcase, print "Case i: ", and then the answer, where i is the testcase number, 1-indexed. -----Constraints----- - 1 ≤ T ≤ 500 - 1 ≤ L, K ≤ 5000 -----Example----- Input: 2 4 3 4 4 Output: Case 1: 3 Case 2: 1 -----Explanation----- The figure presented in the problem description is a triangle with side length 4. In testcase 1, the valid triangles are ΔAR1R4, ΔP1BS3, ΔP2S1C In testcase 2, the only valid triangle is ΔABC
# cook your dish here for _ in range(int(input())): l,k = map(int,input().split()) if k<=l: n=l-k+1 res=(n*(n+1))//2 else: res=0 print(f'Case {_+1}: {res}')
# cook your dish here for _ in range(int(input())): l,k = map(int,input().split()) if k<=l: n=l-k+1 res=(n*(n+1))//2 else: res=0 print(f'Case {_+1}: {res}')
train
APPS_structured
Given a non-empty binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root. Example 1: Input: [1,2,3] 1 / \ 2 3 Output: 6 Example 2: Input: [-10,9,20,null,null,15,7]   -10    / \   9  20     /  \    15   7 Output: 42
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def currentmax(self,root): leftval = 0 if root.left != None: leftval = self.currentmax(root.left) leftval = 0 if leftval < 0 else leftval rightval = 0 if root.right != None: rightval = self.currentmax(root.right) rightval = 0 if rightval < 0 else rightval currentnode = leftval + rightval + root.val if self.flag == 0: self.ans = currentnode self.flag = 1 else: self.ans = self.ans if self.ans > currentnode else currentnode return root.val + (leftval if leftval > rightval else rightval) def maxPathSum(self, root): self.ans = 0 self.flag = 0 self.currentmax(root) return self.ans
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def currentmax(self,root): leftval = 0 if root.left != None: leftval = self.currentmax(root.left) leftval = 0 if leftval < 0 else leftval rightval = 0 if root.right != None: rightval = self.currentmax(root.right) rightval = 0 if rightval < 0 else rightval currentnode = leftval + rightval + root.val if self.flag == 0: self.ans = currentnode self.flag = 1 else: self.ans = self.ans if self.ans > currentnode else currentnode return root.val + (leftval if leftval > rightval else rightval) def maxPathSum(self, root): self.ans = 0 self.flag = 0 self.currentmax(root) return self.ans
train
APPS_structured
A new task for you! You have to create a method, that corrects a given time string. There was a problem in addition, so many of the time strings are broken. Time-Format is european. So from "00:00:00" to "23:59:59". Some examples: "09:10:01" -> "09:10:01" "11:70:10" -> "12:10:10" "19:99:99" -> "20:40:39" "24:01:01" -> "00:01:01" If the input-string is null or empty return exactly this value! (empty string for C++) If the time-string-format is invalid, return null. (empty string for C++) Have fun coding it and please don't forget to vote and rank this kata! :-) I have created other katas. Have a look if you like coding and challenges.
import re def time_correct(s): try: assert re.match(r"^\d\d:\d\d:\d\d$", s) a, b, c = [int(x) for x in s.split(":")] except: return "" if s == "" else None b += c // 60 a += b // 60 return ":".join("{:>02}".format(x % y) for x, y in zip([a, b, c], [24, 60, 60]))
import re def time_correct(s): try: assert re.match(r"^\d\d:\d\d:\d\d$", s) a, b, c = [int(x) for x in s.split(":")] except: return "" if s == "" else None b += c // 60 a += b // 60 return ":".join("{:>02}".format(x % y) for x, y in zip([a, b, c], [24, 60, 60]))
train
APPS_structured
=====Problem Statement===== You are asked to ensure that the first and last names of people begin with a capital letter in their passports. For example, alison heck should be capitalised correctly as Alison Heck. alison heck => Alison Heck Given a full name, your task is to capitalize the name appropriately. =====Input Format===== A single line of input containing the full name, S. =====Constraints===== 0<len(S)<1000 The string consists of alphanumeric characters and spaces. Note: in a word only the first character is capitalized. Example 12abc when capitalized remains 12abc. =====Output Format===== Print the capitalized string, S.
s = input() s_ar = s.split(' ') final_ar = [] space = ' ' for w in s_ar: final_ar.append(w.capitalize()) print((space.join(final_ar)))
s = input() s_ar = s.split(' ') final_ar = [] space = ' ' for w in s_ar: final_ar.append(w.capitalize()) print((space.join(final_ar)))
train
APPS_structured
How much bigger is a 16-inch pizza compared to an 8-inch pizza? A more pragmatic question is: How many 8-inch pizzas "fit" in a 16-incher? The answer, as it turns out, is exactly four 8-inch pizzas. For sizes that don't correspond to a round number of 8-inchers, you must round the number of slices (one 8-inch pizza = 8 slices), e.g.: ```python how_many_pizzas(16) -> "pizzas: 4, slices: 0" how_many_pizzas(12) -> "pizzas: 2, slices: 2" how_many_pizzas(8) -> "pizzas: 1, slices: 0" how_many_pizzas(6) -> "pizzas: 0, slices: 4" how_many_pizzas(0) -> "pizzas: 0, slices: 0" ``` Get coding quick, so you can choose the ideal size for your next meal!
def how_many_pizzas(n): return 'pizzas: {}, slices: {}'.format(*divmod(n * n // 8, 8))
def how_many_pizzas(n): return 'pizzas: {}, slices: {}'.format(*divmod(n * n // 8, 8))
train
APPS_structured
Vivek was quite bored with the lockdown, so he came up with an interesting task. He successfully completed this task and now, he would like you to solve it. You are given two strings $A$ and $B$, each with length $N$. Let's index the characters in each string from $0$ ― for each $i$ ($0 \le i < N$), the $i+1$-th characters of $A$ and $B$ are denoted by $A_i$ and $B_i$ respectively. You should convert $A$ to $B$ by performing operations of the following type: - Choose a subset $S$ of the set $\{0, 1, \ldots, N-1\}$. - Let $c$ be the alphabetically smallest character among $A_x$ for all $x \in S$. - For each $x \in S$, replace $A_x$ by $c$. You should find the smallest necessary number of operations or report that it is impossible to convert $A$ to $B$. If it is possible, you also need to find one way to convert $A$ to $B$ using this smallest number of operations. If there are multiple solutions, you may find any one. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains a single integer $N$. - The second line contains a single string $A$. - The third line contains a single string $B$. -----Output----- For each test case: - If it is impossible to convert $A$ to $B$, print a single line containing the integer $-1$. - Otherwise, first, print a line containing a single integer $K$ ― the minimum number of operations. - Then, print $K$ lines describing the operations. Each of these lines should contain a positive integer $Z$, followed by a space and $Z$ pairwise distinct space-separated integers from the set $\{0, 1, \ldots, N-1\}$ ― the elements of $S$. -----Constraints----- - $1 \le T \le 20$ - $1 \le N \le 10^3$ - $|A| = |B| = N$ - $A$ and $B$ contain only lowercase English letters -----Subtasks----- Subtask #1 (30 points): $B$ contains only characters 'a' and 'b' Subtask #2 (70 points): original constraints -----Example Input----- 3 5 abcab aabab 3 aaa aab 2 de cd -----Example Output----- 2 3 1 2 4 3 0 1 3 -1 -1 -----Explanation----- Example case 1: - First, we can choose $S = (1, 2, 4)$, so the character $c$ is 'b' and the string $A$ after this operation is "abbab". - Then, we choose $S = (0, 1, 3)$, so $c$ is 'a', and $A$ becomes "aabab". - There is no way to convert $A$ to $B$ in only one operation. Example case 2: We can see that it is impossible to convert $A$ to $B$ since $c$ is always 'a'. Example case 3: We can see again that it is impossible to convert $A$ to $B$ since $c$ cannot be 'c'.
import string ASCII_ASC = string.ascii_lowercase ASCII_DSC = sorted(ASCII_ASC, reverse=True) def int_input(): return int(input()) def array_input(data_type=int): if data_type != str: return list(map(data_type, input().split(""))) else: return list(map(str, input())) def solve(): N = int_input() A = array_input(data_type=str) B = array_input(data_type=str) for i in range(N): if A[i] < B[i]: print(-1) return res = [] for ch in ASCII_DSC: idx_pos = [] chk = False for i in range(0, N): if B[i] == ch and A[i] != ch: # print("ch",ch) idx_pos.append(i) # print("idx_pos", idx_pos) if chk is False and len(idx_pos): for i in range(0, N): if A[i] == ch: # print("setting chk = True") chk = True idx_pos.append(i) # print("now idx_pos",idx_pos) if chk is False and len(idx_pos): print(-1) return if len(idx_pos): res.append(idx_pos) for idx in idx_pos: A[idx] = ch print(len(res)) for arr in res: print(len(arr), " ".join(map(str, arr))) t = int_input() while t > 0: t -= 1 solve()
import string ASCII_ASC = string.ascii_lowercase ASCII_DSC = sorted(ASCII_ASC, reverse=True) def int_input(): return int(input()) def array_input(data_type=int): if data_type != str: return list(map(data_type, input().split(""))) else: return list(map(str, input())) def solve(): N = int_input() A = array_input(data_type=str) B = array_input(data_type=str) for i in range(N): if A[i] < B[i]: print(-1) return res = [] for ch in ASCII_DSC: idx_pos = [] chk = False for i in range(0, N): if B[i] == ch and A[i] != ch: # print("ch",ch) idx_pos.append(i) # print("idx_pos", idx_pos) if chk is False and len(idx_pos): for i in range(0, N): if A[i] == ch: # print("setting chk = True") chk = True idx_pos.append(i) # print("now idx_pos",idx_pos) if chk is False and len(idx_pos): print(-1) return if len(idx_pos): res.append(idx_pos) for idx in idx_pos: A[idx] = ch print(len(res)) for arr in res: print(len(arr), " ".join(map(str, arr))) t = int_input() while t > 0: t -= 1 solve()
train
APPS_structured
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses. Example 1: Input: numerator = 1, denominator = 2 Output: "0.5" Example 2: Input: numerator = 2, denominator = 1 Output: "2" Example 3: Input: numerator = 2, denominator = 3 Output: "0.(6)"
class Solution: def fractionToDecimal(self, numerator, denominator): """ :type numerator: int :type denominator: int :rtype: str """ sign=0 if numerator*denominator<0: sign =-1 numerator,denominator = abs(numerator),abs(denominator) n = numerator s ='' if n >denominator: s +=str(n//denominator) n %=denominator else: s ='0' if sign==-1: s = '-'+s if n == 0: return s s +='.' t =[n] x = n s1='' while 1: x *=10 s1 +=str(x//denominator) x %=denominator if x in t or x==0: break else: t.append(x) if x in t: s1=s1[:t.index(x)]+'('+s1[t.index(x):]+')' return s+s1
class Solution: def fractionToDecimal(self, numerator, denominator): """ :type numerator: int :type denominator: int :rtype: str """ sign=0 if numerator*denominator<0: sign =-1 numerator,denominator = abs(numerator),abs(denominator) n = numerator s ='' if n >denominator: s +=str(n//denominator) n %=denominator else: s ='0' if sign==-1: s = '-'+s if n == 0: return s s +='.' t =[n] x = n s1='' while 1: x *=10 s1 +=str(x//denominator) x %=denominator if x in t or x==0: break else: t.append(x) if x in t: s1=s1[:t.index(x)]+'('+s1[t.index(x):]+')' return s+s1
train
APPS_structured
This kata explores writing an AI for a two player, turn based game called *NIM*. The Board -------------- The board starts out with several piles of straw. Each pile has a random number of straws. ``` Pile 0: |||| Pile 1: || Pile 2: ||||| Pile 3: | Pile 4: |||||| ...or more concisely: [4,2,5,1,6] ``` The Rules -------------- - The players take turns picking a pile, and removing any number of straws from the pile they pick - A player must pick at least one straw - If a player picks the last straw, she wins! The Task ------------ In this kata, you have to write an AI to play the straw picking game. You have to encode an AI in a function `choose_move` (or `chooseMove`, or `choose-move`) that takes a board, represented as a list of positive integers, and returns ```python (pile_index, number_of_straws) ``` Which refers to an index of a pile on the board, and some none-zero number of straws to draw from that pile. The test suite is written so that your AI is expected to play 50 games and win every game it plays.
from operator import xor from itertools import imap def choose_move(game_state): ns = reduce(xor, game_state) for i, p, s in imap(lambda (k, v): (k, v, ns ^ v), enumerate(game_state)): if s < p: return (i, p - s)
from operator import xor from itertools import imap def choose_move(game_state): ns = reduce(xor, game_state) for i, p, s in imap(lambda (k, v): (k, v, ns ^ v), enumerate(game_state)): if s < p: return (i, p - s)
train
APPS_structured
Consider having a cow that gives a child every year from her fourth year of life on and all her subsequent children do the same. After n years how many cows will you have? Return null if n is not an integer. Note: Assume all the cows are alive after n years.
from collections import deque def count_cows(n): if not isinstance(n, int): return None calves = deque([1, 0, 0]) cows = 0 for i in range(n): cows += calves.pop() calves.appendleft(cows) return cows + sum(calves)
from collections import deque def count_cows(n): if not isinstance(n, int): return None calves = deque([1, 0, 0]) cows = 0 for i in range(n): cows += calves.pop() calves.appendleft(cows) return cows + sum(calves)
train
APPS_structured
Write a function that takes a positive integer n, sums all the cubed values from 1 to n, and returns that sum. Assume that the input n will always be a positive integer. Examples: ```python sum_cubes(2) > 9 # sum of the cubes of 1 and 2 is 1 + 8 ```
def sum_cubes(n): return (n*(n+1)//2)**2
def sum_cubes(n): return (n*(n+1)//2)**2
train
APPS_structured
table { width: 236px; } table, tr, td { border: 0px; } In a grid of 4 by 4 squares you want to place a skyscraper in each square with only some clues: The height of the skyscrapers is between 1 and 4 No two skyscrapers in a row or column may have the same number of floors A clue is the number of skyscrapers that you can see in a row or column from the outside Higher skyscrapers block the view of lower skyscrapers located behind them Can you write a program that can solve this puzzle? Example: To understand how the puzzle works, this is an example of a row with 2 clues. Seen from the left side there are 4 buildings visible while seen from the right side only 1:  4  1 There is only one way in which the skyscrapers can be placed. From left-to-right all four buildings must be visible and no building may hide behind another building:  4  1  2  3  4  1 Example of a 4 by 4 puzzle with the solution:  1  2  2  1  3  1  2  2  1  4  3  3  4  1  2  2  1  4  2  3  1  1  3  2  4  3 Task: Finish:
from itertools import chain, product def unique_products(sets, excluding=frozenset()): """ Calculates cartesian product between the sets passed as parameter, only keeping products with unique numbers. """ if not sets: yield () return for x in sets[0] - excluding: for rest in unique_products(sets[1:], excluding | {x}): yield (x,) + rest def solve_column(column, clue): # First calculates all valid fillings with the given column, than merges the solutions in a single list where each # cell is the set containing the values in the same position of each solution. # [column=[{1, 2, 3}, {1, 2, 3}, {1, 2}, {4}], clue=2] -> [(3, 1, 2, 4), (3, 2, 1, 4)] -> [{3}, {1, 2}, {1, 2}, {4}] combos = [set(x) for x in list(zip(*[x for x in unique_products(column) if see(x) == clue]))] for i in range(len(column)): column[i] -= column[i] - combos[i] def see(column): """ Calculates how many buildings can be viewed. """ visible = tallest = 0 for building in column: visible += building > tallest tallest = max(building, tallest) return visible def simplify(column, clue, n): if clue is 1: column[0] -= set(range(1, n)) # the highest building must be in the first cell elif clue > 0: # if clue is 0 means no hint for i in range(clue - 1): column[i] -= set(range(n, n + i + 1 - clue, -1)) solve_column(column, clue) def solve_cross(city, x, y): """ Removes from the same row and column the number found at (x, y), if the cell contains only one number. :type city: list of (list of set) """ if len(city[x][y]) is not 1: solve_uniqueness(city, x, y) return for i in chain(range(x), range(x + 1, len(city))): city[i][y] -= city[x][y] for j in chain(range(y), range(y + 1, len(city))): city[x][j] -= city[x][y] def solve_uniqueness(city, x, y): """ Checks if one of the numbers in the cell city[x][y] compares only once in the same row / column. """ for n in city[x][y]: # checks if a number appears only once in the row / column if not any([n in city[i][y] for i in chain(range(x), range(x + 1, len(city)))]) or \ not any([n in city[x][j] for j in chain(range(y), range(y + 1, len(city)))]): city[x][y].clear() city[x][y].add(n) solve_cross(city, x, y) break def solve(n, clues): city = list(list(set(range(1, n + 1)) for i in range(n)) for j in range(n)) while not all([len(cell) is 1 for row in city for cell in row]): for i in range(n): for j in range(n): simplify([city[k][j] for k in range(n)], clues[i * n + j], n) for s in range(n): for t in range(n): solve_cross(city, s, t) city = [list(row) for row in reversed(list(zip(*city)))] # rotates the city 90° anti-clockwise return tuple(tuple(cell.pop() for cell in row) for row in city) solve_puzzle = lambda x: solve(4, x)
from itertools import chain, product def unique_products(sets, excluding=frozenset()): """ Calculates cartesian product between the sets passed as parameter, only keeping products with unique numbers. """ if not sets: yield () return for x in sets[0] - excluding: for rest in unique_products(sets[1:], excluding | {x}): yield (x,) + rest def solve_column(column, clue): # First calculates all valid fillings with the given column, than merges the solutions in a single list where each # cell is the set containing the values in the same position of each solution. # [column=[{1, 2, 3}, {1, 2, 3}, {1, 2}, {4}], clue=2] -> [(3, 1, 2, 4), (3, 2, 1, 4)] -> [{3}, {1, 2}, {1, 2}, {4}] combos = [set(x) for x in list(zip(*[x for x in unique_products(column) if see(x) == clue]))] for i in range(len(column)): column[i] -= column[i] - combos[i] def see(column): """ Calculates how many buildings can be viewed. """ visible = tallest = 0 for building in column: visible += building > tallest tallest = max(building, tallest) return visible def simplify(column, clue, n): if clue is 1: column[0] -= set(range(1, n)) # the highest building must be in the first cell elif clue > 0: # if clue is 0 means no hint for i in range(clue - 1): column[i] -= set(range(n, n + i + 1 - clue, -1)) solve_column(column, clue) def solve_cross(city, x, y): """ Removes from the same row and column the number found at (x, y), if the cell contains only one number. :type city: list of (list of set) """ if len(city[x][y]) is not 1: solve_uniqueness(city, x, y) return for i in chain(range(x), range(x + 1, len(city))): city[i][y] -= city[x][y] for j in chain(range(y), range(y + 1, len(city))): city[x][j] -= city[x][y] def solve_uniqueness(city, x, y): """ Checks if one of the numbers in the cell city[x][y] compares only once in the same row / column. """ for n in city[x][y]: # checks if a number appears only once in the row / column if not any([n in city[i][y] for i in chain(range(x), range(x + 1, len(city)))]) or \ not any([n in city[x][j] for j in chain(range(y), range(y + 1, len(city)))]): city[x][y].clear() city[x][y].add(n) solve_cross(city, x, y) break def solve(n, clues): city = list(list(set(range(1, n + 1)) for i in range(n)) for j in range(n)) while not all([len(cell) is 1 for row in city for cell in row]): for i in range(n): for j in range(n): simplify([city[k][j] for k in range(n)], clues[i * n + j], n) for s in range(n): for t in range(n): solve_cross(city, s, t) city = [list(row) for row in reversed(list(zip(*city)))] # rotates the city 90° anti-clockwise return tuple(tuple(cell.pop() for cell in row) for row in city) solve_puzzle = lambda x: solve(4, x)
train
APPS_structured
In this kata, your job is to return the two distinct highest values in a list. If there're less than 2 unique values, return as many of them, as possible. The result should also be ordered from highest to lowest. Examples: ``` [4, 10, 10, 9] => [10, 9] [1, 1, 1] => [1] [] => [] ```
def two_highest(arg1): x = [] y = [] z = [] if len(arg1) == 0: return [] elif len(arg1) == 1: return arg1 else: x = sorted(arg1, reverse = True) for i in range(len(x)): if x[i] in y: y = y else: y.append(x[i]) z.append(y[0]) z.append(y[1]) return z
def two_highest(arg1): x = [] y = [] z = [] if len(arg1) == 0: return [] elif len(arg1) == 1: return arg1 else: x = sorted(arg1, reverse = True) for i in range(len(x)): if x[i] in y: y = y else: y.append(x[i]) z.append(y[0]) z.append(y[1]) return z
train
APPS_structured
You receive the name of a city as a string, and you need to return a string that shows how many times each letter shows up in the string by using an asterisk (`*`). For example: ``` "Chicago" --> "c:**,h:*,i:*,a:*,g:*,o:*" ``` As you can see, the letter `c` is shown only once, but with 2 asterisks. The return string should include **only the letters** (not the dashes, spaces, apostrophes, etc). There should be no spaces in the output, and the different letters are separated by a comma (`,`) as seen in the example above. Note that the return string must list the letters in order of their first appearence in the original string. More examples: ``` "Bangkok" --> "b:*,a:*,n:*,g:*,k:**,o:*" "Las Vegas" --> "l:*,a:**,s:**,v:*,e:*,g:*" ``` Have fun! ;)
import json def get_strings(city): city = city.lower() city = city.replace(" ","") c = {} for i in city: if i in c: c[i] += "*" else: c[i] = "*" final = json.dumps(c) final = (final.replace("{","").replace("}","").replace(" ","").replace('"',"")) return final
import json def get_strings(city): city = city.lower() city = city.replace(" ","") c = {} for i in city: if i in c: c[i] += "*" else: c[i] = "*" final = json.dumps(c) final = (final.replace("{","").replace("}","").replace(" ","").replace('"',"")) return final
train
APPS_structured
Given 2 strings, your job is to find out if there is a substring that appears in both strings. You will return true if you find a substring that appears in both strings, or false if you do not. We only care about substrings that are longer than one letter long. #Examples: ```` *Example 1* SubstringTest("Something","Fun"); //Returns false *Example 2* SubstringTest("Something","Home"); //Returns true ```` In the above example, example 2 returns true because both of the inputs contain the substring "me". (so**ME**thing and ho**ME**) In example 1, the method will return false because something and fun contain no common substrings. (We do not count the 'n' as a substring in this Kata because it is only 1 character long) #Rules: Lowercase and uppercase letters are the same. So 'A' == 'a'. We only count substrings that are > 1 in length. #Input: Two strings with both lower and upper cases. #Output: A boolean value determining if there is a common substring between the two inputs.
def substring_test(str1, str2): str1,str2 = str1.lower(),str2.lower() s1 = [str1[i:i+2] for i in range(len(str1)-1)] s2 = [str2[i:i+2] for i in range(len(str2)-1)] return len(set(s1).intersection(s2))>0
def substring_test(str1, str2): str1,str2 = str1.lower(),str2.lower() s1 = [str1[i:i+2] for i in range(len(str1)-1)] s2 = [str2[i:i+2] for i in range(len(str2)-1)] return len(set(s1).intersection(s2))>0
train
APPS_structured
Increasing COVID cases have created panic amongst the people of Chefland, so the government is starting to push for production of a vaccine. It has to report to the media about the exact date when vaccines will be available. There are two companies which are producing vaccines for COVID. Company A starts producing vaccines on day $D_1$ and it can produce $V_1$ vaccines per day. Company B starts producing vaccines on day $D_2$ and it can produce $V_2$ vaccines per day. Currently, we are on day $1$. We need a total of $P$ vaccines. How many days are required to produce enough vaccines? Formally, find the smallest integer $d$ such that we have enough vaccines at the end of the day $d$. -----Input----- - The first and only line of the input contains five space-separated integers $D_1$, $V_1$, $D_2$, $V_2$ and $P$. -----Output----- Print a single line containing one integer ― the smallest required number of days. -----Constraints----- - $1 \le D_1, V_1, D_2, V_2 \le 100$ - $1 \le P \le 1,000$ -----Subtasks----- Subtask #1 (30 points): $D_1 = D_2$ Subtask #2 (70 points): original constraints -----Example Input 1----- 1 2 1 3 14 -----Example Output 1----- 3 -----Explanation----- Since $D_1 = D_2 = 1$, we can produce $V_1 + V_2 = 5$ vaccines per day. In $3$ days, we produce $15$ vaccines, which satisfies our requirement of $14$ vaccines. -----Example Input 2----- 5 4 2 10 100 -----Example Output 2----- 9 -----Explanation----- There are $0$ vaccines produced on the first day, $10$ vaccines produced on each of days $2$, $3$ and $4$, and $14$ vaccines produced on the fifth and each subsequent day. In $9$ days, it makes a total of $0 + 10 \cdot 3 + 14 \cdot 5 = 100$ vaccines.
vacc=0 day=0 d1,v1,d2,v2,p=list(map(int,input().split())) for i in range(1,1000): if i>=d1: vacc=vacc+v1 if i>=d2: vacc=vacc+v2 day=day+1 if vacc>=p: break print(day)
vacc=0 day=0 d1,v1,d2,v2,p=list(map(int,input().split())) for i in range(1,1000): if i>=d1: vacc=vacc+v1 if i>=d2: vacc=vacc+v2 day=day+1 if vacc>=p: break print(day)
train
APPS_structured
We have a collection of rocks, each rock has a positive integer weight. Each turn, we choose any two rocks and smash them together.  Suppose the stones have weights x and y with x <= y.  The result of this smash is: If x == y, both stones are totally destroyed; If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x. At the end, there is at most 1 stone left.  Return the smallest possible weight of this stone (the weight is 0 if there are no stones left.) Example 1: Input: [2,7,4,1,8,1] Output: 1 Explanation: We can combine 2 and 4 to get 2 so the array converts to [2,7,1,8,1] then, we can combine 7 and 8 to get 1 so the array converts to [2,1,1,1] then, we can combine 2 and 1 to get 1 so the array converts to [1,1,1] then, we can combine 1 and 1 to get 0 so the array converts to [1] then that's the optimal value. Note: 1 <= stones.length <= 30 1 <= stones[i] <= 100
from functools import lru_cache class Solution: def lastStoneWeightII(self, stones: List[int]) -> int: n = len(stones) if n == 1: return stones[0] @lru_cache(None) def dfs(index, curSum): if index == n: return abs(curSum) return min(dfs(index + 1, curSum + stones[index]), dfs(index + 1, curSum - stones[index])) return dfs(0, 0)
from functools import lru_cache class Solution: def lastStoneWeightII(self, stones: List[int]) -> int: n = len(stones) if n == 1: return stones[0] @lru_cache(None) def dfs(index, curSum): if index == n: return abs(curSum) return min(dfs(index + 1, curSum + stones[index]), dfs(index + 1, curSum - stones[index])) return dfs(0, 0)
train
APPS_structured
Introduction The GADERYPOLUKI is a simple substitution cypher used in scouting to encrypt messages. The encryption is based on short, easy to remember key. The key is written as paired letters, which are in the cipher simple replacement. The most frequently used key is "GA-DE-RY-PO-LU-KI". ``` G => A g => a a => g A => G D => E etc. ``` The letters, which are not on the list of substitutes, stays in the encrypted text without changes. Task Your task is to help scouts to encrypt and decrypt thier messages. Write the `Encode` and `Decode` functions. Input/Output The input string consists of lowercase and uperrcase characters and white . The substitution has to be case-sensitive. Example # GADERYPOLUKI collection GADERYPOLUKI cypher vol 1 GADERYPOLUKI cypher vol 2 GADERYPOLUKI cypher vol 3 - Missing Key GADERYPOLUKI cypher vol 4 - Missing key madness
t = str.maketrans("gdrplkGDRPLKaeyouiAEYOUI", "aeyouiAEYOUIgdrplkGDRPLK") encode = decode = lambda s: s.translate(t)
t = str.maketrans("gdrplkGDRPLKaeyouiAEYOUI", "aeyouiAEYOUIgdrplkGDRPLK") encode = decode = lambda s: s.translate(t)
train
APPS_structured
Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition. The binary number returned should be a string.
def add_binary(a,b): total = a + b total = (bin(total)[2:]) return total
def add_binary(a,b): total = a + b total = (bin(total)[2:]) return total
train
APPS_structured
I have the `par` value for each hole on a golf course and my stroke `score` on each hole. I have them stored as strings, because I wrote them down on a sheet of paper. Right now, I'm using those strings to calculate my golf score by hand: take the difference between my actual `score` and the `par` of the hole, and add up the results for all 18 holes. For example: * If I took 7 shots on a hole where the par was 5, my score would be: 7 - 5 = 2 * If I got a hole-in-one where the par was 4, my score would be: 1 - 4 = -3. Doing all this math by hand is really hard! Can you help make my life easier? ## Task Overview Complete the function which accepts two strings and calculates the golf score of a game. Both strings will be of length 18, and each character in the string will be a number between 1 and 9 inclusive.
def digitsum(x): total = 0 for letter in str(x): total += ord(letter)-48 return total def golf_score_calculator(par, score): return digitsum(score) - digitsum(par)
def digitsum(x): total = 0 for letter in str(x): total += ord(letter)-48 return total def golf_score_calculator(par, score): return digitsum(score) - digitsum(par)
train
APPS_structured
Chef has decided to start home delivery from his restaurant. He hopes that he will get a lot of orders for delivery, however there is a concern. He doesn't have enough work forces for all the deliveries. For this he has came up with an idea - he will group together all those orders which have to be delivered in nearby areas. In particular, he has identified certain bidirectional roads which he calls as fast roads. They are short and usually traffic free, so the fast travel is possible along these roads. His plan is that he will send orders to locations A and B together if and only if it is possible to travel between A and B using only fast roads. Your task is, given the configuration of fast roads, identify which orders are to be sent together. -----Input----- First line of input contains an integer T, the number of test cases. Then T test cases follow. First line of each test case contains two space separated integers N and M, denoting number of locations and the number of fast roads. Then M lines follow each containing two space separated integers A and B, denoting that there is a fast road between locations A and B. Assume that locations are indexed by numbers from 0 to N-1. Next line contains an integer Q denoting the number of queries. Each of the next Q lines contain two integers X and Y. For each query you have to find out if orders meant for locations X and Y are to be sent together or not. Note that there might be multiple fast roads between same pair of locations, also there might be a fast road that links a location to itself. -----Output----- For each test case print Q lines - one for each query. Output "YO" if the orders are to be delivered together and "NO" otherwise (quotes for clarity). -----Constraints----- 1 ≤ T ≤ 100 1 ≤ N ≤ 100 1 ≤ M ≤ 1000 0 ≤ A, B, X, Y ≤ N-1 1 ≤ Q ≤ 3000 -----Example----- Input: 1 4 2 0 1 1 2 3 0 2 0 3 2 1 Output: YO NO YO -----Warning!----- There are large input and output files in this problem. Make sure you use fast enough I/O methods.
import sys sys.setrecursionlimit(10000) def dfs(n): ans = set() queue = [n] bool[n] = True ans.add(n) while queue!=[]: z = queue.pop(0) ans.add(z) for j in hash[z]: if bool[j] == False: bool[j] = True queue.append(j) return ans from collections import defaultdict t = int(input()) for _ in range(t): ans = [] hash = defaultdict(list) n,m = map(int,sys.stdin.readline().strip().split()) for i in range(m): a,b = map(int,sys.stdin.readline().strip().split()) hash[a].append(b) hash[b].append(a) for i in range(n): bool = [False]*n z = dfs(i) hash[i] = z q = int(input()) for i in range(q): a,b = map(int,sys.stdin.readline().strip().split()) dfs(a) # print(bool) if b in hash[a]: z = 'YO' sys.stdout.write(z) print() else: z = 'NO' sys.stdout.write(z) print()
import sys sys.setrecursionlimit(10000) def dfs(n): ans = set() queue = [n] bool[n] = True ans.add(n) while queue!=[]: z = queue.pop(0) ans.add(z) for j in hash[z]: if bool[j] == False: bool[j] = True queue.append(j) return ans from collections import defaultdict t = int(input()) for _ in range(t): ans = [] hash = defaultdict(list) n,m = map(int,sys.stdin.readline().strip().split()) for i in range(m): a,b = map(int,sys.stdin.readline().strip().split()) hash[a].append(b) hash[b].append(a) for i in range(n): bool = [False]*n z = dfs(i) hash[i] = z q = int(input()) for i in range(q): a,b = map(int,sys.stdin.readline().strip().split()) dfs(a) # print(bool) if b in hash[a]: z = 'YO' sys.stdout.write(z) print() else: z = 'NO' sys.stdout.write(z) print()
train
APPS_structured
Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result. Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0). If the input string is empty, return an empty string. The words in the input String will only contain valid consecutive numbers. ## Examples ``` "is2 Thi1s T4est 3a" --> "Thi1s is2 3a T4est" "4of Fo1r pe6ople g3ood th5e the2" --> "Fo1r the2 g3ood 4of th5e pe6ople" "" --> "" ```
order = lambda xs: ' '.join(sorted(xs.split(), key=min))
order = lambda xs: ' '.join(sorted(xs.split(), key=min))
train
APPS_structured
You are given two positive integers $N$ and $K$, where $K \le N$. Find a sequence $A_1, A_2, \ldots, A_N$ such that: - for each valid $i$, $A_i$ is either $i$ or $-i$ - there are exactly $K$ values of $i$ such that $1 \le i \le N$ and $A_1 + A_2 + \ldots + A_i > 0$ If there are multiple solutions, you may print any one of them. It can be proved that at least one solution always exists. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first and only line of each test case contains two space-separated integers $N$ and $K$. -----Output----- For each test case, print a single line containing $N$ space-separated integers $A_1, A_2, \ldots, A_N$. -----Constraints----- - $1 \le T \le 1,000$ - $1 \le K \le N \le 1,000$ -----Subtasks----- Subtask #1 (10 points): $N \le 10$ Subtask #2 (90 points): original constraints -----Example Input----- 1 3 3 -----Example Output----- 1 2 3
# cook your dish here t=int(input()) import math while t: t=t-1 n,k=input().split() n=int(n) k=int(k) l=[-1*(i+1) for i in range(n)] for i in range(1,n,2): l[i]=l[i]*(-1) #print(l) if k-(math.floor(n/2))>0: s=k-(math.floor(n/2)) while s: for i in range(n-1,-1,-1): # print(i,s,"*",l) if l[i]<0: l[i]=(-1)*l[i] s=s-1 break if (math.floor(n/2))-k>0: s=(math.floor(n/2))-k while s: for i in range(n-1,-1,-1): if l[i]>0: l[i]=(-1)*l[i] s=s-1 break for i in range(n): print(l[i],end=" ")
# cook your dish here t=int(input()) import math while t: t=t-1 n,k=input().split() n=int(n) k=int(k) l=[-1*(i+1) for i in range(n)] for i in range(1,n,2): l[i]=l[i]*(-1) #print(l) if k-(math.floor(n/2))>0: s=k-(math.floor(n/2)) while s: for i in range(n-1,-1,-1): # print(i,s,"*",l) if l[i]<0: l[i]=(-1)*l[i] s=s-1 break if (math.floor(n/2))-k>0: s=(math.floor(n/2))-k while s: for i in range(n-1,-1,-1): if l[i]>0: l[i]=(-1)*l[i] s=s-1 break for i in range(n): print(l[i],end=" ")
train
APPS_structured
=====Problem Statement===== You are given n words. Some words may repeat. For each word, output its number of occurrences. The output order should correspond with the input order of appearance of the word. See the sample input/output for clarification. Note: Each input line ends with a "\n" character. =====Constraints===== 1≤n≤10^5 The sum of the lengths of all the words do not exceed 10^6 All the words are composed of lowercase English letters only. =====Input Format===== The first line contains the integer, n. The next n lines each contain a word. =====Output Format===== Output 2 lines. On the first line, output the number of distinct words from the input. On the second line, output the number of occurrences for each distinct word according to their appearance in the input.
from collections import Counter, OrderedDict class OrderedCounter(Counter,OrderedDict): pass word_ar = [] n = int(input()) for i in range(n): word_ar.append(input().strip()) word_counter = OrderedCounter(word_ar) print(len(word_counter)) for word in word_counter: print(word_counter[word],end=' ')
from collections import Counter, OrderedDict class OrderedCounter(Counter,OrderedDict): pass word_ar = [] n = int(input()) for i in range(n): word_ar.append(input().strip()) word_counter = OrderedCounter(word_ar) print(len(word_counter)) for word in word_counter: print(word_counter[word],end=' ')
train
APPS_structured
#### Task: Your job here is to implement a method, `approx_root` in Ruby/Python/Crystal and `approxRoot` in JavaScript/CoffeeScript, that takes one argument, `n`, and returns the approximate square root of that number, rounded to the nearest hundredth and computed in the following manner. 1. Start with `n = 213` (as an example). 2. To approximate the square root of n, we will first find the greatest perfect square that is below or equal to `n`. (In this example, that would be 196, or 14 squared.) We will call the square root of this number (which means sqrt 196, or 14) `base`. 3. Then, we will take the lowest perfect square that is greater than or equal to `n`. (In this example, that would be 225, or 15 squared.) 4. Next, subtract 196 (greatest perfect square less than or equal to `n`) from `n`. (213 - 196 = **17**) We will call this value `diff_gn`. 5. Find the difference between the lowest perfect square greater than or equal to `n` and the greatest perfect square less than or equal to `n`. (225 – 196 = **29**) We will call this value `diff_lg`. 6. Your final answer is `base` + (`diff_gn` / `diff_lg`). In this example: 14 + (17 / 29) which is 14.59, rounded to the nearest hundredth. Just to clarify, if the input is a perfect square itself, you should return the exact square of the input. In case you are curious, the approximation (computed like above) for 213 rounded to four decimal places is 14.5862. The actual square root of 213 is 14.5945. Inputs will always be positive whole numbers. If you are having trouble understanding it, let me know with a comment, or take a look at the second group of the example cases. #### Some examples: ```python approx_root(400) #=> 20 approx_root(401) #=> # smallest perfect square above 401 is 441 or 21 squared # greatest perfect square below 401 is 400 or 20 squared # difference between 441 and 400 is 41 # difference between 401 and 400 is 1 # answer is 20 + (1 / 41) which becomes 20.02, rounded to the nearest hundredth # final answer = 20.02. approx_root(2) #=> # smallest perfect square above 2 is 4 or 2 squared # greatest perfect square below 2 is 1 or 1 squared # difference between 4 and 1 is 3 # difference between 2 and 1 is 1 # answer is 1 + (1 / 3), which becomes 1.33, rounded to the nearest hundredth # final answer = 1.33. # math.sqrt() isn't disabled. ``` Also check out my other creations — [Square Roots: Simplifying/Desimplifying](https://www.codewars.com/kata/square-roots-simplify-slash-desimplify/), [Square and Cubic Factors](https://www.codewars.com/kata/square-and-cubic-factors), [Keep the Order](https://www.codewars.com/kata/keep-the-order), [Naming Files](https://www.codewars.com/kata/naming-files), [Elections: Weighted Average](https://www.codewars.com/kata/elections-weighted-average), [Identify Case](https://www.codewars.com/kata/identify-case), [Split Without Loss](https://www.codewars.com/kata/split-without-loss), [Adding Fractions](https://www.codewars.com/kata/adding-fractions), [Random Integers](https://www.codewars.com/kata/random-integers), [Implement String#transpose](https://www.codewars.com/kata/implement-string-number-transpose), [Implement Array#transpose!](https://www.codewars.com/kata/implement-array-number-transpose), [Arrays and Procs #1](https://www.codewars.com/kata/arrays-and-procs-number-1), and [Arrays and Procs #2](https://www.codewars.com/kata/arrays-and-procs-number-2). If you notice any issues or have any suggestions/comments whatsoever, please don't hesitate to mark an issue or just comment. Thanks!
approx_root=r=lambda n,i=0:n>(i+1)**2and r(n,i+1)or round(i+(n-i*i)/(2*i+1),2)
approx_root=r=lambda n,i=0:n>(i+1)**2and r(n,i+1)or round(i+(n-i*i)/(2*i+1),2)
train
APPS_structured
Given a sorted array of numbers, return the summary of its ranges. ## Examples ```python summary_ranges([1, 2, 3, 4]) == ["1->4"] summary_ranges([1, 1, 1, 1, 1]) == ["1"] summary_ranges([0, 1, 2, 5, 6, 9]) == ["0->2", "5->6", "9"] summary_ranges([0, 1, 2, 3, 3, 3, 4, 5, 6, 7]) == ["0->7"] summary_ranges([0, 1, 2, 3, 3, 3, 4, 4, 5, 6, 7, 7, 9, 9, 10]) == ["0->7", "9->10"] summary_ranges([-2, 0, 1, 2, 3, 3, 3, 4, 4, 5, 6, 7, 7, 9, 9, 10, 12]) == ["-2", "0->7", "9->10", "12"] ```
def summary_ranges(a): a,i,li = sorted(set(a), key=a.index),0,[] while i < len(a): temp = [a[i]] ; i += 1 while i < len(a) and temp[-1] + 1 == a[i] : temp.append(a[i]) ; i += 1 li.append(temp) return [f"{i[0]}->{i[-1]}" if len(i) > 1 else f"{i[0]}" for i in li]
def summary_ranges(a): a,i,li = sorted(set(a), key=a.index),0,[] while i < len(a): temp = [a[i]] ; i += 1 while i < len(a) and temp[-1] + 1 == a[i] : temp.append(a[i]) ; i += 1 li.append(temp) return [f"{i[0]}->{i[-1]}" if len(i) > 1 else f"{i[0]}" for i in li]
train
APPS_structured
In mathematics, the factorial of integer 'n' is written as 'n!'. It is equal to the product of n and every integer preceding it. For example: **5! = 1 x 2 x 3 x 4 x 5 = 120** Your mission is simple: write a function that takes an integer 'n' and returns 'n!'. You are guaranteed an integer argument. For any values outside the positive range, return `null`, `nil` or `None` . **Note:** 0! is always equal to 1. Negative values should return null; For more on Factorials : http://en.wikipedia.org/wiki/Factorial
import math def factorial(n): if n < 0: return None return math.factorial(n)
import math def factorial(n): if n < 0: return None return math.factorial(n)
train
APPS_structured