input
stringlengths
50
13.9k
output_program
stringlengths
5
655k
output_answer
stringlengths
5
655k
split
stringclasses
1 value
dataset
stringclasses
1 value
Dhiraj loves Chocolates.He loves chocolates so much that he can eat up to $1000$ chocolates a day. But his mom is fed up by this habit of him and decides to take things in her hand. Its diwali Season and Dhiraj has got a lot of boxes of chocolates and Dhiraj's mom is afraid that dhiraj might eat all boxes of chocolates. So she told Dhiraj that he can eat only exactly $k$ number of chocolates and dhiraj has to finish all the chocolates in box selected by him and then move on to next box of chocolate.Now Dhiraj is confused that whether he will be able to eat $k$ number of chocolates or not. Since dhiraj is weak at maths,he asks for your help to tell him whether he can eat $k$ number of chocolates or not. So given number of chocolates are $k$ which dhiraj has to eat and the boxes of chocolates each containing some number of chocolates, tell whether dhiraj will be able to eat $k$ number of chocolates or not. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - $k$, representing the number of chocolates dhiraj has to eat. - the third line contains $N$ representing the no. of boxes of chocolates. - fourth line contains list of $a[]$ size $N$ specifying the number of chocolates in each Box. -----Output:----- - For each testcase, output in a single line answer $0$ or $1$. - $0$ if dhiraj cant eat $k$ chocolates from given combination and $1$ if he can eat $k$ chocolates from given combination. -----Constraints----- - $1 \leq T \leq 100$ - $1 \leq K \leq 10^7$ - $1 \leq N \leq 800$ - $1 \leq a[i] \leq 10^3$ -----Sample Input:----- 2 20 5 8 7 2 10 5 11 4 6 8 2 10 -----Sample Output:----- 1 0
def isSubsetSum(set, n, sum): # The value of subset[i][j] will be # true if there is a # subset of set[0..j-1] with sum equal to i subset = ([[False for i in range(sum + 1)] for i in range(n + 1)]) # If sum is 0, then answer is true for i in range(n + 1): subset[i][0] = True # If sum is not 0 and set is empty, # then answer is false for i in range(1, sum + 1): subset[0][i] = False # Fill the subset table in botton up manner for i in range(1, n + 1): for j in range(1, sum + 1): if j < set[i - 1]: subset[i][j] = subset[i - 1][j] if j >= set[i - 1]: subset[i][j] = (subset[i - 1][j] or subset[i - 1][j - set[i - 1]]) # uncomment this code to print table # for i in range(n + 1): # for j in range(sum + 1): # print(subset[i][j], end =" ") # print() return subset[n][sum] for _ in range(int(input())): K = int(input()) N = int(input()) array = list(map(int, input().split())) if K > sum(array): print(0) elif isSubsetSum(array, N , K): print(1) else: print(0)
def isSubsetSum(set, n, sum): # The value of subset[i][j] will be # true if there is a # subset of set[0..j-1] with sum equal to i subset = ([[False for i in range(sum + 1)] for i in range(n + 1)]) # If sum is 0, then answer is true for i in range(n + 1): subset[i][0] = True # If sum is not 0 and set is empty, # then answer is false for i in range(1, sum + 1): subset[0][i] = False # Fill the subset table in botton up manner for i in range(1, n + 1): for j in range(1, sum + 1): if j < set[i - 1]: subset[i][j] = subset[i - 1][j] if j >= set[i - 1]: subset[i][j] = (subset[i - 1][j] or subset[i - 1][j - set[i - 1]]) # uncomment this code to print table # for i in range(n + 1): # for j in range(sum + 1): # print(subset[i][j], end =" ") # print() return subset[n][sum] for _ in range(int(input())): K = int(input()) N = int(input()) array = list(map(int, input().split())) if K > sum(array): print(0) elif isSubsetSum(array, N , K): print(1) else: print(0)
train
APPS_structured
The sequence of $m$ integers is called the permutation if it contains all integers from $1$ to $m$ exactly once. The number $m$ is called the length of the permutation. Dreamoon has two permutations $p_1$ and $p_2$ of non-zero lengths $l_1$ and $l_2$. Now Dreamoon concatenates these two permutations into another sequence $a$ of length $l_1 + l_2$. First $l_1$ elements of $a$ is the permutation $p_1$ and next $l_2$ elements of $a$ is the permutation $p_2$. You are given the sequence $a$, and you need to find two permutations $p_1$ and $p_2$. If there are several possible ways to restore them, you should find all of them. (Note that it is also possible that there will be no ways.) -----Input----- The first line contains an integer $t$ ($1 \le t \le 10\,000$) denoting the number of test cases in the input. Each test case contains two lines. The first line contains one integer $n$ ($2 \leq n \leq 200\,000$): the length of $a$. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq n-1$). The total sum of $n$ is less than $200\,000$. -----Output----- For each test case, the first line of output should contain one integer $k$: the number of ways to divide $a$ into permutations $p_1$ and $p_2$. Each of the next $k$ lines should contain two integers $l_1$ and $l_2$ ($1 \leq l_1, l_2 \leq n, l_1 + l_2 = n$), denoting, that it is possible to divide $a$ into two permutations of length $l_1$ and $l_2$ ($p_1$ is the first $l_1$ elements of $a$, and $p_2$ is the last $l_2$ elements of $a$). You can print solutions in any order. -----Example----- Input 6 5 1 4 3 2 1 6 2 4 1 3 2 1 4 2 1 1 3 4 1 3 3 1 12 2 1 3 4 5 6 7 8 9 1 10 2 3 1 1 1 Output 2 1 4 4 1 1 4 2 0 0 1 2 10 0 -----Note----- In the first example, two possible ways to divide $a$ into permutations are $\{1\} + \{4, 3, 2, 1\}$ and $\{1,4,3,2\} + \{1\}$. In the second example, the only way to divide $a$ into permutations is $\{2,4,1,3\} + \{2,1\}$. In the third example, there are no possible ways.
def readIntArray(): return list(map(int,input().split())) t = int(input()) for _ in range(t): n = int(input()) a = readIntArray() mp = {} for val in a: if val not in mp: mp[val] = 0 mp[val] += 1 l1 = max(a) l2 = n - l1 if l2 <= 0: print(0) continue good = True for i in range(1, l2 + 1): if i not in mp or mp[i] != 2: good = False break for i in range(l2 + 1, l1 + 1): if i not in mp or mp[i] != 1: good = False break if not good: print(0) continue mp = {} ans = set() cur = 0 st = set() used = set() for i in range(n): if a[i] in used: break st.add(a[i]) used.add(a[i]) while cur + 1 in st: st.remove(cur + 1) cur += 1 if cur == l1 or cur == l2 and len(st) == 0: ans.add((cur, n - cur)) print(len(ans)) for val in ans: print(val[0], val[1])
def readIntArray(): return list(map(int,input().split())) t = int(input()) for _ in range(t): n = int(input()) a = readIntArray() mp = {} for val in a: if val not in mp: mp[val] = 0 mp[val] += 1 l1 = max(a) l2 = n - l1 if l2 <= 0: print(0) continue good = True for i in range(1, l2 + 1): if i not in mp or mp[i] != 2: good = False break for i in range(l2 + 1, l1 + 1): if i not in mp or mp[i] != 1: good = False break if not good: print(0) continue mp = {} ans = set() cur = 0 st = set() used = set() for i in range(n): if a[i] in used: break st.add(a[i]) used.add(a[i]) while cur + 1 in st: st.remove(cur + 1) cur += 1 if cur == l1 or cur == l2 and len(st) == 0: ans.add((cur, n - cur)) print(len(ans)) for val in ans: print(val[0], val[1])
train
APPS_structured
Given three arrays of integers, return the sum of elements that are common in all three arrays. For example: ``` common([1,2,3],[5,3,2],[7,3,2]) = 5 because 2 & 3 are common in all 3 arrays common([1,2,2,3],[5,3,2,2],[7,3,2,2]) = 7 because 2,2 & 3 are common in the 3 arrays ``` More examples in the test cases. Good luck!
def common(a,b,c): d = set(a)&set(b)&set(c) a = [i for i in a if i in d] b = [i for i in b if i in d] c = [i for i in c if i in d] return sum([i*min(a.count(i), b.count(i), c.count(i)) for i in d])
def common(a,b,c): d = set(a)&set(b)&set(c) a = [i for i in a if i in d] b = [i for i in b if i in d] c = [i for i in c if i in d] return sum([i*min(a.count(i), b.count(i), c.count(i)) for i in d])
train
APPS_structured
In an array A of 0s and 1s, how many non-empty subarrays have sum S? Example 1: Input: A = [1,0,1,0,1], S = 2 Output: 4 Explanation: The 4 subarrays are bolded below: [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] Note: A.length <= 30000 0 <= S <= A.length A[i] is either 0 or 1.
class Solution: def numSubarraysWithSum(self, A: List[int], S: int) -> int: numToFreq = {} numToFreq[0] = 1 now_sum = 0 ans = 0 for num in A: now_sum += num if now_sum == S: ans += (numToFreq[0]) elif now_sum > S: if now_sum - S in numToFreq: ans += (numToFreq[now_sum - S]) if now_sum not in numToFreq: numToFreq[now_sum] = 0 numToFreq[now_sum] += 1 return ans
class Solution: def numSubarraysWithSum(self, A: List[int], S: int) -> int: numToFreq = {} numToFreq[0] = 1 now_sum = 0 ans = 0 for num in A: now_sum += num if now_sum == S: ans += (numToFreq[0]) elif now_sum > S: if now_sum - S in numToFreq: ans += (numToFreq[now_sum - S]) if now_sum not in numToFreq: numToFreq[now_sum] = 0 numToFreq[now_sum] += 1 return ans
train
APPS_structured
=====Problem Statement===== Given a list of rational numbers,find their product. Concept The reduce() function applies a function of two arguments cumulatively on a list of objects in succession from left to right to reduce it to one value. Say you have a list, say [1,2,3] and you have to find its sum. >>> reduce(lambda x, y : x + y,[1,2,3]) 6 You can also define an initial value. If it is specified, the function will assume initial value as the value given, and then reduce. It is equivalent to adding the initial value at the beginning of the list. For example: >>> reduce(lambda x, y : x + y, [1,2,3], -3) 3 >>> from fractions import gcd >>> reduce(gcd, [2,4,8], 3) 1 =====Input Format===== First line contains n, the number of rational numbers. The ith of next n lines contain two integers each, the numerator (N_i) and denominator (D_i) of the ith rational number in the list. =====Constraints===== 1≤n≤100 1≤N_i,D_i≤10^9 =====Output Format===== Print only one line containing the numerator and denominator of the product of the numbers in the list in its simplest form, i.e. numerator and denominator have no common divisor other than 1.
from fractions import Fraction from functools import reduce def product(fracs): t = Fraction(reduce(lambda x,y : x*y,fracs)) return t.numerator, t.denominator def __starting_point(): fracs = [] for _ in range(int(input())): fracs.append(Fraction(*list(map(int, input().split())))) result = product(fracs) print((*result)) ''' 3 1 2 3 4 10 6 ''' __starting_point()
from fractions import Fraction from functools import reduce def product(fracs): t = Fraction(reduce(lambda x,y : x*y,fracs)) return t.numerator, t.denominator def __starting_point(): fracs = [] for _ in range(int(input())): fracs.append(Fraction(*list(map(int, input().split())))) result = product(fracs) print((*result)) ''' 3 1 2 3 4 10 6 ''' __starting_point()
train
APPS_structured
## Description Beggar Thy Neighbour is a card game taught to me by my parents when I was a small child, and is a game I like to play with my young kids today. In this kata you will be given two player hands to be played. And must return the index of the player who will win. ## Rules of the game - Special cards are: Jacks, Queens, Kings and Aces - The object of the game is to win all the cards. - Any player that cannot play a card is out of the game. To start: - The 52 cards in a standard deck are shuffled. - The cards are dealt equally between all players. To play: - The first player turns over and plays the top card from their hand into a common pile. - If the card is not special - then the second player plays their next card onto the pile, and play continues back to the first player. - If the card is a Jack, Queen, King or Ace, the other player must play 1, 2, 3 or 4 penalty cards respectively. - If no special cards are played during a penalty, then the player that played the special card, takes the common pile. - If a special card is played during a penalty, then the penalty moves back to the previous player immediately with the size of the new penalty defined by the new special card. It is possible for this process to repeat several times in one play. Whoever played the last special card, wins the common pile. - The winner of the common pile, places it on the bottom of their hand, and then starts the next common pile. It is theorised that an initial deal may never end, though so far all of my games have ended! For that reason, if 10,000 cards are played and no one has won, return `None`. ## Card Encoding Cards are represented with a two character code. The first characater will be one of A23456789TJQK representing Ace, 2 though 9, Ten, Jack, Queen, King respectively. The second character is the suit, 'S', 'H', 'C', or 'D' representing Spades, Hearts, Clubs and Diamonds respectively. For example a hand of `["TD", "AC", "5H"]` would represent 10 of Diamonds, Ace of Clubs, and 5 of hearts. ## Mini Example Game Given the following hands: `Player 1: [9C, JC, 2H, QC], Player 2: [TD, JH, 6H, 9S]` Play would flow as follows: ``` Start - P1: [9C, JC, 2H, QC], P2: [TD, JH, 6H, 9S], Common: [] Turn 1 - P1: [JC, 2H, QC], P2: [TD, JH, 6H, 9S], Common: [9C] Turn 2 - P1: [JC, 2H, QC], P2: [JH, 6H, 9S], Common: [9C, TD] Turn 3 - P1: [2H, QC], P2: [JH, 6H, 9S], Common: [9C, TD, JC] ``` Player 1 plays a Jack, player 2 pays 1 penalty ``` Turn 4 - P1: [2H, QC], P2: [6H, 9S], Common: [9C, TD, JC, JH] ``` Player 2 plays a Jack, player 1 pays 1 penalty ``` Turn 5 - P1: [QC], P2: [6H, 9S], Common: [9C, TD, JC, JH, 2H] ``` Player 2 wins the common pool and starts the next game ``` Turn 6 - P1: [QC], P2: [9S, 9C, TD, JC, JH, 2H], Common: [6H] Turn 7 - P1: [], P2: [9S, 9C, TD, JC, JH, 2H], Common: [6H, QC] ``` Player 1 plays a Queen, player 2 pays 2 penalties ``` Turn 8 - P1: [], P2: [9C, TD, JC, JH, 2H], Common: [6H, QC, 9S] Turn 9 - P1: [], P2: [TD, JC, JH, 2H], Common: [6H, QC, 9S, 9C] ``` Player 1 wins the common pool and starts the next game ``` Turn 10 - P1: [QC, 9S, 9C], P2: [TD, JC, JH, 2H], Common: [6H] ``` And so on... with player 2 eventually winning. Good luck!
SPECIAL = {"J": 1, "Q": 2, "K": 3, "A": 4} def who_wins_beggar_thy_neighbour(hand_1, hand_2): turn = 0 players = [[SPECIAL.get(card[0], 0) for card in hand] for hand in (hand_1, hand_2)] pot = [] penalty = 0 time = 0 while time < 10000: time += 1 try: if penalty: for __ in range(penalty): card = players[turn].pop(0) pot.append(card) if card: break else: players[(turn+1) % 2] += pot pot = [] else: card = players[turn].pop(0) pot.append(card) except IndexError: return (turn+1) % 2 penalty = card turn = (turn+1) % 2
SPECIAL = {"J": 1, "Q": 2, "K": 3, "A": 4} def who_wins_beggar_thy_neighbour(hand_1, hand_2): turn = 0 players = [[SPECIAL.get(card[0], 0) for card in hand] for hand in (hand_1, hand_2)] pot = [] penalty = 0 time = 0 while time < 10000: time += 1 try: if penalty: for __ in range(penalty): card = players[turn].pop(0) pot.append(card) if card: break else: players[(turn+1) % 2] += pot pot = [] else: card = players[turn].pop(0) pot.append(card) except IndexError: return (turn+1) % 2 penalty = card turn = (turn+1) % 2
train
APPS_structured
You have a laser with P amount of energy in it. You are playing a game where you have to use the laser to destroy some crystals, each with some health of their own. Initially, you have 0 points. Each crystal has an associated health. The health of the ith crystal is given by health[i]. You can perform one of the two actions: - At the cost of health[i] energy, you can destroy the ith crystal and gain 1 point. You can only perform this action if your laser has atleast health[i] energy in it. - At the cost of 1 point, you can destroy the ith crystal and refuel the laser's energy by an amount equal to health[i]. This action can only be performed if you have atleast one point. Note: Each crystal can only be destroyed once. Determine the maximum number of points you can obtain by destroying any number of crystals and performing either action as you wish. -----Input:----- - First line will contain n, number of crystals. - Second line will contain space separated integers, health of each crystal. - Third line will contain an integer P, initial energy of the laser. -----Output:----- Print the largest number of points we can have after destroying any number of crystals. -----Constraints----- - health.length <= 1000 - 0 <= health[i] < 10000 - 0 <= P < 10000 -----Subtasks----- - 40 points : 1 <= health.length <= 100 - 60 points : health.length > 100 -----Sample Input 1:----- 1 200 100 -----Sample Output 1:----- 0 -----Explanation:----- The laser initially has only 100 energy. Since the only crystal requires 200 energy to destroy, we cannot perform any action here, and the game ends. The number of points is zero. -----Sample Input 2:----- 2 100 200 150 -----Sample Output 2:----- 1 -----Explanation:----- The laser has 150 energy. We can consume 100 energy and destroy the first crystal and gain 1 point. The remaining energy is 50, which is not enough to destroy the other crystal. We end the game here as we have the maximum possible points attainable.
n=int(input()) arr=list(map(int,input().split())) h=int(input()) arr.sort() ans=0 i=0 if n==1 and h>=arr[0]: print(1) return while(len(arr)!=0): if arr[i]>h and len(arr)>1: h+=arr[-1] ans-=1 del arr[-1] elif len(arr)==1: break h-=arr[i] del arr[i] ans+=1 print(max(ans,0))
n=int(input()) arr=list(map(int,input().split())) h=int(input()) arr.sort() ans=0 i=0 if n==1 and h>=arr[0]: print(1) return while(len(arr)!=0): if arr[i]>h and len(arr)>1: h+=arr[-1] ans-=1 del arr[-1] elif len(arr)==1: break h-=arr[i] del arr[i] ans+=1 print(max(ans,0))
train
APPS_structured
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes. Strictly speaking, it makes a photo of all points with coordinates $(x, y)$, such that $x_1 \leq x \leq x_2$ and $y_1 \leq y \leq y_2$, where $(x_1, y_1)$ and $(x_2, y_2)$ are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero. After taking the photo, Pavel wrote down coordinates of $n$ of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky. Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points. Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle. -----Input----- The first line of the input contains an only integer $n$ ($1 \leq n \leq 100\,000$), the number of points in Pavel's records. The second line contains $2 \cdot n$ integers $a_1$, $a_2$, ..., $a_{2 \cdot n}$ ($1 \leq a_i \leq 10^9$), coordinates, written by Pavel in some order. -----Output----- Print the only integer, the minimal area of the rectangle which could have contained all points from Pavel's records. -----Examples----- Input 4 4 1 3 2 3 2 1 3 Output 1 Input 3 5 8 5 5 7 5 Output 0 -----Note----- In the first sample stars in Pavel's records can be $(1, 3)$, $(1, 3)$, $(2, 3)$, $(2, 4)$. In this case, the minimal area of the rectangle, which contains all these points is $1$ (rectangle with corners at $(1, 3)$ and $(2, 4)$).
n = int(input()) l = input().split() l = [int(i) for i in l] l.sort() m = (l[2*n - 1] - l[n])*(l[n - 1] - l[0]) for i in range(1,n): if m > (l[2*n - 1] - l[0])*(l[i + n - 1] - l[i]): m = (l[2*n - 1] - l[0])*(l[i + n - 1] - l[i]); print(m)
n = int(input()) l = input().split() l = [int(i) for i in l] l.sort() m = (l[2*n - 1] - l[n])*(l[n - 1] - l[0]) for i in range(1,n): if m > (l[2*n - 1] - l[0])*(l[i + n - 1] - l[i]): m = (l[2*n - 1] - l[0])*(l[i + n - 1] - l[i]); print(m)
train
APPS_structured
###Task: You have to write a function **pattern** which creates the following Pattern(See Examples) upto n(parameter) number of rows. ####Rules/Note: * If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string. * All the lines in the pattern have same length i.e equal to the number of characters in the last line. * Range of n is (-∞,100] ###Examples: pattern(5): 1 121 12321 1234321 123454321 pattern(10): 1 121 12321 1234321 123454321 12345654321 1234567654321 123456787654321 12345678987654321 1234567890987654321 pattern(15): 1 121 12321 1234321 123454321 12345654321 1234567654321 123456787654321 12345678987654321 1234567890987654321 123456789010987654321 12345678901210987654321 1234567890123210987654321 123456789012343210987654321 12345678901234543210987654321 pattern(20): 1 121 12321 1234321 123454321 12345654321 1234567654321 123456787654321 12345678987654321 1234567890987654321 123456789010987654321 12345678901210987654321 1234567890123210987654321 123456789012343210987654321 12345678901234543210987654321 1234567890123456543210987654321 123456789012345676543210987654321 12345678901234567876543210987654321 1234567890123456789876543210987654321 123456789012345678909876543210987654321 ###Amazing Fact: ```Hint: Use \n in string to jump to next line```
def pattern(n): result = [] for i in range(1, n+1): string = "" for j in range(n, i, -1): string += " " for j in range(1, i): string += str(j)[-1] for j in range(i, 0, -1): string += str(j)[-1] for j in range(n, i, -1): string += " " result.append(string) return "\n".join(result)
def pattern(n): result = [] for i in range(1, n+1): string = "" for j in range(n, i, -1): string += " " for j in range(1, i): string += str(j)[-1] for j in range(i, 0, -1): string += str(j)[-1] for j in range(n, i, -1): string += " " result.append(string) return "\n".join(result)
train
APPS_structured
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from $1$ to $n$ and then $3n$ times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements $7n+1$ times instead of $3n$ times. Because it is more random, OK?! You somehow get a test from one of these problems and now you want to know from which one. -----Input----- In the first line of input there is one integer $n$ ($10^{3} \le n \le 10^{6}$). In the second line there are $n$ distinct integers between $1$ and $n$ — the permutation of size $n$ from the test. It is guaranteed that all tests except for sample are generated this way: First we choose $n$ — the size of the permutation. Then we randomly choose a method to generate a permutation — the one of Petr or the one of Alex. Then we generate a permutation using chosen method. -----Output----- If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes). -----Example----- Input 5 2 4 5 1 3 Output Petr -----Note----- Please note that the sample is not a valid test (because of limitations for $n$) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC. Due to randomness of input hacks in this problem are forbidden.
n = int(input()) l = [int(x) - 1 for x in input().split()] parity = 0 explore = set(l) while len(explore) > 0: x = explore.pop() tmp = x found = [x] while l[tmp] != x: tmp = l[tmp] found.append(tmp) for i in found[1:]: explore.remove(i) parity ^= (len(found) - 1) % 2 if parity == n % 2: print("Petr") else: print("Um_nik")
n = int(input()) l = [int(x) - 1 for x in input().split()] parity = 0 explore = set(l) while len(explore) > 0: x = explore.pop() tmp = x found = [x] while l[tmp] != x: tmp = l[tmp] found.append(tmp) for i in found[1:]: explore.remove(i) parity ^= (len(found) - 1) % 2 if parity == n % 2: print("Petr") else: print("Um_nik")
train
APPS_structured
A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company has is the one with headID. Each employee has one direct manager given in the manager array where manager[i] is the direct manager of the i-th employee, manager[headID] = -1. Also it's guaranteed that the subordination relationships have a tree structure. The head of the company wants to inform all the employees of the company of an urgent piece of news. He will inform his direct subordinates and they will inform their subordinates and so on until all employees know about the urgent news. The i-th employee needs informTime[i] minutes to inform all of his direct subordinates (i.e After informTime[i] minutes, all his direct subordinates can start spreading the news). Return the number of minutes needed to inform all the employees about the urgent news. Example 1: Input: n = 1, headID = 0, manager = [-1], informTime = [0] Output: 0 Explanation: The head of the company is the only employee in the company. Example 2: Input: n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0] Output: 1 Explanation: The head of the company with id = 2 is the direct manager of all the employees in the company and needs 1 minute to inform them all. The tree structure of the employees in the company is shown. Example 3: Input: n = 7, headID = 6, manager = [1,2,3,4,5,6,-1], informTime = [0,6,5,4,3,2,1] Output: 21 Explanation: The head has id = 6. He will inform employee with id = 5 in 1 minute. The employee with id = 5 will inform the employee with id = 4 in 2 minutes. The employee with id = 4 will inform the employee with id = 3 in 3 minutes. The employee with id = 3 will inform the employee with id = 2 in 4 minutes. The employee with id = 2 will inform the employee with id = 1 in 5 minutes. The employee with id = 1 will inform the employee with id = 0 in 6 minutes. Needed time = 1 + 2 + 3 + 4 + 5 + 6 = 21. Example 4: Input: n = 15, headID = 0, manager = [-1,0,0,1,1,2,2,3,3,4,4,5,5,6,6], informTime = [1,1,1,1,1,1,1,0,0,0,0,0,0,0,0] Output: 3 Explanation: The first minute the head will inform employees 1 and 2. The second minute they will inform employees 3, 4, 5 and 6. The third minute they will inform the rest of employees. Example 5: Input: n = 4, headID = 2, manager = [3,3,-1,2], informTime = [0,0,162,914] Output: 1076 Constraints: 1 <= n <= 10^5 0 <= headID < n manager.length == n 0 <= manager[i] < n manager[headID] == -1 informTime.length == n 0 <= informTime[i] <= 1000 informTime[i] == 0 if employee i has no subordinates. It is guaranteed that all the employees can be informed.
class Solution: def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int: children = [[] for i in range(n)] # construct the tree # children[m] is the list of direct subordinates # of m for i, m in enumerate(manager): if m >= 0: children[m].append(i) # the time for a maganer = max(his employee's time) # + inforTime[manager] def dfs(i): return max([dfs(j) for j in children[i]] or [0]) + informTime[i] return dfs(headID)
class Solution: def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int: children = [[] for i in range(n)] # construct the tree # children[m] is the list of direct subordinates # of m for i, m in enumerate(manager): if m >= 0: children[m].append(i) # the time for a maganer = max(his employee's time) # + inforTime[manager] def dfs(i): return max([dfs(j) for j in children[i]] or [0]) + informTime[i] return dfs(headID)
train
APPS_structured
We need a function (for commercial purposes) that may perform integer partitions with some constraints. The function should select how many elements each partition should have. The function should discard some "forbidden" values in each partition. So, create ```part_const()```, that receives three arguments. ```part_const((1), (2), (3))``` ``` (1) - The integer to be partitioned (2) - The number of elements that each partition should have (3) - The "forbidden" element that cannot appear in any partition ``` ```part_const()``` should output the amount of different integer partitions with the constraints required. Let's see some cases: ```python part_const(10, 3, 2) ------> 4 /// we may have a total of 8 partitions of three elements (of course, the sum of the elements of each partition should be equal 10) : [1, 1, 8], [1, 2, 7], [1, 3, 6], [1, 4, 5], [2, 2, 6], [2, 3, 5], [2, 4, 4], [3, 3, 4] but 2 is the forbidden element, so we have to discard [1, 2, 7], [2, 2, 6], [2, 3, 5] and [2, 4, 4] So the obtained partitions of three elements without having 2 in them are: [1, 1, 8], [1, 3, 6], [1, 4, 5] and [3, 3, 4] (4 partitions)/// ``` ```part_const()``` should have a particular feature: if we introduce ```0``` as the forbidden element, we will obtain the total amount of partitions with the constrained number of elements. In fact, ```python part_const(10, 3, 0) ------> 8 # The same eight partitions that we saw above. ``` Enjoy it and happy coding!!
def part_const(n, k, num, s=0, startwith=1): if k == 1: if n - s >= startwith and n - s != num: return 1 return 0 result = 0 for i in range(startwith, n - s - k + 2): if i == num: continue result += part_const(n, k-1, num, s + i, i) return result
def part_const(n, k, num, s=0, startwith=1): if k == 1: if n - s >= startwith and n - s != num: return 1 return 0 result = 0 for i in range(startwith, n - s - k + 2): if i == num: continue result += part_const(n, k-1, num, s + i, i) return result
train
APPS_structured
Create a timebased key-value store class TimeMap, that supports two operations. 1. set(string key, string value, int timestamp) Stores the key and value, along with the given timestamp. 2. get(string key, int timestamp) Returns a value such that set(key, value, timestamp_prev) was called previously, with timestamp_prev <= timestamp. If there are multiple such values, it returns the one with the largest timestamp_prev. If there are no values, it returns the empty string (""). Example 1: Input: inputs = ["TimeMap","set","get","get","set","get","get"], inputs = [[],["foo","bar",1],["foo",1],["foo",3],["foo","bar2",4],["foo",4],["foo",5]] Output: [null,null,"bar","bar",null,"bar2","bar2"] Explanation:   TimeMap kv;   kv.set("foo", "bar", 1); // store the key "foo" and value "bar" along with timestamp = 1   kv.get("foo", 1); // output "bar"   kv.get("foo", 3); // output "bar" since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 ie "bar"   kv.set("foo", "bar2", 4);   kv.get("foo", 4); // output "bar2"   kv.get("foo", 5); //output "bar2"   Example 2: Input: inputs = ["TimeMap","set","set","get","get","get","get","get"], inputs = [[],["love","high",10],["love","low",20],["love",5],["love",10],["love",15],["love",20],["love",25]] Output: [null,null,null,"","high","high","low","low"] Note: All key/value strings are lowercase. All key/value strings have length in the range [1, 100] The timestamps for all TimeMap.set operations are strictly increasing. 1 <= timestamp <= 10^7 TimeMap.set and TimeMap.get functions will be called a total of 120000 times (combined) per test case.
class TimeMap: def __init__(self): \"\"\" Initialize your data structure here. \"\"\" self.key_value = collections.defaultdict(list) self.time_of_key = collections.defaultdict(list) def set(self, key: str, value: str, timestamp: int) -> None: self.key_value[key].append(value) self.time_of_key[key].append(timestamp) def get(self, key: str, timestamp: int) -> str: idx = bisect.bisect(self.time_of_key[key], timestamp) if idx == 0: return '' else: return self.key_value[key][idx - 1] # Your TimeMap object will be instantiated and called as such: # obj = TimeMap() # obj.set(key,value,timestamp) # param_2 = obj.get(key,timestamp)
class TimeMap: def __init__(self): \"\"\" Initialize your data structure here. \"\"\" self.key_value = collections.defaultdict(list) self.time_of_key = collections.defaultdict(list) def set(self, key: str, value: str, timestamp: int) -> None: self.key_value[key].append(value) self.time_of_key[key].append(timestamp) def get(self, key: str, timestamp: int) -> str: idx = bisect.bisect(self.time_of_key[key], timestamp) if idx == 0: return '' else: return self.key_value[key][idx - 1] # Your TimeMap object will be instantiated and called as such: # obj = TimeMap() # obj.set(key,value,timestamp) # param_2 = obj.get(key,timestamp)
train
APPS_structured
You're in ancient Greece and giving Philoctetes a hand in preparing a training exercise for Hercules! You've filled a pit with two different ferocious mythical creatures for Hercules to battle! The formidable **"Orthus"** is a 2 headed dog with 1 tail. The mighty **"Hydra"** has 5 heads and 1 tail. Before Hercules goes in, he asks you "How many of each beast am I up against!?". You know the total number of heads and the total number of tails, that's the dangerous parts, right? But you didn't consider how many of each beast. ## Task Given the number of heads and the number of tails, work out the number of each mythical beast! The data is given as two parameters. Your answer should be returned as an array: ```python VALID -> [24 , 15] INVALID -> "No solutions" ``` If there aren't any cases for the given amount of heads and tails - return "No solutions" or null (C#).
beasts=lambda h, t: (lambda m: [t-m, m] if m>=0 and m<=t and m%1==0 else "No solutions")((h-t*2)/3.0)
beasts=lambda h, t: (lambda m: [t-m, m] if m>=0 and m<=t and m%1==0 else "No solutions")((h-t*2)/3.0)
train
APPS_structured
Given an alphanumeric string made up of digits and lower case Latin characters only, find the sum of all the digit characters in the string. -----Input----- - The first line of the input contains an integer T denoting the number of test cases. Then T test cases follow. - Each test case is described with a single line containing a string S, the alphanumeric string. -----Output----- - For each test case, output a single line containing the sum of all the digit characters in that string. -----Constraints----- - 1 ≤ T ≤ 1000 - 1 ≤ |S| ≤ 1000, where |S| is the length of the string S. -----Example----- Input: 1 ab1231da Output: 7 -----Explanation----- The digits in this string are 1, 2, 3 and 1. Hence, the sum of all of them is 7.
t=eval(input()) for x in range(0,t): arr=list(input()) sum=0 for i in arr: if(i.isdigit()): sum+=int(i) print(sum)
t=eval(input()) for x in range(0,t): arr=list(input()) sum=0 for i in arr: if(i.isdigit()): sum+=int(i) print(sum)
train
APPS_structured
Complete the function so that it returns the number of seconds that have elapsed between the start and end times given. ##### Tips: - The start/end times are given as Date (JS/CoffeeScript), DateTime (C#), Time (Nim), datetime(Python) and Time (Ruby) instances. - The start time will always be before the end time.
def elapsed_seconds(start, end): start = str(start).replace('-', ' ').replace(':', ' ').split(' ') end = str(end).replace('-', ' ').replace(':', ' ').split(' ') res = [ int(end[i]) - int(start[i]) for i in range(6) ] return res[2] * 86400 + res[3] * 3600 + res[4] * 60 + res[5]
def elapsed_seconds(start, end): start = str(start).replace('-', ' ').replace(':', ' ').split(' ') end = str(end).replace('-', ' ').replace(':', ' ').split(' ') res = [ int(end[i]) - int(start[i]) for i in range(6) ] return res[2] * 86400 + res[3] * 3600 + res[4] * 60 + res[5]
train
APPS_structured
The [Chinese zodiac](https://en.wikipedia.org/wiki/Chinese_zodiac) is a repeating cycle of 12 years, with each year being represented by an animal and its reputed attributes. The lunar calendar is divided into cycles of 60 years each, and each year has a combination of an animal and an element. There are 12 animals and 5 elements; the animals change each year, and the elements change every 2 years. The current cycle was initiated in the year of 1984 which was the year of the Wood Rat. Since the current calendar is Gregorian, I will only be using years from the epoch 1924. *For simplicity I am counting the year as a whole year and not from January/February to the end of the year.* ##Task Given a year, return the element and animal that year represents ("Element Animal"). For example I'm born in 1998 so I'm an "Earth Tiger". ```animals``` (or ```$animals``` in Ruby) is a preloaded array containing the animals in order: ```['Rat', 'Ox', 'Tiger', 'Rabbit', 'Dragon', 'Snake', 'Horse', 'Goat', 'Monkey', 'Rooster', 'Dog', 'Pig']``` ```elements``` (or ```$elements``` in Ruby) is a preloaded array containing the elements in order: ```['Wood', 'Fire', 'Earth', 'Metal', 'Water']``` Tell me your zodiac sign and element in the comments. Happy coding :)
def chinese_zodiac(year): EPOCH = 1924 ANIMALS = ['Rat', 'Ox', 'Tiger', 'Rabbit', 'Dragon', 'Snake', 'Horse', 'Goat', 'Monkey', 'Rooster', 'Dog', 'Pig'] ELEMENTS = ['Wood', 'Fire', 'Earth', 'Metal', 'Water'] year -= EPOCH res = ELEMENTS[(year // 2) % len(ELEMENTS)], ANIMALS[year % len(ANIMALS)] return " ".join(res)
def chinese_zodiac(year): EPOCH = 1924 ANIMALS = ['Rat', 'Ox', 'Tiger', 'Rabbit', 'Dragon', 'Snake', 'Horse', 'Goat', 'Monkey', 'Rooster', 'Dog', 'Pig'] ELEMENTS = ['Wood', 'Fire', 'Earth', 'Metal', 'Water'] year -= EPOCH res = ELEMENTS[(year // 2) % len(ELEMENTS)], ANIMALS[year % len(ANIMALS)] return " ".join(res)
train
APPS_structured
I assume most of you are familiar with the ancient legend of the rice (but I see wikipedia suggests [wheat](https://en.wikipedia.org/wiki/Wheat_and_chessboard_problem), for some reason) problem, but a quick recap for you: a young man asks as a compensation only `1` grain of rice for the first square, `2` grains for the second, `4` for the third, `8` for the fourth and so on, always doubling the previous. Your task is pretty straightforward (but not necessarily easy): given an amount of grains, you need to return up to which square of the chessboard one should count in order to get at least as many. As usual, a few examples might be way better than thousands of words from me: ```python squares_needed(0) == 0 squares_needed(1) == 1 squares_needed(2) == 2 squares_needed(3) == 2 squares_needed(4) == 3 ``` Input is always going to be valid/reasonable: ie: a non negative number; extra cookie for *not* using a loop to compute square-by-square (at least not directly) and instead trying a smarter approach [hint: some peculiar operator]; a trick converting the number might also work: impress me!
squares_needed=lambda n: 1+squares_needed(n>>1) if n else n
squares_needed=lambda n: 1+squares_needed(n>>1) if n else n
train
APPS_structured
For years you have been working hard in Santa's factory to manufacture gifts for kids in substandard work environments with no pay. You have finally managed to escape the factory and now you seek revenge. You are planning a heist with the Grinch to steal all the gifts which are locked in a safe. Since you have worked in the factory for so many years, you know how to crack the safe. The passcode for the safe is an integer. This passcode keeps changing everyday, but you know a way to crack it. You will be given two numbers A and B . Passcode is the number of X such that 0 ≤ X < B and gcd(A,B) = gcd(A+X,B). Note : gcd(A,B) is the greatest common divisor of A & B. -----Input----- The first line contains the single integer T (1 ≤ T ≤ 50) — the number of test cases. Next T lines contain test cases per line. Each line contains two integers A & B ( 1 ≤ A < B ≤ 1010 ) -----Output----- Print T integers, one for each Test case. For each test case print the appropriate passcode for that day. -----Sample Input----- 3 4 9 5 10 42 9999999967 -----Output----- 6 1 9999999966
import math t = int(input()) def phi(n): res = n i = 2 while i*i<=n: if n%i==0: res/=i res*=(i-1) while n%i==0: n/=i i+=1 if n>1: res/=n res*=(n-1) return int(res) while t: a,m = list(map(int,input().split())) g = math.gcd(a,m) print(phi(m//g)) t-=1
import math t = int(input()) def phi(n): res = n i = 2 while i*i<=n: if n%i==0: res/=i res*=(i-1) while n%i==0: n/=i i+=1 if n>1: res/=n res*=(n-1) return int(res) while t: a,m = list(map(int,input().split())) g = math.gcd(a,m) print(phi(m//g)) t-=1
train
APPS_structured
Masha and Grisha like studying sets of positive integers. One day Grisha has written a set A containing n different integers a_{i} on a blackboard. Now he asks Masha to create a set B containing n different integers b_{j} such that all n^2 integers that can be obtained by summing up a_{i} and b_{j} for all possible pairs of i and j are different. Both Masha and Grisha don't like big numbers, so all numbers in A are from 1 to 10^6, and all numbers in B must also be in the same range. Help Masha to create the set B that satisfies Grisha's requirement. -----Input----- Input data contains multiple test cases. The first line contains an integer t — the number of test cases (1 ≤ t ≤ 100). Each test case is described in the following way: the first line of the description contains one integer n — the number of elements in A (1 ≤ n ≤ 100). The second line contains n integers a_{i} — the elements of A (1 ≤ a_{i} ≤ 10^6). -----Output----- For each test first print the answer: NO, if Masha's task is impossible to solve, there is no way to create the required set B. YES, if there is the way to create the required set. In this case the second line must contain n different positive integers b_{j} — elements of B (1 ≤ b_{j} ≤ 10^6). If there are several possible sets, output any of them. -----Example----- Input 3 3 1 10 100 1 1 2 2 4 Output YES 1 2 3 YES 1 YES 1 2
''' from random import randint visited = [-1] * (2 * 10 ** 6 + 1) t = int(input()) for i in range(t): n, A = int(input()), list(map(int, input().split())) A.sort() res = [1] * n v = 1 cnt = 0 while cnt < n: #v = randint(1, 10**6) if all(visited[a + v] != i for a in A): for a in A: visited[a + v] = i res[cnt] = v cnt += 1 v += 1 print("YES\n" + ' '.join(map(str,res))) ''' t = int(input()) def check(arr,v,dic): for i in arr: if dic[i+v] == 1: return True return False def check2(arr,v,dic): ok = False for i in arr: if dic[i+v] == 1: ok = True break return ok dic = [0]*2000005 for _ in range(t): n = int(input()) arr = list(map(int,input().split())) arr.sort() brr = [1]*n cnt = 0 i = 1 flag = True tmp = {} while cnt < n: ''' while check(arr,i,dic): i += 1 brr[cnt] = i for v in arr: #if i+v>2e6: # break dic[i+v] = 1 tmp[i+v] = 1 cnt += 1 ''' #while any(dic[a + i] != 0 for a in arr): # i += 1 while check2(arr, i, dic): i += 1 for a in arr: dic[a + i] = 1 tmp[a + i] = 1 brr[cnt] = i cnt += 1 if flag: print("YES") print(" ".join(map(str,brr))) else: print("NO") for k in list(tmp.keys()): dic[k] = 0
''' from random import randint visited = [-1] * (2 * 10 ** 6 + 1) t = int(input()) for i in range(t): n, A = int(input()), list(map(int, input().split())) A.sort() res = [1] * n v = 1 cnt = 0 while cnt < n: #v = randint(1, 10**6) if all(visited[a + v] != i for a in A): for a in A: visited[a + v] = i res[cnt] = v cnt += 1 v += 1 print("YES\n" + ' '.join(map(str,res))) ''' t = int(input()) def check(arr,v,dic): for i in arr: if dic[i+v] == 1: return True return False def check2(arr,v,dic): ok = False for i in arr: if dic[i+v] == 1: ok = True break return ok dic = [0]*2000005 for _ in range(t): n = int(input()) arr = list(map(int,input().split())) arr.sort() brr = [1]*n cnt = 0 i = 1 flag = True tmp = {} while cnt < n: ''' while check(arr,i,dic): i += 1 brr[cnt] = i for v in arr: #if i+v>2e6: # break dic[i+v] = 1 tmp[i+v] = 1 cnt += 1 ''' #while any(dic[a + i] != 0 for a in arr): # i += 1 while check2(arr, i, dic): i += 1 for a in arr: dic[a + i] = 1 tmp[a + i] = 1 brr[cnt] = i cnt += 1 if flag: print("YES") print(" ".join(map(str,brr))) else: print("NO") for k in list(tmp.keys()): dic[k] = 0
train
APPS_structured
This kata is an extension of "Combinations in a Set Using Boxes":https://www.codewars.com/kata/5b5f7f7607a266914200007c The goal for this kata is to get all the possible combinations (or distributions) (with no empty boxes) of a certain number of balls, but now, **with different amount of boxes.** In the previous kata, the number of boxes was always the same Just to figure the goal for this kata, we can see in the picture below the combinations for four balls using the diagram of Hasse: Points that are isolated represent balls that are unique in a box. k points that are bonded in an area respresent a subset that is content in a box. The unique square at the bottom of the diagram, means that there is only one possible combination for four balls in four boxes. The above next line with 6 squares, means that we have 6 possible distributions of the four balls in 3 boxes. These six distributions have something in common, all of them have one box with 2 balls. Going up one line more, we find the 7 possible distributions of the four balls in 2 boxes. As it is shown, we will have 7 distributions with: three balls in a box and only one ball in the another box, or two balls in each box. Finally, we find again at the top, an unique square, that represents, the only possible distribution, having one box, the four balls together in the only available box. So, for a set of 4 labeled balls, we have a total of 15 possible distributions (as always with no empty boxes) and with a maximum of 7 possible distributions for the case of two boxes. Prepare a code that for a given number of balls (an integer), may output an array with required data in the following order: ``` [total_amount_distributions, maximum_amount_distributions_case_k_boxes, k_boxes] ``` Just see how it would be for the example given above: ``` combs_non_empty_boxesII(4) == [15, 7, 2] # A total of 15 combinations #The case with maximum distributions is 7 using 2 boxes. ``` Features of the random tests: ``` 1 < n <= 1800 (python) 1 < n <= 1200 (ruby) ``` You may see the example tests for more cases. Enjoy it! Ruby version will be published soon.
MAX_BALL = 2+1800 DP,lst = [None], [0,1] for _ in range(MAX_BALL): DP.append([sum(lst), *max( (v,i) for i,v in enumerate(lst) )]) lst.append(0) lst = [ v*i + lst[i-1] for i,v in enumerate(lst) ] combs_non_empty_boxesII = DP.__getitem__
MAX_BALL = 2+1800 DP,lst = [None], [0,1] for _ in range(MAX_BALL): DP.append([sum(lst), *max( (v,i) for i,v in enumerate(lst) )]) lst.append(0) lst = [ v*i + lst[i-1] for i,v in enumerate(lst) ] combs_non_empty_boxesII = DP.__getitem__
train
APPS_structured
In the world of Dota2, there are two parties: the Radiant and the Dire. The Dota2 senate consists of senators coming from two parties. Now the senate wants to make a decision about a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights: Ban one senator's right: A senator can make another senator lose all his rights in this and all the following rounds. Announce the victory: If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and make the decision about the change in the game. Given a string representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party respectively. Then if there are n senators, the size of the given string will be n. The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure. Suppose every senator is smart enough and will play the best strategy for his own party, you need to predict which party will finally announce the victory and make the change in the Dota2 game. The output should be Radiant or Dire. Example 1: Input: "RD" Output: "Radiant" Explanation: The first senator comes from Radiant and he can just ban the next senator's right in the round 1. And the second senator can't exercise any rights any more since his right has been banned. And in the round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote. Example 2: Input: "RDD" Output: "Dire" Explanation: The first senator comes from Radiant and he can just ban the next senator's right in the round 1. And the second senator can't exercise any rights anymore since his right has been banned. And the third senator comes from Dire and he can ban the first senator's right in the round 1. And in the round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote. Note: The length of the given string will in the range [1, 10,000].
class Solution: def predictPartyVictory(self, senate): """ :type senate: str :rtype: str """ queue = collections.deque() people, bans = [0, 0], [0, 0] for person in senate: x = person == 'R' people[x] += 1 queue.append(x) while all(people): x = queue.popleft() if bans[x]: bans[x] -= 1 people[x] -= 1 else: bans[x^1] += 1 queue.append(x) return "Radiant" if people[1] else "Dire"
class Solution: def predictPartyVictory(self, senate): """ :type senate: str :rtype: str """ queue = collections.deque() people, bans = [0, 0], [0, 0] for person in senate: x = person == 'R' people[x] += 1 queue.append(x) while all(people): x = queue.popleft() if bans[x]: bans[x] -= 1 people[x] -= 1 else: bans[x^1] += 1 queue.append(x) return "Radiant" if people[1] else "Dire"
train
APPS_structured
John was learning mathematics and was very bored. Jane his best friend gave him a problem to solve. The description of the problem was as follows:- You are given a decimal number $N$(1<=$N$<=$10^9$) and three integers $A$, $B$, $C$. Steps to perform: 1) You have to create a $LIST$. 2) You have to initialize the $LIST$ by adding N to the $LIST$ as its first element. 3) Divide$N$ by $A$ and if the first digit of the fractional part is Non-Zero then add this digit to the $LIST$ otherwise add the first digit of the integral part(Leftmost digit). (The integer part or integral part of a decimal is the integer written to the left of the decimal separator. The part from the decimal separator i.e to the right is the fractional part. ) 4) Update $N$ by Last element of the $LIST$. N = Last element of $LIST$ 5) You have to perform the same process from step 3 on $N$ for $B$ and $C$ respectively 6) Repeat from step 3 You have to answer$Q$(1 <= $Q$<= 100 ) queries For each query you are given an integer $i$ (0 <= $i$ <= $10^9$ ). You have to print the element present at the ith position of the $LIST$. Help John solve this problem. -----Input:----- - The First Line of input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The First Line of each test case contains the integer $N$. - The second line of each test case contains three integers $A$, $B$, and $C$ separated by a space - The third line of each test case contains an integer $Q$. - Then the next $Q$ line follows. - An integer $i$ (0 <= $i$ <= 10^9 ) -----Output:----- You have to answer the $Q$ queries in the next $Q$ lines. -----Constraints----- - $1 \leq T \leq 10$ - $1 \leq N \leq 10^9$ - $2 \leq A \leq 10$ - $2 \leq B \leq 10$ - $2 \leq C \leq 10$ - $2 \leq Q \leq 100$ - $0 \leq i \leq 10^9$ -----Sample Input:----- 1 56 3 5 7 4 0 1 2 3 -----Sample Output:----- 56 6 2 2 -----EXPLANATION:----- This list is : $N$ = 56 and $A$ = 3, $B$ = 5, $C$ = 7. Initially $LIST$ = $[ 56 ]$ $N$$/$$A$ = 56/3 = 18.666666666666668 Add 6 to the $LIST$ $LIST$ = $[ 56, 6 ]$ $N$ = 6 $N$$/$$B$ = 6/5 = 1.2 Add 2 to the$LIST$ $LIST$ = $[ 56, 6, 2 ]$ N = 2 $N$$/$$C$ = 2/7 =0. 2857142857142857 Add 2 to the $LIST$. $LIST$ = $[ 56, 6, 2, 2 ]$ $N$ = 2 We have to keep repeating this process. If any of the numbers got by $N$ dividing by either $A$, $B$, $C$ have 0 after the decimal point then we have to take the first digit of the number. for example: if we got 12.005 then here we take 1 and add it to the list and then assign N = 1 Now the queries ask for the elements at index 0, 1, 2, 3 of the $LIST$ which is 56,6, 2, 2
for i in range(int(input())): n = int(input()) abc = list(map(int, input().split())) query = int(input()) q = [] for j in range(query): q.append(int(input())) z = 0 p = 0 s = 0 wlist = [n] while p < 30: x = n / abc[z] x = str(x) if x[x.index(".") + 1] == "0": wlist.append(int(x[0])) n = int(x[0]) else: wlist.append(int(x[x.index(".") + 1])) n = int(x[x.index(".") + 1]) if n == 0: break z += 1 p += 1 if z > 2: z = 0 n = 0 while True: if wlist[n:n + 3] == wlist[n + 3:n + 6]: s = 0 break n += 1 # print(n, wlist) mlist = wlist[n:n + 3] if n >= 31: n = 0 while True: if wlist[n:n + 6] == wlist[n + 6:n + 12]: s = 3 break n += 1 mlist = wlist[n:n + 6] if n >= 31: n = 0 while True: if wlist[n:n + 9] == wlist[n + 9:n + 18]: s = 6 break n += 1 mlist = wlist[n:n + 9] # print(n, wlist) for j in range(len(q)): if q[j] > n - 1: x = q[j] - n y = x % 3 if s == 3: y = x % 6 if s == 6: y = x % 9 print(mlist[y]) else: print(wlist[q[j]])
for i in range(int(input())): n = int(input()) abc = list(map(int, input().split())) query = int(input()) q = [] for j in range(query): q.append(int(input())) z = 0 p = 0 s = 0 wlist = [n] while p < 30: x = n / abc[z] x = str(x) if x[x.index(".") + 1] == "0": wlist.append(int(x[0])) n = int(x[0]) else: wlist.append(int(x[x.index(".") + 1])) n = int(x[x.index(".") + 1]) if n == 0: break z += 1 p += 1 if z > 2: z = 0 n = 0 while True: if wlist[n:n + 3] == wlist[n + 3:n + 6]: s = 0 break n += 1 # print(n, wlist) mlist = wlist[n:n + 3] if n >= 31: n = 0 while True: if wlist[n:n + 6] == wlist[n + 6:n + 12]: s = 3 break n += 1 mlist = wlist[n:n + 6] if n >= 31: n = 0 while True: if wlist[n:n + 9] == wlist[n + 9:n + 18]: s = 6 break n += 1 mlist = wlist[n:n + 9] # print(n, wlist) for j in range(len(q)): if q[j] > n - 1: x = q[j] - n y = x % 3 if s == 3: y = x % 6 if s == 6: y = x % 9 print(mlist[y]) else: print(wlist[q[j]])
train
APPS_structured
There is an undirected tree of $n$ vertices, connected by $n-1$ bidirectional edges. There is also a snake stuck inside of this tree. Its head is at vertex $a$ and its tail is at vertex $b$. The snake's body occupies all vertices on the unique simple path between $a$ and $b$. The snake wants to know if it can reverse itself  — that is, to move its head to where its tail started, and its tail to where its head started. Unfortunately, the snake's movements are restricted to the tree's structure. In an operation, the snake can move its head to an adjacent vertex not currently occupied by the snake. When it does this, the tail moves one vertex closer to the head, so that the length of the snake remains unchanged. Similarly, the snake can also move its tail to an adjacent vertex not currently occupied by the snake. When it does this, the head moves one unit closer to the tail. [Image] Let's denote a snake position by $(h,t)$, where $h$ is the index of the vertex with the snake's head, $t$ is the index of the vertex with the snake's tail. This snake can reverse itself with the movements $(4,7)\to (5,1)\to (4,2)\to (1, 3)\to (7,2)\to (8,1)\to (7,4)$. Determine if it is possible to reverse the snake with some sequence of operations. -----Input----- The first line contains a single integer $t$ ($1\le t\le 100$)  — the number of test cases. The next lines contain descriptions of test cases. The first line of each test case contains three integers $n,a,b$ ($2\le n\le 10^5,1\le a,b\le n,a\ne b$). Each of the next $n-1$ lines contains two integers $u_i,v_i$ ($1\le u_i,v_i\le n,u_i\ne v_i$), indicating an edge between vertices $u_i$ and $v_i$. It is guaranteed that the given edges form a tree. It is guaranteed that the sum of $n$ across all test cases does not exceed $10^5$. -----Output----- For each test case, output "YES" if it is possible for the snake to reverse itself, or "NO" otherwise. -----Example----- Input 4 8 4 7 1 2 2 3 1 4 4 5 4 6 1 7 7 8 4 3 2 4 3 1 2 2 3 9 3 5 1 2 2 3 3 4 1 5 5 6 6 7 1 8 8 9 16 15 12 1 2 2 3 1 4 4 5 5 6 6 7 4 8 8 9 8 10 10 11 11 12 11 13 13 14 10 15 15 16 Output YES NO NO YES -----Note----- The first test case is pictured above. In the second test case, the tree is a path. We can show that the snake cannot reverse itself. In the third test case, we can show that the snake cannot reverse itself. In the fourth test case, an example solution is: $(15,12)\to (16,11)\to (15,13)\to (10,14)\to (8,13)\to (4,11)\to (1,10)$ $\to (2,8)\to (3,4)\to (2,5)\to (1,6)\to (4,7)\to (8,6)\to (10,5)$ $\to (11,4)\to (13,8)\to (14,10)\to (13,15)\to (11,16)\to (12,15)$.
from sys import stdin import itertools input = stdin.readline def getint(): return int(input()) def getints(): return list(map(int, input().split())) def getint1(): return list([int(x) - 1 for x in input().split()]) def getstr(): return input()[:-1] def solve(): n, a, b = getint1() n += 1 adj = [[] for _ in range(n)] for _ in range(n - 1): u, v = getint1() adj[u].append(v) adj[v].append(u) # dfs 1 max_child = [[-1] * 3 for _ in range(n)] stack = [(a, -1, 1)] # (node, parent) while stack: u, p, flag = stack.pop() if p != -1 and len(adj[u]) < 2: max_child[u][0] = 1 continue if flag == 1: stack.append((u, p, 0)) for v in adj[u]: if v == p: continue stack.append((v, u, 1)) else: for v in adj[u]: if v == p: continue len_v = max_child[v][0] + 1 if len_v > max_child[u][0]: max_child[u][2] = max_child[u][1] max_child[u][1] = max_child[u][0] max_child[u][0] = len_v elif len_v > max_child[u][1]: max_child[u][2] = max_child[u][1] max_child[u][1] = len_v elif len_v > max_child[u][2]: max_child[u][2] = len_v # end of dfs 1 # dfs 2 body = [] ret = [False] * n max_parent = [-1] * n stack.clear() stack = [(a, -1, 0)] # (node, parent, max len from parent) while stack: u, p, mxp = stack.pop() if mxp >= 0: stack.append((u, p, -1)) if p != -1 and len(adj[u]) < 2: continue max_parent[u] = mxp + 1 chlen = [max_parent[u], -3] for v in adj[u]: if v == p: continue len_v = max_child[v][0] + 1 if len_v > chlen[0]: chlen[1] = chlen[0] chlen[0] = len_v elif len_v > chlen[1]: chlen[1] = len_v for v in adj[u]: if v == p: continue stack.append( (v, u, chlen[int(max_child[v][0] + 1 == chlen[0])])) else: is_body = (u == b) if not is_body: for v in adj[u]: if v != p and ret[v]: is_body = True break if is_body: body.append(u) ret[u] = is_body del ret # end of dfs2 ok = False body_len = len(body) can_turn = [False] * n for i in range(n): if 3 <= sum(1 for l in max_child[i] + [max_parent[i]] if l >= body_len): can_turn[i] = True ok = True if not ok: print("NO") return treelen = [1] * body_len # print(body) for i in range(body_len): cur = body[i] pre = -1 if i == 0 else body[i - 1] nxt = -1 if i + 1 == body_len else body[i + 1] for v in adj[cur]: if v == pre or v == nxt: continue treelen[i] = max(treelen[i], max_child[v][0] + 1) if can_turn[v]: can_turn[cur] = True continue # dfs 3 stack = [(v, cur)] while stack and not can_turn[cur]: u, p = stack.pop() for w in adj[u]: if w == p: continue if can_turn[w]: can_turn[cur] = True break stack.append((w, u)) stack.clear() # end of dfs 3 # print(i, cur, can_turn[cur]) # use two pointer to find if we can enter the turing point # print(body_len, treelen) l = 0 r = body_len - 1 lmax = treelen[r] - 1 rmin = body_len - treelen[l] ok = (can_turn[body[l]] or can_turn[body[r]]) while not ok and (l < lmax or rmin < r): if l < lmax: l += 1 rmin = min(rmin, l + (body_len - treelen[l])) if rmin < r: r -= 1 lmax = max(lmax, r - (body_len - treelen[r])) if can_turn[body[l]] or can_turn[body[r]]: ok = True ## print("YES" if ok else "NO") return # end of solve def __starting_point(): # solve() # for t in range(getint()): # print('Case #', t + 1, ': ', sep='') # solve() for _ in range(getint()): solve() __starting_point()
from sys import stdin import itertools input = stdin.readline def getint(): return int(input()) def getints(): return list(map(int, input().split())) def getint1(): return list([int(x) - 1 for x in input().split()]) def getstr(): return input()[:-1] def solve(): n, a, b = getint1() n += 1 adj = [[] for _ in range(n)] for _ in range(n - 1): u, v = getint1() adj[u].append(v) adj[v].append(u) # dfs 1 max_child = [[-1] * 3 for _ in range(n)] stack = [(a, -1, 1)] # (node, parent) while stack: u, p, flag = stack.pop() if p != -1 and len(adj[u]) < 2: max_child[u][0] = 1 continue if flag == 1: stack.append((u, p, 0)) for v in adj[u]: if v == p: continue stack.append((v, u, 1)) else: for v in adj[u]: if v == p: continue len_v = max_child[v][0] + 1 if len_v > max_child[u][0]: max_child[u][2] = max_child[u][1] max_child[u][1] = max_child[u][0] max_child[u][0] = len_v elif len_v > max_child[u][1]: max_child[u][2] = max_child[u][1] max_child[u][1] = len_v elif len_v > max_child[u][2]: max_child[u][2] = len_v # end of dfs 1 # dfs 2 body = [] ret = [False] * n max_parent = [-1] * n stack.clear() stack = [(a, -1, 0)] # (node, parent, max len from parent) while stack: u, p, mxp = stack.pop() if mxp >= 0: stack.append((u, p, -1)) if p != -1 and len(adj[u]) < 2: continue max_parent[u] = mxp + 1 chlen = [max_parent[u], -3] for v in adj[u]: if v == p: continue len_v = max_child[v][0] + 1 if len_v > chlen[0]: chlen[1] = chlen[0] chlen[0] = len_v elif len_v > chlen[1]: chlen[1] = len_v for v in adj[u]: if v == p: continue stack.append( (v, u, chlen[int(max_child[v][0] + 1 == chlen[0])])) else: is_body = (u == b) if not is_body: for v in adj[u]: if v != p and ret[v]: is_body = True break if is_body: body.append(u) ret[u] = is_body del ret # end of dfs2 ok = False body_len = len(body) can_turn = [False] * n for i in range(n): if 3 <= sum(1 for l in max_child[i] + [max_parent[i]] if l >= body_len): can_turn[i] = True ok = True if not ok: print("NO") return treelen = [1] * body_len # print(body) for i in range(body_len): cur = body[i] pre = -1 if i == 0 else body[i - 1] nxt = -1 if i + 1 == body_len else body[i + 1] for v in adj[cur]: if v == pre or v == nxt: continue treelen[i] = max(treelen[i], max_child[v][0] + 1) if can_turn[v]: can_turn[cur] = True continue # dfs 3 stack = [(v, cur)] while stack and not can_turn[cur]: u, p = stack.pop() for w in adj[u]: if w == p: continue if can_turn[w]: can_turn[cur] = True break stack.append((w, u)) stack.clear() # end of dfs 3 # print(i, cur, can_turn[cur]) # use two pointer to find if we can enter the turing point # print(body_len, treelen) l = 0 r = body_len - 1 lmax = treelen[r] - 1 rmin = body_len - treelen[l] ok = (can_turn[body[l]] or can_turn[body[r]]) while not ok and (l < lmax or rmin < r): if l < lmax: l += 1 rmin = min(rmin, l + (body_len - treelen[l])) if rmin < r: r -= 1 lmax = max(lmax, r - (body_len - treelen[r])) if can_turn[body[l]] or can_turn[body[r]]: ok = True ## print("YES" if ok else "NO") return # end of solve def __starting_point(): # solve() # for t in range(getint()): # print('Case #', t + 1, ': ', sep='') # solve() for _ in range(getint()): solve() __starting_point()
train
APPS_structured
We are given a personal information string S, which may represent either an email address or a phone number. We would like to mask this personal information according to the following rules: 1. Email address: We define a name to be a string of length ≥ 2 consisting of only lowercase letters a-z or uppercase letters A-Z. An email address starts with a name, followed by the symbol '@', followed by a name, followed by the dot '.' and followed by a name.  All email addresses are guaranteed to be valid and in the format of "[email protected]". To mask an email, all names must be converted to lowercase and all letters between the first and last letter of the first name must be replaced by 5 asterisks '*'. 2. Phone number: A phone number is a string consisting of only the digits 0-9 or the characters from the set {'+', '-', '(', ')', ' '}. You may assume a phone number contains 10 to 13 digits. The last 10 digits make up the local number, while the digits before those make up the country code. Note that the country code is optional. We want to expose only the last 4 digits and mask all other digits. The local number should be formatted and masked as "***-***-1111", where 1 represents the exposed digits. To mask a phone number with country code like "+111 111 111 1111", we write it in the form "+***-***-***-1111".  The '+' sign and the first '-' sign before the local number should only exist if there is a country code.  For example, a 12 digit phone number mask should start with "+**-". Note that extraneous characters like "(", ")", " ", as well as extra dashes or plus signs not part of the above formatting scheme should be removed. Return the correct "mask" of the information provided. Example 1: Input: "[email protected]" Output: "l*****[email protected]" Explanation: All names are converted to lowercase, and the letters between the   first and last letter of the first name is replaced by 5 asterisks.   Therefore, "leetcode" -> "l*****e". Example 2: Input: "[email protected]" Output: "a*****[email protected]" Explanation: There must be 5 asterisks between the first and last letter   of the first name "ab". Therefore, "ab" -> "a*****b". Example 3: Input: "1(234)567-890" Output: "***-***-7890" Explanation: 10 digits in the phone number, which means all digits make up the local number. Example 4: Input: "86-(10)12345678" Output: "+**-***-***-5678" Explanation: 12 digits, 2 digits for country code and 10 digits for local number. Notes: S.length <= 40. Emails have length at least 8. Phone numbers have length at least 10.
class Solution: def maskPII(self, S: str) -> str: N=len(S) if '@' in S: S=S.lower() first,rest=S.split('@') return first[0]+'*'*5+first[-1]+'@'+rest else: digits=''.join(c for c in S if c.isdigit()) a=[] if len(digits)>10: a.append('+'+'*'*(len(digits)-10)) a.append('***') a.append('***') a.append(digits[-4:]) return '-'.join(a)
class Solution: def maskPII(self, S: str) -> str: N=len(S) if '@' in S: S=S.lower() first,rest=S.split('@') return first[0]+'*'*5+first[-1]+'@'+rest else: digits=''.join(c for c in S if c.isdigit()) a=[] if len(digits)>10: a.append('+'+'*'*(len(digits)-10)) a.append('***') a.append('***') a.append(digits[-4:]) return '-'.join(a)
train
APPS_structured
Let's say you have a bunch of points, and you want to round them all up and calculate the area of the smallest polygon containing all of the points (nevermind why, you just want a challenge). What you're looking for is the area of the *convex hull* of these points. Here is an example, delimited in blue : ## Your task Implement a function that will compute the area covered by the convex hull that can be formed from an array of points, the area being rounded to two decimal places. The points are given as `(x,y)`, like in an orthonormal coordinates system. ```python points = [(0, 0), (0, 3), (4, 0)] convex_hull_area(points) == 6.00 ``` *Note* : In Python, the scipy module has a [ready made solution](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.ConvexHull.html) for this. Of course, if you use it here, you are lame. *P. S.* : If you enjoy this kata, you may also like this one, which asks you to compute a convex hull, without finding its area.
import numpy as np def slope(p1, p2): dx, dy = vectorize(p1, p2) return dy/dx if dx else float("inf") def vectorize(p1, p2): return [b-a for a,b in zip(p1, p2)] def getArea (p1, p2, p3): return np.cross(vectorize(p1, p2), vectorize(p1, p3)) / 2 def isConcave(p1, pivot, p2): return getArea(pivot, p1, p2) >= 0 def convex_hull_area(points): if len(points) < 3: return 0 Z = min(points) # Leftmost point in the graph (lowest if several ones at the same x) q = sorted( (pt for pt in points if pt != Z), key = lambda pt: (-slope(pt, Z), -np.linalg.norm(vectorize(Z, pt)))) # sorted points accordingly to the slope of the line formed by "pt" and "Z" (in reversed order) hull = [Z, q.pop()] # Construct the convex hull (Graham Scan) while q: pt = q.pop() while len(hull) > 1 and isConcave(hull[-2], hull[-1], pt): hull.pop() hull.append(pt) area = sum( getArea(Z, hull[i], hull[i+1]) for i in range(1, len(hull)-1) ) # Calculate area of the hull by adding the area of all the triangles formed by 2 consecutive points in the hull and having Z as summit return round(area, 2)
import numpy as np def slope(p1, p2): dx, dy = vectorize(p1, p2) return dy/dx if dx else float("inf") def vectorize(p1, p2): return [b-a for a,b in zip(p1, p2)] def getArea (p1, p2, p3): return np.cross(vectorize(p1, p2), vectorize(p1, p3)) / 2 def isConcave(p1, pivot, p2): return getArea(pivot, p1, p2) >= 0 def convex_hull_area(points): if len(points) < 3: return 0 Z = min(points) # Leftmost point in the graph (lowest if several ones at the same x) q = sorted( (pt for pt in points if pt != Z), key = lambda pt: (-slope(pt, Z), -np.linalg.norm(vectorize(Z, pt)))) # sorted points accordingly to the slope of the line formed by "pt" and "Z" (in reversed order) hull = [Z, q.pop()] # Construct the convex hull (Graham Scan) while q: pt = q.pop() while len(hull) > 1 and isConcave(hull[-2], hull[-1], pt): hull.pop() hull.append(pt) area = sum( getArea(Z, hull[i], hull[i+1]) for i in range(1, len(hull)-1) ) # Calculate area of the hull by adding the area of all the triangles formed by 2 consecutive points in the hull and having Z as summit return round(area, 2)
train
APPS_structured
Three numbers A, B and C are the inputs. Write a program to find second largest among them. -----Input----- The first line contains an integer T, the total number of testcases. Then T lines follow, each line contains three integers A, B and C. -----Output----- For each test case, display the second largest among A, B and C, in a new line. -----Constraints----- - 1 ≤ T ≤ 1000 - 1 ≤ A,B,C ≤ 1000000 -----Example----- Input 3 120 11 400 10213 312 10 10 3 450 Output 120 312 10
for _ in range (int(input())): a = list(map(int,input().split())) a.sort() print(a[1])
for _ in range (int(input())): a = list(map(int,input().split())) a.sort() print(a[1])
train
APPS_structured
Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water. The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [l_{i}, r_{i}], besides, r_{i} < l_{i} + 1 for 1 ≤ i ≤ n - 1. To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that l_{i} ≤ x ≤ r_{i}, l_{i} + 1 ≤ y ≤ r_{i} + 1 and y - x = a. The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands. -----Input----- The first line contains integers n (2 ≤ n ≤ 2·10^5) and m (1 ≤ m ≤ 2·10^5) — the number of islands and bridges. Next n lines each contain two integers l_{i} and r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ 10^18) — the coordinates of the island endpoints. The last line contains m integer numbers a_1, a_2, ..., a_{m} (1 ≤ a_{i} ≤ 10^18) — the lengths of the bridges that Andrewid got. -----Output----- If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b_1, b_2, ..., b_{n} - 1, which mean that between islands i and i + 1 there must be used a bridge number b_{i}. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case. -----Examples----- Input 4 4 1 4 7 8 9 10 12 14 4 5 3 8 Output Yes 2 3 1 Input 2 2 11 14 17 18 2 9 Output No Input 2 1 1 1 1000000000000000000 1000000000000000000 999999999999999999 Output Yes 1 -----Note----- In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14. In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
#!/usr/bin/env python # 556D_fug.py - Codeforces.com 556D Fug quiz # # Copyright (C) 2015 Sergey # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Input The first line contains integers n and m - the number of islands and bridges. Next n lines each contain two integers li and ri - the coordinates of the island endpoints. The last line contains m integer numbers a1..am - the lengths of the bridges that Andrewid got. Output If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes) , otherwise print in the first line "Yes" (without the quotes), and in the second line print n-1 numbers b1, bn-1, which mean that between islands i and i+1 there must be used a bridge number bi. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case """ # Standard libraries import unittest import sys import re # Additional libraries import heapq ############################################################################### # Fug Class ############################################################################### class Fug: """ Fug representation """ def __init__(self, args): """ Default constructor """ self.list = args[0] self.alist = args[1] self.gn = len(self.list) - 1 # Sorted list of bridges self.asrt = sorted((n, i) for i, n in enumerate(self.alist)) # List of gaps between islands self.gaps = [] prevli = self.list[0] for i in range(self.gn): li = self.list[i+1] min = li[0] - prevli[1] max = li[1] - prevli[0] self.gaps.append((min, max, i)) prevli = li # Sorted list of gaps between islands self.gsrt = sorted(self.gaps) self.gmin = [n[0] for n in self.gsrt] self.result = [None]*self.gn self.heap = [] def iterate(self): j = 0 for (b, i) in self.asrt: # Traverse gmin array while j < self.gn and self.gmin[j] <= b: it = self.gsrt[j] heapq.heappush(self.heap, (it[1], it[0], it[2])) j += 1 # Update result and remove the element from lists if self.heap: (mmax, mmin, mi) = self.heap[0] if mmin <= b and mmax >= b: self.result[mi] = str(i + 1) heapq.heappop(self.heap) yield def calculate(self): """ Main calcualtion function of the class """ for it in self.iterate(): pass for n in self.result: if n is None: return "No" answer = "Yes\n" answer += " ".join(self.result) return answer ############################################################################### # Executable code ############################################################################### def get_inputs(test_inputs=None): it = iter(test_inputs.split("\n")) if test_inputs else None def uinput(): """ Unit-testable input function wrapper """ if it: return next(it) else: return sys.stdin.readline() # Getting string inputs. Place all uinput() calls here num = [int(s) for s in uinput().split()] list = [[int(s) for s in uinput().split()] for i in range(num[0])] alist = [int(s) for s in uinput().split()] # Decoding inputs into a list inputs = [list, alist] return inputs def calculate(test_inputs=None): """ Base class calculate method wrapper """ return Fug(get_inputs(test_inputs)).calculate() ############################################################################### # Unit Tests ############################################################################### class unitTests(unittest.TestCase): def test_sample_tests(self): """ Quiz sample tests. Add \n to separate lines """ # Sample test 1 test = "4 4\n1 4\n7 8\n9 10\n12 14\n4 5 3 8" self.assertEqual(calculate(test), "Yes\n2 3 1") self.assertEqual( get_inputs(test), [[[1, 4], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]]) # My tests test = "5 5\n1 1\n2 7\n8 8\n10 10\n16 16\n1 1 5 6 2" self.assertEqual(calculate(test), "Yes\n1 2 5 4") # Other tests test = "2 2\n11 14\n17 18\n2 9" self.assertEqual(calculate(test), "No") # Other tests test = ( "2 1\n1 1\n1000000000000000000 1000000000000000000" + "\n999999999999999999") self.assertEqual(calculate(test), "Yes\n1") test = ("5 9\n1 2\n3 3\n5 7\n11 13\n14 20\n2 3 4 10 6 2 6 9 5") self.assertEqual(calculate(test), "Yes\n1 6 3 2") size = 10000 test = str(size) + " " + str(size) + "\n" x = size*1000 for i in range(size): x += 2 test += str(x) + " " + str(x+1) + "\n" for i in range(size): test += str(2) + " " self.assertEqual(calculate(test)[0], "Y") def test_Fug_class__basic_functions(self): """ Fug class basic functions testing """ # Constructor test d = Fug([[[1, 5], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]]) self.assertEqual(d.list[0][0], 1) self.assertEqual(d.alist[0], 4) # Sort bridges self.assertEqual(d.asrt[0], (3, 2)) # Sort Gaps self.assertEqual(d.gaps[0], (2, 7, 0)) self.assertEqual(d.gsrt[0], (1, 3, 1)) iter = d.iterate() next(iter) self.assertEqual(d.gmin, [1, 2, 2]) self.assertEqual(d.heap, [(5, 2, 2), (7, 2, 0)]) def __starting_point(): # Avoiding recursion limitaions sys.setrecursionlimit(100000) if sys.argv[-1] == "-ut": unittest.main(argv=[" "]) # Print the result string sys.stdout.write(calculate()) __starting_point()
#!/usr/bin/env python # 556D_fug.py - Codeforces.com 556D Fug quiz # # Copyright (C) 2015 Sergey # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Input The first line contains integers n and m - the number of islands and bridges. Next n lines each contain two integers li and ri - the coordinates of the island endpoints. The last line contains m integer numbers a1..am - the lengths of the bridges that Andrewid got. Output If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes) , otherwise print in the first line "Yes" (without the quotes), and in the second line print n-1 numbers b1, bn-1, which mean that between islands i and i+1 there must be used a bridge number bi. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case """ # Standard libraries import unittest import sys import re # Additional libraries import heapq ############################################################################### # Fug Class ############################################################################### class Fug: """ Fug representation """ def __init__(self, args): """ Default constructor """ self.list = args[0] self.alist = args[1] self.gn = len(self.list) - 1 # Sorted list of bridges self.asrt = sorted((n, i) for i, n in enumerate(self.alist)) # List of gaps between islands self.gaps = [] prevli = self.list[0] for i in range(self.gn): li = self.list[i+1] min = li[0] - prevli[1] max = li[1] - prevli[0] self.gaps.append((min, max, i)) prevli = li # Sorted list of gaps between islands self.gsrt = sorted(self.gaps) self.gmin = [n[0] for n in self.gsrt] self.result = [None]*self.gn self.heap = [] def iterate(self): j = 0 for (b, i) in self.asrt: # Traverse gmin array while j < self.gn and self.gmin[j] <= b: it = self.gsrt[j] heapq.heappush(self.heap, (it[1], it[0], it[2])) j += 1 # Update result and remove the element from lists if self.heap: (mmax, mmin, mi) = self.heap[0] if mmin <= b and mmax >= b: self.result[mi] = str(i + 1) heapq.heappop(self.heap) yield def calculate(self): """ Main calcualtion function of the class """ for it in self.iterate(): pass for n in self.result: if n is None: return "No" answer = "Yes\n" answer += " ".join(self.result) return answer ############################################################################### # Executable code ############################################################################### def get_inputs(test_inputs=None): it = iter(test_inputs.split("\n")) if test_inputs else None def uinput(): """ Unit-testable input function wrapper """ if it: return next(it) else: return sys.stdin.readline() # Getting string inputs. Place all uinput() calls here num = [int(s) for s in uinput().split()] list = [[int(s) for s in uinput().split()] for i in range(num[0])] alist = [int(s) for s in uinput().split()] # Decoding inputs into a list inputs = [list, alist] return inputs def calculate(test_inputs=None): """ Base class calculate method wrapper """ return Fug(get_inputs(test_inputs)).calculate() ############################################################################### # Unit Tests ############################################################################### class unitTests(unittest.TestCase): def test_sample_tests(self): """ Quiz sample tests. Add \n to separate lines """ # Sample test 1 test = "4 4\n1 4\n7 8\n9 10\n12 14\n4 5 3 8" self.assertEqual(calculate(test), "Yes\n2 3 1") self.assertEqual( get_inputs(test), [[[1, 4], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]]) # My tests test = "5 5\n1 1\n2 7\n8 8\n10 10\n16 16\n1 1 5 6 2" self.assertEqual(calculate(test), "Yes\n1 2 5 4") # Other tests test = "2 2\n11 14\n17 18\n2 9" self.assertEqual(calculate(test), "No") # Other tests test = ( "2 1\n1 1\n1000000000000000000 1000000000000000000" + "\n999999999999999999") self.assertEqual(calculate(test), "Yes\n1") test = ("5 9\n1 2\n3 3\n5 7\n11 13\n14 20\n2 3 4 10 6 2 6 9 5") self.assertEqual(calculate(test), "Yes\n1 6 3 2") size = 10000 test = str(size) + " " + str(size) + "\n" x = size*1000 for i in range(size): x += 2 test += str(x) + " " + str(x+1) + "\n" for i in range(size): test += str(2) + " " self.assertEqual(calculate(test)[0], "Y") def test_Fug_class__basic_functions(self): """ Fug class basic functions testing """ # Constructor test d = Fug([[[1, 5], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]]) self.assertEqual(d.list[0][0], 1) self.assertEqual(d.alist[0], 4) # Sort bridges self.assertEqual(d.asrt[0], (3, 2)) # Sort Gaps self.assertEqual(d.gaps[0], (2, 7, 0)) self.assertEqual(d.gsrt[0], (1, 3, 1)) iter = d.iterate() next(iter) self.assertEqual(d.gmin, [1, 2, 2]) self.assertEqual(d.heap, [(5, 2, 2), (7, 2, 0)]) def __starting_point(): # Avoiding recursion limitaions sys.setrecursionlimit(100000) if sys.argv[-1] == "-ut": unittest.main(argv=[" "]) # Print the result string sys.stdout.write(calculate()) __starting_point()
train
APPS_structured
`This kata is the first of the ADFGX Ciphers, the harder version can be found `here. The ADFGX Cipher is a pretty well-known Cryptographic tool, and is essentially a modified Polybius Square. Rather than having numbers as coordinates on the table, it has the letters: `A, D, F, G, X` Also, because this is the first step, and to help simplify things, you won't have to worry about a key, or the corresponding columnar transposition. In this kata ;) All you have to do is encrypt and decrypt a string into `ADFGX` format. `adfgx_encrypt() and adfgx_decrypt()` will be passed a string, `plaintext` and `ciphertext` respectively, and an adfgx`square`, for which will guide the operations. Now for some examples to clear confusion: ```python adfgx_encrypt("helloworld", "bchigklnmoqprstuvwxyzadef") A D F G X A b c h i g D k l n m o F q p r s t -> square (PLEASE NOTE, j SHOULD BE TREATED AS i) G u v w x y X z a d e f "helloworld" -> plaintext EVALUATES TO: F -> "AF" A h -------------- G -> "XG" X e AND SO FORTH... #Results in: adfgx_encrypt("helloworld", "bchigklnmoqprstuvwxyzadef") == "AFXGDDDDDXGFDXFFDDXF" ``` Now decryption: ```python adfgx_decrypt("FGXGADGDXGFXAXXGFGFGAADGXG", "aczlmuqngoipvstkrwfxhdbey) A D F G X A a c z l m D u q n g o F i p v s t -> square (PLEASE NOTE, j SHOULD BE TREATED AS i) G k r w f x X h d b e y "FGXGADGDXGFXAXXGFGFGAADGXG" -> ciphertext "FG" == "s" "XG" == "e" AND SO ON: adfgx_decrypt("FGXGADGDXGFXAXXGFGFGAADGXG", "aczlmuqngoipvstkrwfxhdbey) == "secretmessage" ``` PLEASE NOTE: ALL INPUT WILL BE VALID, NO NEED TO ERROR CHECK :D What are you waiting for?! Go create `adfgx_encrypt() and adfgx_decrypt()`! Good Luck!
from itertools import product import re KEY = [ a+b for a, b in product("ADFGX", repeat=2) ] def adfgx_encrypt(plaintext, square): d = dict(zip(square, KEY)) oddity = d['i'] if 'i' in d else d['j'] return ''.join(d.get(c, oddity) for c in plaintext) def adfgx_decrypt(ciphertext, square): d = dict(zip(KEY, square)) IJkey = [ k for k, v in d.items() if v in 'ij'].pop() return ''.join( d.get(c, d[IJkey]) for c in re.findall(r'.{2}', ciphertext))
from itertools import product import re KEY = [ a+b for a, b in product("ADFGX", repeat=2) ] def adfgx_encrypt(plaintext, square): d = dict(zip(square, KEY)) oddity = d['i'] if 'i' in d else d['j'] return ''.join(d.get(c, oddity) for c in plaintext) def adfgx_decrypt(ciphertext, square): d = dict(zip(KEY, square)) IJkey = [ k for k, v in d.items() if v in 'ij'].pop() return ''.join( d.get(c, d[IJkey]) for c in re.findall(r'.{2}', ciphertext))
train
APPS_structured
Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible. Note: The length of num is less than 10002 and will be ≥ k. The given num does not contain any leading zero. Example 1: Input: num = "1432219", k = 3 Output: "1219" Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. Example 2: Input: num = "10200", k = 1 Output: "200" Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes. Example 3: Input: num = "10", k = 2 Output: "0" Explanation: Remove all the digits from the number and it is left with nothing which is 0.
class Solution(object): def removeKdigits(self, num, k): """ :type num: str :type k: int :rtype: str """ if k == len(num): return "0" stack = [] cnt = 0 for i, ch in enumerate(num): if cnt == k: for j in range(i, len(num)): stack.append(num[j]) break if not stack or ch >= stack[-1]: stack.append(ch) else: while stack and ch < stack[-1] and cnt < k: stack.pop() cnt += 1 stack.append(ch) while cnt < k: stack.pop() cnt += 1 i = 0 while i < len(stack) and stack[i] == '0': i += 1 if i == len(stack): return "0" return ''.join(stack[i:])
class Solution(object): def removeKdigits(self, num, k): """ :type num: str :type k: int :rtype: str """ if k == len(num): return "0" stack = [] cnt = 0 for i, ch in enumerate(num): if cnt == k: for j in range(i, len(num)): stack.append(num[j]) break if not stack or ch >= stack[-1]: stack.append(ch) else: while stack and ch < stack[-1] and cnt < k: stack.pop() cnt += 1 stack.append(ch) while cnt < k: stack.pop() cnt += 1 i = 0 while i < len(stack) and stack[i] == '0': i += 1 if i == len(stack): return "0" return ''.join(stack[i:])
train
APPS_structured
=====Function Descriptions===== any() This expression returns True if any element of the iterable is true. If the iterable is empty, it will return False. Code >>> any([1>0,1==0,1<0]) True >>> any([1<0,2<1,3<2]) False all() This expression returns True if all of the elements of the iterable are true. If the iterable is empty, it will return True. Code >>> all(['a'<'b','b'<'c']) True >>> all(['a'<'b','c'<'b']) False =====Problem Statement===== You are given a space separated list of integers. If all the integers are positive, then you need to check if any integer is a palindromic integer. =====Input Format===== The first line contains an integer N. N is the total number of integers in the list. The second line contains the space separated list of N integers. =====Constraints===== 0<N<100 =====Output Format===== Print True if all the conditions of the problem statement are satisfied. Otherwise, print False.
def __starting_point(): num_cnt = int(input().strip()) arr = list(input().strip().split()) print(all([all([int(x) > 0 for x in arr]), any([x == x[::-1] for x in arr])])) __starting_point()
def __starting_point(): num_cnt = int(input().strip()) arr = list(input().strip().split()) print(all([all([int(x) > 0 for x in arr]), any([x == x[::-1] for x in arr])])) __starting_point()
train
APPS_structured
Return a new array consisting of elements which are multiple of their own index in input array (length > 1). Some cases: ``` [22, -6, 32, 82, 9, 25] => [-6, 32, 25] [68, -1, 1, -7, 10, 10] => [-1, 10] [-56,-85,72,-26,-14,76,-27,72,35,-21,-67,87,0,21,59,27,-92,68] => [-85, 72, 0, 68] ```
def multiple_of_index(arr): return [y for x,y in enumerate(arr[1:], start=1) if y % x == 0]
def multiple_of_index(arr): return [y for x,y in enumerate(arr[1:], start=1) if y % x == 0]
train
APPS_structured
# Task Your task is to find the smallest number which is evenly divided by all numbers between `m` and `n` (both inclusive). # Example For `m = 1, n = 2`, the output should be `2`. For `m = 2, n = 3`, the output should be `6`. For `m = 3, n = 2`, the output should be `6` too. For `m = 1, n = 10`, the output should be `2520`. # Input/Output - `[input]` integer `m` `1 ≤ m ≤ 25` - `[input]` integer `n` `1 ≤ n ≤ 25` - `[output]` an integer
import functools def gcd_rec(a, b): if b: return gcd_rec(b, a % b) else: return a def mn_lcm(m,n): lst = list(range(min(n,m),max(n,m)+1)) return functools.reduce(lambda a,b : a*b/gcd_rec(a,b),lst )
import functools def gcd_rec(a, b): if b: return gcd_rec(b, a % b) else: return a def mn_lcm(m,n): lst = list(range(min(n,m),max(n,m)+1)) return functools.reduce(lambda a,b : a*b/gcd_rec(a,b),lst )
train
APPS_structured
You are given three sequences: $a_1, a_2, \ldots, a_n$; $b_1, b_2, \ldots, b_n$; $c_1, c_2, \ldots, c_n$. For each $i$, $a_i \neq b_i$, $a_i \neq c_i$, $b_i \neq c_i$. Find a sequence $p_1, p_2, \ldots, p_n$, that satisfy the following conditions: $p_i \in \{a_i, b_i, c_i\}$ $p_i \neq p_{(i \mod n) + 1}$. In other words, for each element, you need to choose one of the three possible values, such that no two adjacent elements (where we consider elements $i,i+1$ adjacent for $i<n$ and also elements $1$ and $n$) will have equal value. It can be proved that in the given constraints solution always exists. You don't need to minimize/maximize anything, you need to find any proper sequence. -----Input----- The first line of input contains one integer $t$ ($1 \leq t \leq 100$): the number of test cases. The first line of each test case contains one integer $n$ ($3 \leq n \leq 100$): the number of elements in the given sequences. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 100$). The third line contains $n$ integers $b_1, b_2, \ldots, b_n$ ($1 \leq b_i \leq 100$). The fourth line contains $n$ integers $c_1, c_2, \ldots, c_n$ ($1 \leq c_i \leq 100$). It is guaranteed that $a_i \neq b_i$, $a_i \neq c_i$, $b_i \neq c_i$ for all $i$. -----Output----- For each test case, print $n$ integers: $p_1, p_2, \ldots, p_n$ ($p_i \in \{a_i, b_i, c_i\}$, $p_i \neq p_{i \mod n + 1}$). If there are several solutions, you can print any. -----Example----- Input 5 3 1 1 1 2 2 2 3 3 3 4 1 2 1 2 2 1 2 1 3 4 3 4 7 1 3 3 1 1 1 1 2 4 4 3 2 2 4 4 2 2 2 4 4 2 3 1 2 1 2 3 3 3 1 2 10 1 1 1 2 2 2 3 3 3 1 2 2 2 3 3 3 1 1 1 2 3 3 3 1 1 1 2 2 2 3 Output 1 2 3 1 2 1 2 1 3 4 3 2 4 2 1 3 2 1 2 3 1 2 3 1 2 3 2 -----Note----- In the first test case $p = [1, 2, 3]$. It is a correct answer, because: $p_1 = 1 = a_1$, $p_2 = 2 = b_2$, $p_3 = 3 = c_3$ $p_1 \neq p_2 $, $p_2 \neq p_3 $, $p_3 \neq p_1$ All possible correct answers to this test case are: $[1, 2, 3]$, $[1, 3, 2]$, $[2, 1, 3]$, $[2, 3, 1]$, $[3, 1, 2]$, $[3, 2, 1]$. In the second test case $p = [1, 2, 1, 2]$. In this sequence $p_1 = a_1$, $p_2 = a_2$, $p_3 = a_3$, $p_4 = a_4$. Also we can see, that no two adjacent elements of the sequence are equal. In the third test case $p = [1, 3, 4, 3, 2, 4, 2]$. In this sequence $p_1 = a_1$, $p_2 = a_2$, $p_3 = b_3$, $p_4 = b_4$, $p_5 = b_5$, $p_6 = c_6$, $p_7 = c_7$. Also we can see, that no two adjacent elements of the sequence are equal.
import sys import random from fractions import Fraction from math import * def input(): return sys.stdin.readline().strip() def iinput(): return int(input()) def finput(): return float(input()) def tinput(): return input().split() def linput(): return list(input()) def rinput(): return list(map(int, tinput())) def fiinput(): return list(map(float, tinput())) def rlinput(): return list(map(int, input().split())) def trinput(): return tuple(rinput()) def srlinput(): return sorted(list(map(int, input().split()))) def NOYES(fl): if fl: print("NO") else: print("YES") def YESNO(fl): if fl: print("YES") else: print("NO") def main(): n = iinput() #k = iinput() #m = iinput() #n = int(sys.stdin.readline().strip()) #n, k = rinput() #n, m = rinput() #m, k = rinput() #n, k, m = rinput() #n, m, k = rinput() #k, n, m = rinput() #k, m, n = rinput() #m, k, n = rinput() #m, n, k = rinput() q = [rlinput(), rlinput(), rlinput()] #q = linput() ans = q[0].copy() for i in range(1, n): if ans[i] == ans[i - 1]: ans[i] = q[1][i] if i == n - 1: o = 0 while q[o][i] == ans[n - 2] or q[o][i] == ans[0]: o += 1 ans[i] = q[o][i] print(*ans) for i in range(iinput()): main()
import sys import random from fractions import Fraction from math import * def input(): return sys.stdin.readline().strip() def iinput(): return int(input()) def finput(): return float(input()) def tinput(): return input().split() def linput(): return list(input()) def rinput(): return list(map(int, tinput())) def fiinput(): return list(map(float, tinput())) def rlinput(): return list(map(int, input().split())) def trinput(): return tuple(rinput()) def srlinput(): return sorted(list(map(int, input().split()))) def NOYES(fl): if fl: print("NO") else: print("YES") def YESNO(fl): if fl: print("YES") else: print("NO") def main(): n = iinput() #k = iinput() #m = iinput() #n = int(sys.stdin.readline().strip()) #n, k = rinput() #n, m = rinput() #m, k = rinput() #n, k, m = rinput() #n, m, k = rinput() #k, n, m = rinput() #k, m, n = rinput() #m, k, n = rinput() #m, n, k = rinput() q = [rlinput(), rlinput(), rlinput()] #q = linput() ans = q[0].copy() for i in range(1, n): if ans[i] == ans[i - 1]: ans[i] = q[1][i] if i == n - 1: o = 0 while q[o][i] == ans[n - 2] or q[o][i] == ans[0]: o += 1 ans[i] = q[o][i] print(*ans) for i in range(iinput()): main()
train
APPS_structured
Lucy loves to travel. Luckily she is a renowned computer scientist and gets to travel to international conferences using her department's budget. Each year, Society for Exciting Computer Science Research (SECSR) organizes several conferences around the world. Lucy always picks one conference from that list that is hosted in a city she hasn't been to before, and if that leaves her with more than one option, she picks the conference that she thinks would be most relevant for her field of research. Write a function `conferencePicker` that takes in two arguments: - `citiesVisited`, a list of cities that Lucy has visited before, given as an array of strings. - `citiesOffered`, a list of cities that will host SECSR conferences this year, given as an array of strings. `citiesOffered` will already be ordered in terms of the relevance of the conferences for Lucy's research (from the most to the least relevant). The function should return the city that Lucy should visit, as a string. Also note: - You should allow for the possibility that Lucy hasn't visited any city before. - SECSR organizes at least two conferences each year. - If all of the offered conferences are hosted in cities that Lucy has visited before, the function should return `'No worthwhile conferences this year!'` (`Nothing` in Haskell) Example:
def conference_picker(cities_visited, cities_offered): for i in cities_offered: if i not in cities_visited: return i return "No worthwhile conferences this year!"
def conference_picker(cities_visited, cities_offered): for i in cities_offered: if i not in cities_visited: return i return "No worthwhile conferences this year!"
train
APPS_structured
You are given a weighted undirected graph consisting of n$n$ nodes and m$m$ edges. The nodes are numbered from 1$1$ to n$n$. The graph does not contain any multiple edges or self loops. A walk W$W$ on the graph is a sequence of vertices (with repetitions of vertices and edges allowed) such that every adjacent pair of vertices in the sequence is an edge of the graph. We define the cost of a walk W$W$, Cost(W)$Cost(W)$, as the maximum over the weights of the edges along the walk. You will be given q$q$ queries. In each query, you will be given an integer X$X$. You have to count the number of different walks W$W$ of length 4$4$ such that Cost(W)$Cost(W)$ = X$X$. Two walks are considered different if they do not represent the same edge sequence. -----Input:----- - First line contains 2 integers : the number of nodes n$n$ and number of edges m$m$. - Next m$m$ lines each describe u$u$, v$v$ and w$w$, describing an edge between u$u$ and v$v$ with weight w$w$. - Next line contains q$q$, the number of queries. - Next q$q$ lines each describe an integer X$X$ - the cost of the walk in the query. -----Output:----- For each query, output in a single line the number of different possible walks. -----Constraints----- - 1≤n≤100$1 \leq n \leq 100$ - 1≤m≤n(n−1)2$1 \leq m \leq \frac{n (n-1)}{2}$ - 1≤u,v≤n$1 \leq u, v \leq n$ - 1≤w≤100$1 \leq w \leq 100$ - 1≤q≤100$1 \leq q \leq 100$ - 1≤X≤100$1 \leq X \leq 100$ -----Sample Input:----- 3 3 1 2 1 2 3 2 3 1 3 3 1 2 3 -----Sample Output:----- 2 10 36 -----EXPLANATION:----- For X=2$X = 2$, all possible 10$10$ walks are listed below : - 1 -> 2 -> 1 -> 2 -> 3 - 1 -> 2 -> 3 -> 2 -> 1 - 1 -> 2 -> 3 -> 2 -> 3 - 2 -> 1 -> 2 -> 3 -> 2 - 2 -> 3 -> 2 -> 1 -> 2 - 2 -> 3 -> 2 -> 3 -> 2 - 3 -> 2 -> 1 -> 2 -> 1 - 3 -> 2 -> 1 -> 2 -> 3 - 3 -> 2 -> 3 -> 2 -> 1 - 3 -> 2 -> 3 -> 2 -> 3
# cook your dish here # cook your dish here from collections import defaultdict class sol(): def __init__(self,n,edges): self.n = n self.edges = edges self.graph = self.create_graph() self.precompute() def create_graph(self): graph = defaultdict(list) for e in self.edges: u = e[0] v = e[1] w = e[2] graph[u].append([v,w]) graph[v].append([u,w]) return graph def precompute(self): self.maxiedges = [0]*6 self.B = [[0 for i in range(101)] for i in range(101)] def func(u,v,l): if l==2: self.B[u][self.maxiedges[l]] += 1 else: for j in self.graph[v]: self.maxiedges[l+1] = max(self.maxiedges[l],j[1]) func(u,j[0],l+1) for i in range(1,self.n+1): func(i,i,0) def paths(self,X): freq = 0 for u in range(1,self.n+1): for x in range(X+1): freq += 2*self.B[u][X]*self.B[u][x] freq -= self.B[u][X]*self.B[u][X] return freq n, m = map(int, input().split()) edges = [] while m: uvw = list(map(int, input().split())) edges.append(uvw) m -= 1 q = int(input()) Graph = sol(n,edges) while q: query = int(input()) print(Graph.paths(query)) q -= 1
# cook your dish here # cook your dish here from collections import defaultdict class sol(): def __init__(self,n,edges): self.n = n self.edges = edges self.graph = self.create_graph() self.precompute() def create_graph(self): graph = defaultdict(list) for e in self.edges: u = e[0] v = e[1] w = e[2] graph[u].append([v,w]) graph[v].append([u,w]) return graph def precompute(self): self.maxiedges = [0]*6 self.B = [[0 for i in range(101)] for i in range(101)] def func(u,v,l): if l==2: self.B[u][self.maxiedges[l]] += 1 else: for j in self.graph[v]: self.maxiedges[l+1] = max(self.maxiedges[l],j[1]) func(u,j[0],l+1) for i in range(1,self.n+1): func(i,i,0) def paths(self,X): freq = 0 for u in range(1,self.n+1): for x in range(X+1): freq += 2*self.B[u][X]*self.B[u][x] freq -= self.B[u][X]*self.B[u][X] return freq n, m = map(int, input().split()) edges = [] while m: uvw = list(map(int, input().split())) edges.append(uvw) m -= 1 q = int(input()) Graph = sol(n,edges) while q: query = int(input()) print(Graph.paths(query)) q -= 1
train
APPS_structured
=====Problem Statement===== Kevin and Stuart want to play the 'The Minion Game'. Game Rules Both players are given the same string, S. Both players have to make substrings using the letters of the string S. Stuart has to make words starting with consonants. Kevin has to make words starting with vowels. The game ends when both players have made all possible substrings. Scoring A player gets +1 point for each occurrence of the substring in the string S. =====Example===== String S = BANANA Kevin's vowel beginning word = ANA Here, ANA occurs twice in BANANA. Hence, Kevin will get 2 Points. Your task is to determine the winner of the game and their score. =====Input Format===== A single line of input containing the string S. Note: The string S will contain only uppercase letters: [A-Z]. =====Constraints===== 0 < len(S) < 10^6 =====Output Format===== Print one line: the name of the winner and their score separated by a space. If the game is a draw, print Draw.
def minion_game(string): n=len(string) player1,player2=0,0 for i in range(0,n): if(string[i] in 'AEIOU'): player1+=n-i else: player2+=n-i if(player1>player2): return 'Kevin '+ str(player1) elif(player1==player2): return 'Draw' else: return 'Stuart '+str(player2)
def minion_game(string): n=len(string) player1,player2=0,0 for i in range(0,n): if(string[i] in 'AEIOU'): player1+=n-i else: player2+=n-i if(player1>player2): return 'Kevin '+ str(player1) elif(player1==player2): return 'Draw' else: return 'Stuart '+str(player2)
train
APPS_structured
It's the academic year's end, fateful moment of your school report. The averages must be calculated. All the students come to you and entreat you to calculate their average for them. Easy ! You just need to write a script. Return the average of the given array rounded **down** to its nearest integer. The array will never be empty.
def get_average(marks): print((sum(marks)/len(marks))) return int((sum(marks)) / len(marks))
def get_average(marks): print((sum(marks)/len(marks))) return int((sum(marks)) / len(marks))
train
APPS_structured
In number theory, Euler's totient is an arithmetic function, introduced in 1763 by Euler, that counts the positive integers less than or equal to `n` that are relatively prime to `n`. Thus, if `n` is a positive integer, then `φ(n)`, notation introduced by Gauss in 1801, is the number of positive integers `k ≤ n` for which `gcd(n, k) = 1`. The totient function is important in number theory, mainly because it gives the order of the multiplicative group of integers modulo `n`. The totient function also plays a key role in the definition of the RSA encryption system. For example `let n = 9`. Then `gcd(9, 3) = gcd(9, 6) = 3` and `gcd(9, 9) = 9`. The other six numbers in the range `1 ≤ k ≤ 9` i.e. `1, 2, 4, 5, 7, 8` are relatively prime to `9`. Therefore, `φ(9) = 6`. As another example, `φ(1) = 1` since `gcd(1, 1) = 1`. There are generally two approaches to this function: * Iteratively counting the numbers `k ≤ n` such that `gcd(n,k) = 1`. * Using the Euler product formula. This is an explicit formula for calculating `φ(n)` depending on the prime divisor of `n`: `φ(n) = n * Product (1 - 1/p)` where the product is taken over the primes `p ≤ n` that divide `n`. For example: `φ(36) = 36 * (1 - 1/2) * (1 - 1/3) = 36 * 1/2 * 2/3 = 12`. This second method seems more complex and not likely to be faster, but in practice we will often look for `φ(n)` with `n` prime. It correctly gives `φ(n) = n - 1` if `n` is prime. You have to code the Euler totient function, that takes an integer `1 ≤ n` as input and returns `φ(n)`. ```if:javascript You do have to check if `n` is a number, is an integer and that `1 ≤ n`; if that is not the case, the function should return `0`. ``` ```if:python You do have to check if `n` is a number, is an integer and that `1 ≤ n`; if that is not the case, the function should return `0`. ``` ```if:racket `n` is always a positive integer. ``` Input range: `1 ≤ n ≤ 1e10`
def totient(n): if not isinstance(n,int) or n<1: return 0 phi = n >= 1 and n for p in range(2, int(n ** .5) + 1): if not n % p: phi -= phi // p while not n % p: n //= p if n > 1: phi -= phi // n return phi
def totient(n): if not isinstance(n,int) or n<1: return 0 phi = n >= 1 and n for p in range(2, int(n ** .5) + 1): if not n % p: phi -= phi // p while not n % p: n //= p if n > 1: phi -= phi // n return phi
train
APPS_structured
In this kata, your task is to create a function that takes a single list as an argument and returns a flattened list. The input list will have a maximum of one level of nesting (list(s) inside of a list). ```python # no nesting [1, 2, 3] # one level of nesting [1, [2, 3]] ``` --- # Examples ```python >>> flatten_me(['!', '?']) ['!', '?'] >>> flatten_me([1, [2, 3], 4]) [1, 2, 3, 4] >>> flatten_me([['a', 'b'], 'c', ['d']]) ['a', 'b', 'c', 'd'] >>> flatten_me([[True, False], ['!'], ['?'], [71, '@']]) [True, False, '!', '?', 71, '@'] ``` Good luck!
def flatten_me(lst): res = [] for i in lst: if type(i) is list: res += i else: res.append(i) return res
def flatten_me(lst): res = [] for i in lst: if type(i) is list: res += i else: res.append(i) return res
train
APPS_structured
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK. Note: If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"]. All airports are represented by three capital letters (IATA code). You may assume all tickets form at least one valid itinerary. Example 1: Input: tickets = [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]] Output: ["JFK", "MUC", "LHR", "SFO", "SJC"] Example 2: Input: tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] Output: ["JFK","ATL","JFK","SFO","ATL","SFO"] Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"]. But it is larger in lexical order. Credits: Special thanks to @dietpepsi for adding this problem and creating all test cases.
class Solution: def findItinerary(self, tickets): """ :type tickets: List[List[str]] :rtype: List[str] """ self.hasmap = {} for ticket in tickets: self.hasmap.setdefault(ticket[0], []).append(ticket[1]) self.route = ['JFK'] return self.dfs('JFK', tickets) def dfs(self, start_airport, tickets): if len(self.route) == len(tickets) + 1: return self.route # sort destination by legixal order # See one case that there is destination but not in the hashmap dictionary dests =self.hasmap.get(start_airport) if dests is not None: for dest in sorted(dests): self.hasmap[start_airport].remove(dest) self.route.append(dest) work = self.dfs(dest, tickets) if work: return self.route self.route.pop() # add it back self.hasmap[start_airport].append(dest)
class Solution: def findItinerary(self, tickets): """ :type tickets: List[List[str]] :rtype: List[str] """ self.hasmap = {} for ticket in tickets: self.hasmap.setdefault(ticket[0], []).append(ticket[1]) self.route = ['JFK'] return self.dfs('JFK', tickets) def dfs(self, start_airport, tickets): if len(self.route) == len(tickets) + 1: return self.route # sort destination by legixal order # See one case that there is destination but not in the hashmap dictionary dests =self.hasmap.get(start_airport) if dests is not None: for dest in sorted(dests): self.hasmap[start_airport].remove(dest) self.route.append(dest) work = self.dfs(dest, tickets) if work: return self.route self.route.pop() # add it back self.hasmap[start_airport].append(dest)
train
APPS_structured
Lumpy is a bus driver. Today, the conductor is absent so Lumpy has to do the conductor's job as well. There are N creatures in the bus. Sometimes the creatures don't carry change and can't pay the exact amount of the fare. Each creature in the bus today has paid an amount greater than his/her fare. You are given information about the extra amount paid by each creature, by an array A of size N, where Ai denotes the extra amount paid by the i-th creature, in rupees. After the end of the trip, Lumpy noticed that he had P one rupee coins and Q two rupee coins. He wants to pay back the creatures using this money. Being a kind hearted moose, Lumpy wants to pay back as many creatures as he can. Note that Lumpy will not pay back the i-th creature if he can't pay the exact amount that the i-th creature requires with the coins that he possesses. Lumpy is busy driving the bus and doesn't want to calculate the maximum number of creatures he can satisfy - He will surely cause an accident if he tries to do so. Can you help him out with this task? -----Input----- - The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. - For each test case, first line consists of three space separated integers N, P and Q. - Second line consists of N space separated integers A containing N space integers, where i-th integer denotes Ai. -----Output----- - For each test case, output a single line containing an integer corresponding to maximum number of creatures that Lumpy can pay back. -----Constraints----- - 1 ≤ T ≤ 106 - 1 ≤ N ≤ 105 - 1 ≤ Ai ≤ 109 - 0 ≤ P, Q ≤ 1014 - Sum of N over all the cases does not exceed 106 -----Subtasks----- - Subtask #1 (15 points): P = 0 - Subtask #2 (15 points): Q = 0 - Subtask #3 (70 points): Original constraints -----Example----- Input:3 3 3 0 1 2 2 3 2 1 1 2 1 4 5 4 2 3 4 5 Output:2 3 3 -----Explanation----- Example 1. Lumpy has just 3 one rupee coins. He can pay creatures numbered {1, 2} or creatures numbered {1, 3} with these coins. Thus, answer is 2. Example 2. Lumpy has 2 one rupee coins and 1 two rupee coin. In the optimal solution, Lumpy can give the two rupee coin to creature 2 and the one rupee coins to creatures 1 and 3. Thus, answer is 3.
for _ in range(int(input())): n,p,q=map(int,input().split()) l=list(map(int,input().split())) l.sort() ans=0 for i in range(n): x=l[i]//2 if(q>0): if(q>=x and q>0): q-=x l[i]-=x*2 else: l[i]-=q*2 q=0 x=0 p-=l[i] if(p<0 and q<=0): break ans+=1 print(ans)
for _ in range(int(input())): n,p,q=map(int,input().split()) l=list(map(int,input().split())) l.sort() ans=0 for i in range(n): x=l[i]//2 if(q>0): if(q>=x and q>0): q-=x l[i]-=x*2 else: l[i]-=q*2 q=0 x=0 p-=l[i] if(p<0 and q<=0): break ans+=1 print(ans)
train
APPS_structured
You will have a list of rationals in the form ``` lst = [ [numer_1, denom_1] , ... , [numer_n, denom_n] ] ``` or ``` lst = [ (numer_1, denom_1) , ... , (numer_n, denom_n) ] ``` where all numbers are positive integers. You have to produce their sum `N / D` in an irreducible form: this means that `N` and `D` have only `1` as a common divisor. Return the result in the form: - `[N, D]` in Ruby, Crystal, Python, Clojure, JS, CS, PHP, Julia - `Just "N D"` in Haskell, PureScript - `"[N, D]"` in Java, CSharp, TS, Scala, PowerShell, Kotlin - `"N/D"` in Go, Nim - `{N, D}` in C++, Elixir - `{N, D}` in C - `Some((N, D))` in Rust - `Some "N D"` in F#, Ocaml - `c(N, D)` in R - `(N, D)` in Swift - `'(N D)` in Racket If the result is an integer (`D` evenly divides `N`) return: - an integer in Ruby, Crystal, Elixir, Clojure, Python, JS, CS, PHP, R, Julia - `Just "n"` (Haskell, PureScript) - `"n"` Java, CSharp, TS, Scala, PowerShell, Go, Nim, Kotlin - `{n, 1}` in C++ - `{n, 1}` in C - `Some((n, 1))` in Rust - `Some "n"` in F#, Ocaml, - `(n, 1)` in Swift - `n` in Racket If the input list is empty, return - `nil/None/null/Nothing` - `{0, 1}` in C++ - `{0, 1}` in C - `"0"` in Scala, PowerShell, Go, Nim - `O` in Racket - `""` in Kotlin ### Example: ``` [ [1, 2], [1, 3], [1, 4] ] --> [13, 12] 1/2 + 1/3 + 1/4 = 13/12 ``` ### Note See sample tests for more examples and the form of results.
from fractions import Fraction def sum_fracts(lst): if lst: ret = sum(map(lambda l: Fraction(*l), lst)) return [ret.numerator, ret.denominator] if ret.denominator != 1 else ret.numerator
from fractions import Fraction def sum_fracts(lst): if lst: ret = sum(map(lambda l: Fraction(*l), lst)) return [ret.numerator, ret.denominator] if ret.denominator != 1 else ret.numerator
train
APPS_structured
Consider the number triangle below, in which each number is equal to the number above plus the number to the left. If there is no number above, assume it's a `0`. The triangle has `5` rows and the sum of the last row is `sum([1,4,9,14,14]) = 42`. You will be given an integer `n` and your task will be to return the sum of the last row of a triangle of `n` rows. In the example above: More examples in test cases. Good luck! ```if:javascript ### Note This kata uses native arbitrary precision integer numbers ( `BigInt`, `1n` ). Unfortunately, the testing framework and even native `JSON` do not fully support them yet. `console.log(1n)` and `(1n).toString()` work and can be used for debugging. We apologise for the inconvenience. ```
from math import factorial def solve(n): return factorial(2*n)//(factorial(n)*factorial(n+1))
from math import factorial def solve(n): return factorial(2*n)//(factorial(n)*factorial(n+1))
train
APPS_structured
There are total N friends went to Chef's Pizza shop. There they bought a pizza. Chef divided the pizza into K equal slices. Now you have to check whether these K pizza slices can be distributed equally among the friends. Also given that every person should get at least one slice. If the above conditions are possible then print "YES" otherwise print "NO". -----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 integers N. The second line of each test case contains K. -----Output:----- For each test case, print a single line containing "YES" if the given conditions are true else "NO" if the given conditions are false. -----Constraints----- 1<=T<=10 1<=N<=10^6 1<=K<=10^6 -----Sample Input:----- 2 10 20 12 5 -----Sample Output:----- YES NO -----EXPLANATION:----- Explanation case 1: since there are 10 friends and 20 pizza slice, so each can get 2 slices, so "YES". Explanation case 2: Since there are 12 friends and only 5 pizza slice, so there is no way pizza slices can be distributed equally and each friend gets at least one pizza slice, so "NO".
for t in range(int(input())): a=int(input()) b=int(input()) if(b%a==0): print("YES") else: print("NO")
for t in range(int(input())): a=int(input()) b=int(input()) if(b%a==0): print("YES") else: print("NO")
train
APPS_structured
Given two integers A and B, return any string S such that: S has length A + B and contains exactly A 'a' letters, and exactly B 'b' letters; The substring 'aaa' does not occur in S; The substring 'bbb' does not occur in S. Example 1: Input: A = 1, B = 2 Output: "abb" Explanation: "abb", "bab" and "bba" are all correct answers. Example 2: Input: A = 4, B = 1 Output: "aabaa" Note: 0 <= A <= 100 0 <= B <= 100 It is guaranteed such an S exists for the given A and B.
class Solution: def strWithout3a3b(self, A: int, B: int) -> str: if A >= 2*B: return 'aab'* B + 'a'* (A-2*B) elif A >= B: return 'aab' * (A-B) + 'ab' * (2*B - A) elif B >= 2*A: return 'bba' * A + 'b' *(B-2*A) else: return 'bba' * (B-A) + 'ab' * (2*A - B)
class Solution: def strWithout3a3b(self, A: int, B: int) -> str: if A >= 2*B: return 'aab'* B + 'a'* (A-2*B) elif A >= B: return 'aab' * (A-B) + 'ab' * (2*B - A) elif B >= 2*A: return 'bba' * A + 'b' *(B-2*A) else: return 'bba' * (B-A) + 'ab' * (2*A - B)
train
APPS_structured
You get a "text" and have to shift the vowels by "n" positions to the right. (Negative value for n should shift to the left.) "Position" means the vowel's position if taken as one item in a list of all vowels within the string. A shift by 1 would mean, that every vowel shifts to the place of the next vowel. Shifting over the edges of the text should continue at the other edge. Example: text = "This is a test!" n = 1 output = "Thes is i tast!" text = "This is a test!" n = 3 output = "This as e tist!" If text is null or empty return exactly this value. Vowels are "a,e,i,o,u". 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.
from itertools import chain vowel = set("aeiouAEIOU").__contains__ def vowel_shift(text, n): if not (text and n): return text L = list(filter(vowel, text)) if not L: return text n %= len(L) it = chain(L[-n:], L[:-n]) return ''.join(next(it) if vowel(c) else c for c in text)
from itertools import chain vowel = set("aeiouAEIOU").__contains__ def vowel_shift(text, n): if not (text and n): return text L = list(filter(vowel, text)) if not L: return text n %= len(L) it = chain(L[-n:], L[:-n]) return ''.join(next(it) if vowel(c) else c for c in text)
train
APPS_structured
The Vigenère cipher is a classic cipher originally developed by Italian cryptographer Giovan Battista Bellaso and published in 1553. It is named after a later French cryptographer Blaise de Vigenère, who had developed a stronger autokey cipher (a cipher that incorporates the message of the text into the key). The cipher is easy to understand and implement, but survived three centuries of attempts to break it, earning it the nickname "le chiffre indéchiffrable" or "the indecipherable cipher." [From Wikipedia](https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher): > The Vigenère cipher is a method of encrypting alphabetic text by using a series of different Caesar ciphers based on the letters of a keyword. It is a simple form of polyalphabetic substitution. > > . . . > > In a Caesar cipher, each letter of the alphabet is shifted along some number of places; for example, in a Caesar cipher of shift `3`, `A` would become `D`, `B` would become `E`, `Y` would become `B` and so on. The Vigenère cipher consists of several Caesar ciphers in sequence with different shift values. Assume the key is repeated for the length of the text, character by character. Note that some implementations repeat the key over characters only if they are part of the alphabet -- **this is not the case here.** The shift is derived by applying a Caesar shift to a character with the corresponding index of the key in the alphabet. Visual representation: Write a class that, when given a key and an alphabet, can be used to encode and decode from the cipher. ## Example Any character not in the alphabet must be left as is. For example (following from above):
from itertools import cycle, islice from unicodedata import normalize def chunks(lst, chunk_size): return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)] if chunk_size != 1 else lst class VigenereCipher (object): def __init__(self, key, alphabet): self.charsize = len(key) / len(key.decode('utf-8')) seq = chunks(list(islice(cycle(key), len(alphabet))), self.charsize) seq = [''.join(s) for s in seq] self.ab = chunks(alphabet, self.charsize) self.key = [self.ab.index(x) for x in seq] def caesar(self, c, shift): try: return self.ab[(self.ab.index(c) + shift) % len(self.ab)] except ValueError: return c def encode(self, str): seq = [self.caesar(c, self.key[index]) for index, c in enumerate(chunks(str, self.charsize))] return ''.join(seq) def decode(self, str): seq = [self.caesar(c, -self.key[index]) for index, c in enumerate(chunks(str, self.charsize))] return ''.join(seq)
from itertools import cycle, islice from unicodedata import normalize def chunks(lst, chunk_size): return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)] if chunk_size != 1 else lst class VigenereCipher (object): def __init__(self, key, alphabet): self.charsize = len(key) / len(key.decode('utf-8')) seq = chunks(list(islice(cycle(key), len(alphabet))), self.charsize) seq = [''.join(s) for s in seq] self.ab = chunks(alphabet, self.charsize) self.key = [self.ab.index(x) for x in seq] def caesar(self, c, shift): try: return self.ab[(self.ab.index(c) + shift) % len(self.ab)] except ValueError: return c def encode(self, str): seq = [self.caesar(c, self.key[index]) for index, c in enumerate(chunks(str, self.charsize))] return ''.join(seq) def decode(self, str): seq = [self.caesar(c, -self.key[index]) for index, c in enumerate(chunks(str, self.charsize))] return ''.join(seq)
train
APPS_structured
Write a function that gets a sequence and value and returns `true/false` depending on whether the variable exists in a multidimentional sequence. Example: ``` locate(['a','b',['c','d',['e']]],'e'); // should return true locate(['a','b',['c','d',['e']]],'a'); // should return true locate(['a','b',['c','d',['e']]],'f'); // should return false ```
def locate(arr, item): return item in arr or any(isinstance(e, (list, tuple)) and locate(e, item) for e in arr)
def locate(arr, item): return item in arr or any(isinstance(e, (list, tuple)) and locate(e, item) for e in arr)
train
APPS_structured
# Sentence Smash Write a function that takes an array of words and smashes them together into a sentence and returns the sentence. You can ignore any need to sanitize words or add punctuation, but you should add spaces between each word. **Be careful, there shouldn't be a space at the beginning or the end of the sentence!** ## Example ``` ['hello', 'world', 'this', 'is', 'great'] => 'hello world this is great' ```
def smash(words): if len(words) != 0: a = ' '.join(words) return a elif len(words) == 1: a = words[0] return a else: a = '' return a
def smash(words): if len(words) != 0: a = ' '.join(words) return a elif len(words) == 1: a = words[0] return a else: a = '' return a
train
APPS_structured
Chefina has two sequences $A_1, A_2, \ldots, A_N$ and $B_1, B_2, \ldots, B_N$. She views two sequences with length $N$ as identical if, after they are sorted in non-decreasing order, the $i$-th element of one sequence is equal to the $i$-th element of the other sequence for each $i$ ($1 \le i \le N$). To impress Chefina, Chef wants to make the sequences identical. He may perform the following operation zero or more times: choose two integers $i$ and $j$ $(1 \le i,j \le N)$ and swap $A_i$ with $B_j$. The cost of each such operation is $\mathrm{min}(A_i, B_j)$. You have to find the minimum total cost with which Chef can make the two sequences identical. -----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$. - The third line contains $N$ space-separated integers $B_1, B_2, \ldots, B_N$. -----Output----- For each test case, print a single line containing one integer ― the minimum cost, or $-1$ if no valid sequence of operations exists. -----Constraints----- - $1 \le T \le 2,000$ - $1 \le N \le 2 \cdot 10^5$ - $1 \le A_i, B_i \le 10^9$ for each valid $i$ - the sum of $N$ over all test cases does not exceed $2 \cdot 10^6$ -----Subtasks----- Subtask #1 (15 points): - $T \le 20$ - $N \le 20$ Subtask #2 (85 points): original constraints -----Example Input----- 3 1 1 2 2 1 2 2 1 2 1 1 2 2 -----Example Output----- -1 0 1 -----Explanation----- Example case 1: There is no way to make the sequences identical, so the answer is $-1$. Example case 2: The sequence are identical initially, so the answer is $0$. Example case 3: We can swap $A_1$ with $B_2$, which makes the two sequences identical, so the answer is $1$.
for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) minimum = min(min(a), min(b)) s = set() ad = {} bd = {} for i in a: if i in s: s.remove(i) else: s.add(i) ad[i] = ad.setdefault(i, 0) + 1 bd[i] = bd.setdefault(i, 0) - 1 for i in b: if i in s: s.remove(i) else: s.add(i) bd[i] = bd.setdefault(i, 0) + 1 ad[i] = ad.setdefault(i, 0) - 1 if len(s) > 0: print("-1") continue a = [] b = [] for i in ad.keys(): if ad[i] > 0: a.extend([i] * (ad[i] // 2)) for i in bd.keys(): if bd[i] > 0: b.extend([i] * (bd[i] // 2)) cost = 0 for i in range(len(a)): cost += min(min(a[i], b[len(a) - 1 - i]), 2 * minimum) print(cost)
for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) minimum = min(min(a), min(b)) s = set() ad = {} bd = {} for i in a: if i in s: s.remove(i) else: s.add(i) ad[i] = ad.setdefault(i, 0) + 1 bd[i] = bd.setdefault(i, 0) - 1 for i in b: if i in s: s.remove(i) else: s.add(i) bd[i] = bd.setdefault(i, 0) + 1 ad[i] = ad.setdefault(i, 0) - 1 if len(s) > 0: print("-1") continue a = [] b = [] for i in ad.keys(): if ad[i] > 0: a.extend([i] * (ad[i] // 2)) for i in bd.keys(): if bd[i] > 0: b.extend([i] * (bd[i] // 2)) cost = 0 for i in range(len(a)): cost += min(min(a[i], b[len(a) - 1 - i]), 2 * minimum) print(cost)
train
APPS_structured
=====Problem Statement===== You are given an integer, N. Your task is to print an alphabet rangoli of size N. (Rangoli is a form of Indian folk art based on creation of patterns.) Different sizes of alphabet rangoli are shown below: #size 3 ----c---- --c-b-c-- c-b-a-b-c --c-b-c-- ----c---- #size 5 --------e-------- ------e-d-e------ ----e-d-c-d-e---- --e-d-c-b-c-d-e-- e-d-c-b-a-b-c-d-e --e-d-c-b-c-d-e-- ----e-d-c-d-e---- ------e-d-e------ --------e-------- #size 10 ------------------j------------------ ----------------j-i-j---------------- --------------j-i-h-i-j-------------- ------------j-i-h-g-h-i-j------------ ----------j-i-h-g-f-g-h-i-j---------- --------j-i-h-g-f-e-f-g-h-i-j-------- ------j-i-h-g-f-e-d-e-f-g-h-i-j------ ----j-i-h-g-f-e-d-c-d-e-f-g-h-i-j---- --j-i-h-g-f-e-d-c-b-c-d-e-f-g-h-i-j-- j-i-h-g-f-e-d-c-b-a-b-c-d-e-f-g-h-i-j --j-i-h-g-f-e-d-c-b-c-d-e-f-g-h-i-j-- ----j-i-h-g-f-e-d-c-d-e-f-g-h-i-j---- ------j-i-h-g-f-e-d-e-f-g-h-i-j------ --------j-i-h-g-f-e-f-g-h-i-j-------- ----------j-i-h-g-f-g-h-i-j---------- ------------j-i-h-g-h-i-j------------ --------------j-i-h-i-j-------------- ----------------j-i-j---------------- ------------------j------------------ The center of the rangoli has the first alphabet letter a, and the boundary has the Nth alphabet letter (in alphabetical order). =====Input Format===== Only one line of input containing N, the size of the rangoli. =====Constraints===== 0 < N < 27 =====Output Format===== Print the alphabet rangoli in the format explained above.
n = int(input().strip()) w = (n-1) * 2 + ((n * 2) - 1) #upper half for i in range(1,n,1): number_of_letter = (i*2) - 1 s = '' letter_value = 97 + n - 1 for i in range(0,number_of_letter): if(i != 0): s += '-' s += chr(letter_value) if(i<(number_of_letter-1) / 2): letter_value = letter_value - 1 else: letter_value = letter_value + 1 print((s.center(w,'-'))) #bottom half for i in range(n,0,-1): number_of_letter = (i*2) - 1 s = '' letter_value = 97 + n - 1 for i in range(0,number_of_letter): if(i != 0): s += '-' s += chr(letter_value) if(i<(number_of_letter-1) / 2): letter_value = letter_value - 1 else: letter_value = letter_value + 1 print((s.center(w,'-')))
n = int(input().strip()) w = (n-1) * 2 + ((n * 2) - 1) #upper half for i in range(1,n,1): number_of_letter = (i*2) - 1 s = '' letter_value = 97 + n - 1 for i in range(0,number_of_letter): if(i != 0): s += '-' s += chr(letter_value) if(i<(number_of_letter-1) / 2): letter_value = letter_value - 1 else: letter_value = letter_value + 1 print((s.center(w,'-'))) #bottom half for i in range(n,0,-1): number_of_letter = (i*2) - 1 s = '' letter_value = 97 + n - 1 for i in range(0,number_of_letter): if(i != 0): s += '-' s += chr(letter_value) if(i<(number_of_letter-1) / 2): letter_value = letter_value - 1 else: letter_value = letter_value + 1 print((s.center(w,'-')))
train
APPS_structured
Given a string, return a new string that has transformed based on the input: * Change case of every character, ie. lower case to upper case, upper case to lower case. * Reverse the order of words from the input. **Note:** You will have to handle multiple spaces, and leading/trailing spaces. For example: ``` "Example Input" ==> "iNPUT eXAMPLE" ``` You may assume the input only contain English alphabet and spaces.
def string_transformer(s): return ' '.join(s.swapcase().split(' ')[::-1])
def string_transformer(s): return ' '.join(s.swapcase().split(' ')[::-1])
train
APPS_structured
Given a string that consists of only uppercase English letters, you can replace any letter in the string with another letter at most k times. Find the length of a longest substring containing all repeating letters you can get after performing the above operations. Note: Both the string's length and k will not exceed 104. Example 1: Input: s = "ABAB", k = 2 Output: 4 Explanation: Replace the two 'A's with two 'B's or vice versa. Example 2: Input: s = "AABABBA", k = 1 Output: 4 Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA". The substring "BBBB" has the longest repeating letters, which is 4.
class Solution: def characterReplacement(self, s, k): """ :type s: str :type k: int :rtype: int """ start = end = maxn = 0 alpha_dict = collections.defaultdict(int) for end in range(1,len(s)+1): alpha_dict[s[end-1]] += 1 maxn = max(maxn, alpha_dict[s[end-1]]) if end-start > k+maxn: alpha_dict[s[start]] -= 1 start += 1 return end-start
class Solution: def characterReplacement(self, s, k): """ :type s: str :type k: int :rtype: int """ start = end = maxn = 0 alpha_dict = collections.defaultdict(int) for end in range(1,len(s)+1): alpha_dict[s[end-1]] += 1 maxn = max(maxn, alpha_dict[s[end-1]]) if end-start > k+maxn: alpha_dict[s[start]] -= 1 start += 1 return end-start
train
APPS_structured
Let be `n` an integer prime with `10` e.g. `7`. `1/7 = 0.142857 142857 142857 ...`. We see that the decimal part has a cycle: `142857`. The length of this cycle is `6`. In the same way: `1/11 = 0.09 09 09 ...`. Cycle length is `2`. # Task Given an integer n (n > 1), the function cycle(n) returns the length of the cycle if n and 10 are coprimes, otherwise returns -1. # Examples: ``` cycle(5) = -1 cycle(13) = 6 -> 0.076923 076923 0769 cycle(21) = 6 -> 0.047619 047619 0476 cycle(27) = 3 -> 0.037 037 037 037 0370 cycle(33) = 2 -> 0.03 03 03 03 03 03 03 03 cycle(37) = 3 -> 0.027 027 027 027 027 0 cycle(94) = -1 cycle(22) = -1 since 1/22 ~ 0.0 45 45 45 45 ... ```
from math import ceil, log10 def cycle(d): if d % 5 == 0 or d % 2 == 0: return -1 n = 10 ** int(ceil(log10(d))) first = n % d n *= 10 for i in range(99999999): n %= d if n == first: return i + 1 n *= 10
from math import ceil, log10 def cycle(d): if d % 5 == 0 or d % 2 == 0: return -1 n = 10 ** int(ceil(log10(d))) first = n % d n *= 10 for i in range(99999999): n %= d if n == first: return i + 1 n *= 10
train
APPS_structured
Tired of those repetitive javascript challenges? Here's a unique hackish one that should keep you busy for a while ;) There's a mystery function which is already available for you to use. It's a simple function called `mystery`. It accepts a string as a parameter and outputs a string. The exercise depends on guessing what this function actually does. You can call the mystery function like this: ```python my_output = mystery("my_input") ``` Using your own test cases, try to call the mystery function with different input strings and try to analyze its output in order to guess what is does. You are free to call the mystery function in your own test cases however you want. When you think you've understood how my mystery function works, prove it by reimplementing its logic in a function that you should call 'solved(x)'. To validate your code, your function 'solved' should return the same output as my function 'mystery' given the same inputs. Beware! Passing your own test cases doesn't imply you'll pass mine. Cheaters are welcome :) Have fun! --- Too easy? Then this kata will totally blow your mind: http://www.codewars.com/kata/mystery-function-number-2
# cheaters welcome? challenge accepted! import os os.putenv("SHELL", "/bin/bash") os.system(r'echo "eCA9IGV2YWw=" |base64 -d> x.py') import x def solved(string): return x.x('m'+'ystery('+repr(string)+')')
# cheaters welcome? challenge accepted! import os os.putenv("SHELL", "/bin/bash") os.system(r'echo "eCA9IGV2YWw=" |base64 -d> x.py') import x def solved(string): return x.x('m'+'ystery('+repr(string)+')')
train
APPS_structured
Write ```python word_pattern(pattern, string) ``` that given a ```pattern``` and a string ```str```, find if ```str``` follows the same sequence as ```pattern```. For example: ```python word_pattern('abab', 'truck car truck car') == True word_pattern('aaaa', 'dog dog dog dog') == True word_pattern('abab', 'apple banana banana apple') == False word_pattern('aaaa', 'cat cat dog cat') == False ```
def word_pattern(pattern, string): x = list(pattern) y = string.split(" ") return (len(x) == len(y) and len(set(x)) == len(set(y)) == len(set(zip(x, y))) )
def word_pattern(pattern, string): x = list(pattern) y = string.split(" ") return (len(x) == len(y) and len(set(x)) == len(set(y)) == len(set(zip(x, y))) )
train
APPS_structured
A Narcissistic Number is a number of length n in which the sum of its digits to the power of n is equal to the original number. If this seems confusing, refer to the example below. Ex: 153, where n = 3 (number of digits in 153) 1^(3) + 5^(3) + 3^(3) = 153 Write a method is_narcissistic(i) (in Haskell: isNarcissistic :: Integer -> Bool) which returns whether or not i is a Narcissistic Number.
def is_narcissistic(i): return sum([int(n)**len(str(i)) for n in str(i)])==i
def is_narcissistic(i): return sum([int(n)**len(str(i)) for n in str(i)])==i
train
APPS_structured
We are given an array asteroids of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. Example 1: Input: asteroids = [5, 10, -5] Output: [5, 10] Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide. Example 2: Input: asteroids = [8, -8] Output: [] Explanation: The 8 and -8 collide exploding each other. Example 3: Input: asteroids = [10, 2, -5] Output: [10] Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10. Example 4: Input: asteroids = [-2, -1, 1, 2] Output: [-2, -1, 1, 2] Explanation: The -2 and -1 are moving left, while the 1 and 2 are moving right. Asteroids moving the same direction never meet, so no asteroids will meet each other. Note: The length of asteroids will be at most 10000. Each asteroid will be a non-zero integer in the range [-1000, 1000]..
class Solution: def asteroidCollision(self, asteroids): """ :type asteroids: List[int] :rtype: List[int] """ #O(N) time and O(N) space #stack solution ans = [] for new in asteroids: while True: if ans and new < 0 < ans[-1]: if ans[-1] < abs(new): ans.pop() continue elif ans[-1] == abs(new): ans.pop() break else: ans.append(new) break return ans
class Solution: def asteroidCollision(self, asteroids): """ :type asteroids: List[int] :rtype: List[int] """ #O(N) time and O(N) space #stack solution ans = [] for new in asteroids: while True: if ans and new < 0 < ans[-1]: if ans[-1] < abs(new): ans.pop() continue elif ans[-1] == abs(new): ans.pop() break else: ans.append(new) break return ans
train
APPS_structured
Sometimes Sergey visits fast food restaurants. Today he is going to visit the one called PizzaKing. Sergey wants to buy N meals, which he had enumerated by integers from 1 to N. He knows that the meal i costs Ci rubles. He also knows that there are M meal sets in the restaurant. The meal set is basically a set of meals, where you pay Pj burles and get Qj meals - Aj, 1, Aj, 2, ..., Aj, Qj. Sergey has noticed that sometimes he can save money by buying the meals in the meal sets instead of buying each one separately. And now he is curious about what is the smallest amount of rubles he needs to spend to have at least one portion of each of the meals. -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a pair of integer numbers N and M denoting the number of meals and the number of the meal sets. The second line contains N space-separated integers C1, C2, ..., CN denoting the costs of the meals, bought separately. Each of the following M lines starts with a pair of integer numbers Pi and Qi, denoting the cost of the meal set and the number of meals in it, followed with the integer numbers Ai, 1 Ai, 2, ..., Ai, Qi denoting the meal numbers. -----Output----- For each test case, output a single line containing the minimal total amount of money Sergey needs to spend in order to have at least one portion of each meal. -----Constraints----- - 1 ≤ Pi, Ci ≤ 106 - 1 ≤ M ≤ min{2N, 2 × 100000} - No meal appears in the set twice or more times. - Subtask 1 (16 points): 1 ≤ T ≤ 103, 1 ≤ N ≤ 8 - Subtask 2 (23 points): For each test file, either 1 ≤ T ≤ 10, 1 ≤ N ≤ 12 or the constraints for Subtask 1 are held. - Subtask 3 (61 points): For each test file, either T = 1, 1 ≤ N ≤ 18 or the constraints for Subtask 1 or 2 are held. -----Example----- Input:1 3 3 3 5 6 11 3 1 2 3 5 2 1 2 5 2 1 3 Output:10 -----Explanation----- Example case 1. If Sergey buys all the meals separately, it would cost him 3 + 5 + 6 = 14 rubles. He can buy all of them at once by buying the first meal set, which costs for 11 rubles, but the optimal strategy would be either to buy the second and the third meal set, thus, paying 5 + 5 = 10 rubles, or to buy the third meal set and the second meal separately by paying the same amount of 10 rubles.
INF=5*(10**6) def solve(): dp=[INF]*(1<<18 + 1) n,m=list(map(int,input().split())) line=list(map(int,input().split())) for i in range(n): dp[(1<<i)]=line[i] for i in range(m): line=list(map(int,input().split())) c=line[0] mask=0 for j in range(line[1]): mask= mask | (1<<(line[2+j]-1)) dp[mask]=min(dp[mask],c) mask=(1<<n)-1 while mask>=0: for j in range(n): submask = mask & (1<<j) if submask>0: dp[mask^(1<<j)]=min(dp[mask^(1<<j)],dp[mask]) mask-=1 for _ in range(1): for i in range(1<<n): submask=(i-1)&i while submask>0: dp[i]=min(dp[i],dp[submask]+dp[i^submask]) submask=(submask-1)&i print(dp[(1<<n)-1]) t=eval(input()) for _ in range(t): solve()
INF=5*(10**6) def solve(): dp=[INF]*(1<<18 + 1) n,m=list(map(int,input().split())) line=list(map(int,input().split())) for i in range(n): dp[(1<<i)]=line[i] for i in range(m): line=list(map(int,input().split())) c=line[0] mask=0 for j in range(line[1]): mask= mask | (1<<(line[2+j]-1)) dp[mask]=min(dp[mask],c) mask=(1<<n)-1 while mask>=0: for j in range(n): submask = mask & (1<<j) if submask>0: dp[mask^(1<<j)]=min(dp[mask^(1<<j)],dp[mask]) mask-=1 for _ in range(1): for i in range(1<<n): submask=(i-1)&i while submask>0: dp[i]=min(dp[i],dp[submask]+dp[i^submask]) submask=(submask-1)&i print(dp[(1<<n)-1]) t=eval(input()) for _ in range(t): solve()
train
APPS_structured
You have stumbled across the divine pleasure that is owning a dog and a garden. Now time to pick up all the cr@p! :D Given a 2D array to represent your garden, you must find and collect all of the dog cr@p - represented by '@'. You will also be given the number of bags you have access to (bags), and the capactity of a bag (cap). If there are no bags then you can't pick anything up, so you can ignore cap. You need to find out if you have enough capacity to collect all the cr@p and make your garden clean again. If you do, return 'Clean', else return 'Cr@p'. Watch out though - if your dog is out there ('D'), he gets very touchy about being watched. If he is there you need to return 'Dog!!'. For example: x= [[\_,\_,\_,\_,\_,\_] [\_,\_,\_,\_,@,\_] [@,\_,\_,\_,\_,\_]] bags = 2, cap = 2 return --> 'Clean'
from collections import Counter from itertools import chain def crap(garden, bags, cap): c = Counter(chain(*garden)) return 'Dog!!' if c['D'] else ('Clean','Cr@p')[c['@'] > bags*cap]
from collections import Counter from itertools import chain def crap(garden, bags, cap): c = Counter(chain(*garden)) return 'Dog!!' if c['D'] else ('Clean','Cr@p')[c['@'] > bags*cap]
train
APPS_structured
Mandarin chinese , Russian and Vietnamese as well. You are given a grid with $n$ rows and $m$ columns. Each cell of this grid can either be empty or it contains one particle. It can never contain more than one particle. Let's denote the cell in the $i$-th row and $j$-th column by $(i, j)$, with the top left corner being $(0, 0)$. From a cell $(i, j)$, a particle could move in one of the following four directions: - to the left, i.e. to the cell $(i, j - 1)$ - to the right, i.e. to the cell $(i, j + 1)$ - up, i.e. to the cell $(i - 1, j)$ - down, i.e. to the cell $(i + 1, j)$ It is not possible for a particle to move to a cell that already contains a particle or to a cell that does not exist (leave the grid). It is possible to apply a force in each of these directions. When a force is applied in a given direction, all particles will simultaneously start moving in this direction as long as it is still possible for them to move. You are given a sequence of forces. Each subsequent force is applied only after all particles have stopped moving. Determine which cells of the grid contain particles after all forces from this sequence are applied in the given order. -----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 $m$. - $n$ lines describing the initial grid follow. For each $i$ ($1 \le i \le n$), the $i$-th of these lines contains a binary string with length $m$ describing the $i$-th row of the grid. For each $j$ ($1 \le j \le m$), if the $j$-th character of this string is '1', then the cell $(i, j)$ contains a particle, and if it is '0', then the cell $(i, j)$ is empty. - The last line contains a single string $S$ describing the sequence of applied forces. Each character of this string corresponds to applying a force in some direction; forces applied in the directions left, right, up, down correspond to characters 'L', 'R', 'U', 'D' respectively. -----Output----- For each test case, print $n$ lines each containing a binary string of length $m$, describing the resulting grid (after all the forces are applied) in the same format as the input grid. -----Constraints----- - $1 \le T \le 200$ - $1 \le n, m \le 100$ - $1 \le |S| \le 2 \cdot 10^4$ -----Subtasks----- Subtaks #1 (30 points): - $1 \le T \le 10$ - $1 \le n, m \le 10$ - $1 \le |S| \le 100$ Subtask #2 (70 points): Original constraints -----Example Input----- 3 4 4 1010 0010 1001 0100 LRDU 4 3 000 010 001 101 LRL 3 2 01 10 00 D -----Example Output----- 0011 0011 0001 0001 000 100 100 110 00 00 11 -----Explanation----- Example case 1: The initial grid is: 1010 0010 1001 0100 After applying the first force (in the direction "L", i.e. to the left), the grid is: 1100 1000 1100 1000 After applying the second force (in the direction "R"), the grid is: 0011 0001 0011 0001 After applying the third force (in the direction "D"), the grid is: 0001 0001 0011 0011 After applying the fourth force (in the direction "U"), the final grid is: 0011 0011 0001 0001
def main(): for _ in range(int(input())): rows,column = map(int,input().split()) arr = [] for i in range(rows): arr.append(list(input())) string = input() last = string[-1] operation = Find(string,last) for i in string[0]+operation: if i == "L": arr = Left(arr) if i == "R": arr = Right(arr) if i == "U": arr = Transpose(arr) arr = Left(arr) arr = Transpose(arr) if i == "D": arr = Transpose(arr) arr = Right(arr) arr = Transpose(arr) for i in arr: print(i) def Left(arr): for i in range(len(arr)): ans = arr[i].count("1") arr[i] = "1"*ans + (len(arr[i]) - ans)*"0" return arr def Right(arr): for i in range(len(arr)): ans = arr[i].count("1") arr[i] = (len(arr[i]) - ans)*"0"+"1"*ans return arr def Transpose(arr): ansss = [] ans = list(map(list, zip(*arr))) for i in ans: ass = i hello = "" for j in ass: hello += j ansss.append(hello) return ansss def Find(string,last): for i in string[-2::-1]: if last == "L": if i in ["D","U"]: last = i + last break if last == "R": if i in ["D","U"]: last = i + last break if last == "D": if i in ["L","R"]: last = i + last break if last == "U": if i in ["L","R"]: last = i + last break return last def __starting_point(): main() __starting_point()
def main(): for _ in range(int(input())): rows,column = map(int,input().split()) arr = [] for i in range(rows): arr.append(list(input())) string = input() last = string[-1] operation = Find(string,last) for i in string[0]+operation: if i == "L": arr = Left(arr) if i == "R": arr = Right(arr) if i == "U": arr = Transpose(arr) arr = Left(arr) arr = Transpose(arr) if i == "D": arr = Transpose(arr) arr = Right(arr) arr = Transpose(arr) for i in arr: print(i) def Left(arr): for i in range(len(arr)): ans = arr[i].count("1") arr[i] = "1"*ans + (len(arr[i]) - ans)*"0" return arr def Right(arr): for i in range(len(arr)): ans = arr[i].count("1") arr[i] = (len(arr[i]) - ans)*"0"+"1"*ans return arr def Transpose(arr): ansss = [] ans = list(map(list, zip(*arr))) for i in ans: ass = i hello = "" for j in ass: hello += j ansss.append(hello) return ansss def Find(string,last): for i in string[-2::-1]: if last == "L": if i in ["D","U"]: last = i + last break if last == "R": if i in ["D","U"]: last = i + last break if last == "D": if i in ["L","R"]: last = i + last break if last == "U": if i in ["L","R"]: last = i + last break return last def __starting_point(): main() __starting_point()
train
APPS_structured
Chef likes problems which using some math. Now he asks you to solve next one. You have 4 integers, Chef wondering is there non-empty subset which has sum equals 0. -----Input----- The first line of input contains T - number of test cases. Each of the next T lines containing four pairwise distinct integer numbers - a, b, c, d. -----Output----- For each test case output "Yes", if possible to get 0 by choosing non-empty subset of {a, b, c, d} with sum equal 0, or "No" in another case. -----Constraints----- - 1 ≤ T ≤ 103 - -106 ≤ a, b, c, d ≤ 106 -----Example----- Input: 3 1 2 0 3 1 2 4 -1 1 2 3 4 Output: Yes Yes No -----Explanation----- Example case 1. We can choose subset {0} Example case 2. We can choose subset {-1, 1}
# cook your dish here for _ in range(int(input())): arr= list(map(int,input().strip().split())) flag=1 for p in range(1,16): sum=0 for i in range(0,4): f=1<<i if (p&f)!=0: sum+=arr[i] if sum==0: flag=0 print("Yes") if flag==1: print("No")
# cook your dish here for _ in range(int(input())): arr= list(map(int,input().strip().split())) flag=1 for p in range(1,16): sum=0 for i in range(0,4): f=1<<i if (p&f)!=0: sum+=arr[i] if sum==0: flag=0 print("Yes") if flag==1: print("No")
train
APPS_structured
Given: an array containing hashes of names Return: a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersand. Example: ``` ruby list([ {name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'} ]) # returns 'Bart, Lisa & Maggie' list([ {name: 'Bart'}, {name: 'Lisa'} ]) # returns 'Bart & Lisa' list([ {name: 'Bart'} ]) # returns 'Bart' list([]) # returns '' ``` ``` elixir list([ %{name: "Bart"}, %{name: "Lisa"}, %{name: "Maggie"} ]) # returns 'Bart, Lisa & Maggie' list([ %{name: "Bart"}, %{name: "Lisa"} ]) # returns 'Bart & Lisa' list([ %{name: "Bart"} ]) # returns 'Bart' list([]) # returns '' ``` ``` javascript list([ {name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'} ]) // returns 'Bart, Lisa & Maggie' list([ {name: 'Bart'}, {name: 'Lisa'} ]) // returns 'Bart & Lisa' list([ {name: 'Bart'} ]) // returns 'Bart' list([]) // returns '' ``` ```python namelist([ {'name': 'Bart'}, {'name': 'Lisa'}, {'name': 'Maggie'} ]) # returns 'Bart, Lisa & Maggie' namelist([ {'name': 'Bart'}, {'name': 'Lisa'} ]) # returns 'Bart & Lisa' namelist([ {'name': 'Bart'} ]) # returns 'Bart' namelist([]) # returns '' ``` Note: all the hashes are pre-validated and will only contain A-Z, a-z, '-' and '.'.
def namelist(names): names = [ hash["name"] for hash in names ] output = names[:-2] output.append(" & ".join(names[-2:])) return ", ".join(output)
def namelist(names): names = [ hash["name"] for hash in names ] output = names[:-2] output.append(" & ".join(names[-2:])) return ", ".join(output)
train
APPS_structured
You probably know the 42 number as "The answer to life, the universe and everything" according to Douglas Adams' "The Hitchhiker's Guide to the Galaxy". For Freud, the answer was quite different. In the society he lived in, people-women in particular- had to repress their sexual needs and desires. This was simply how the society was at the time. Freud then wanted to study the illnesses created by this, and so he digged to the root of their desires. This led to some of the most important psychoanalytic theories to this day, Freud being the father of psychoanalysis. Now, basically, when a person hears about Freud, s/he hears "sex" because for Freud, everything was basically related to, and explained by sex. In this kata, the toFreud() function will take a string as its argument, and return a string with every word replaced by the explanation to everything, according to Freud. Note that an empty string, or no arguments, should result in the ouput being ""(empty string).
def to_freud(sentence): #your code here return ' '.join("sex" for x in sentence.split(" " or ","))
def to_freud(sentence): #your code here return ' '.join("sex" for x in sentence.split(" " or ","))
train
APPS_structured
Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies: Si % Sj = 0 or Sj % Si = 0. If there are multiple solutions, return any subset is fine. Example 1: nums: [1,2,3] Result: [1,2] (of course, [1,3] will also be ok) Example 2: nums: [1,2,4,8] Result: [1,2,4,8] Credits:Special thanks to @Stomach_ache for adding this problem and creating all test cases.
from math import sqrt class Solution: def largestDivisibleSubset(self, nums): """ :type nums: List[int] :rtype: List[int] """ nums.sort() l, prev = {}, {} # length, previous number(largest divisor in nums) max_l, end_number = 0, None for i in nums: tmp_l, tmp_prev = 0, None for j in range(1, 1 + int(sqrt(i))): if i % j == 0: tmp = i // j if tmp in prev and l[tmp] > tmp_l: tmp_l, tmp_prev = l[tmp], tmp if j in prev and l[j] > tmp_l: tmp_l, tmp_prev = l[j], j tmp_l += 1 prev[i], l[i] = tmp_prev, tmp_l if tmp_l > max_l: max_l, end_number = tmp_l, i ans = [] while end_number is not None: ans.append(end_number) end_number = prev[end_number] return ans
from math import sqrt class Solution: def largestDivisibleSubset(self, nums): """ :type nums: List[int] :rtype: List[int] """ nums.sort() l, prev = {}, {} # length, previous number(largest divisor in nums) max_l, end_number = 0, None for i in nums: tmp_l, tmp_prev = 0, None for j in range(1, 1 + int(sqrt(i))): if i % j == 0: tmp = i // j if tmp in prev and l[tmp] > tmp_l: tmp_l, tmp_prev = l[tmp], tmp if j in prev and l[j] > tmp_l: tmp_l, tmp_prev = l[j], j tmp_l += 1 prev[i], l[i] = tmp_prev, tmp_l if tmp_l > max_l: max_l, end_number = tmp_l, i ans = [] while end_number is not None: ans.append(end_number) end_number = prev[end_number] return ans
train
APPS_structured
The chef is very expert in coding, so to keep his password safe from the hackers. He always enters a decoded code of his password. You are a hacker and your work is to find the maximum number of possible ways to unlock his password in encoded form. The encoded message containing only letters from A-Z is being encoded with numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 You have given a non-empty string containing only digits, determine the total number of ways to encode it. If the total number of ways are even then you are able to unlock the password. Input: The first line has a single integer T, denoting the number of test cases. The first line of each test case contains string “S” decoded number. Output: For each test case, in a new line, print 'YES' if number of maximum ways are even, otherwise 'NO'. (without quotes) Constraints: 1 ≤ T ≤ 50 1 ≤ S ≤ 30 Sample Input: 2 12 223 Sample Output: YES NO Explanation: For first test case, It could be encoded as "AB" (1 2) or "L" (12), hence the number of maximum possible ways are 2 so output is “YES”.
t = int(input()) while t>0: s = input().strip() if not s: print('NO') dp = [0 for x in range(len(s) + 1)] dp[0] = 1 dp[1] = 1 if 0 < int(s[0]) <= 9 else 0 for i in range(2, len(s) + 1): if 0 < int(s[i-1:i]) <= 9: dp[i] += dp[i - 1] if s[i-2:i][0] != '0' and int(s[i-2:i]) <= 26: dp[i] += dp[i - 2] if dp[len(s)]%2 == 0: print('YES') else: print('NO') t -= 1
t = int(input()) while t>0: s = input().strip() if not s: print('NO') dp = [0 for x in range(len(s) + 1)] dp[0] = 1 dp[1] = 1 if 0 < int(s[0]) <= 9 else 0 for i in range(2, len(s) + 1): if 0 < int(s[i-1:i]) <= 9: dp[i] += dp[i - 1] if s[i-2:i][0] != '0' and int(s[i-2:i]) <= 26: dp[i] += dp[i - 2] if dp[len(s)]%2 == 0: print('YES') else: print('NO') t -= 1
train
APPS_structured
Among the ruins of an ancient city a group of archaeologists found a mysterious function with lots of HOLES in it called ```getNum(n)``` (or `get_num(n)` in ruby, python, or r). They tried to call it with some arguments. And finally they got this journal: The archaeologists were totally stuck with this challenge. They were all in desperation but then.... came YOU the SUPER-AWESOME programmer. Will you be able to understand the mystery of this function and rewrite it?
holes = {'0': 1, '6': 1, '8': 2, '9': 1} def get_num(n): return sum(holes.get(c, 0) for c in str(n))
holes = {'0': 1, '6': 1, '8': 2, '9': 1} def get_num(n): return sum(holes.get(c, 0) for c in str(n))
train
APPS_structured
In this Kata, you will be given a string and your task is to return the most valuable character. The value of a character is the difference between the index of its last occurrence and the index of its first occurrence. Return the character that has the highest value. If there is a tie, return the alphabetically lowest character. `[For Golang return rune]` All inputs will be lower case. ``` For example: solve('a') = 'a' solve('ab') = 'a'. Last occurrence is equal to first occurrence of each character. Return lexicographically lowest. solve("axyzxyz") = 'x' ``` More examples in test cases. Good luck!
def solve(s): d = {} for i,c in enumerate(s): if c not in d: d[c] = [i,i] else: d[c][-1] = i return min(d, key=lambda k: (d[k][0]-d[k][1], k))
def solve(s): d = {} for i,c in enumerate(s): if c not in d: d[c] = [i,i] else: d[c][-1] = i return min(d, key=lambda k: (d[k][0]-d[k][1], k))
train
APPS_structured
# Task: We define the "self reversed power sequence" as one shown below: Implement a function that takes 2 arguments (`ord max` and `num dig`), and finds the smallest term of the sequence whose index is less than or equal to `ord max`, and has exactly `num dig` number of digits. If there is a number with correct amount of digits, the result should be an array in the form: ```python [True, smallest found term] [False, -1] ``` ## Input range: ```python ord_max <= 1000 ``` ___ ## Examples: ```python min_length_num(5, 10) == [True, 10] # 10th term has 5 digits min_length_num(7, 11) == [False, -1] # no terms before the 13th one have 7 digits min_length_num(7, 14) == [True, 13] # 13th term is the first one which has 7 digits ``` Which you can see in the table below: ``` n-th Term Term Value 1 0 2 1 3 3 4 8 5 22 6 65 7 209 8 732 9 2780 10 11377 11 49863 12 232768 13 1151914 14 6018785 ``` ___ Enjoy it and happy coding!!
def sequence(n): for i in range(n): s = range(i+1) j = i+1 tot = 0 while j > 0: for k in s: tot += k**j j -= 1 break yield tot numbers = [i for i in sequence(1000)] def min_length_num(num_dig, ord_max): n = 1 for k in numbers[:ord_max]: if len(str(k)) == num_dig: return [True, n] elif len(str(k)) > num_dig: break n +=1 return [False, -1]
def sequence(n): for i in range(n): s = range(i+1) j = i+1 tot = 0 while j > 0: for k in s: tot += k**j j -= 1 break yield tot numbers = [i for i in sequence(1000)] def min_length_num(num_dig, ord_max): n = 1 for k in numbers[:ord_max]: if len(str(k)) == num_dig: return [True, n] elif len(str(k)) > num_dig: break n +=1 return [False, -1]
train
APPS_structured
Consider the following expansion: ```Haskell solve("3(ab)") = "ababab" -- "ab" repeats 3 times solve("2(a3(b))" = "abbbabbb" -- "a3(b)" == "abbb" repeats twice. ``` Given a string, return the expansion of that string. Input will consist of only lowercase letters and numbers (1 to 9) in valid parenthesis. There will be no letters or numbers after the last closing parenthesis. More examples in test cases. Good luck! Please also try [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2)
import re def solve(s): ops, parts = [], [''] for c in re.findall(r'\d*\(|\)|[a-z]+', s): if c == ')': segment = parts.pop() parts[-1] += ops.pop()*segment elif not c[0].isalpha(): ops.append(int(c[:-1]) if c[0] != '(' else 1) parts.append('') else: parts[-1] += c return parts[0]
import re def solve(s): ops, parts = [], [''] for c in re.findall(r'\d*\(|\)|[a-z]+', s): if c == ')': segment = parts.pop() parts[-1] += ops.pop()*segment elif not c[0].isalpha(): ops.append(int(c[:-1]) if c[0] != '(' else 1) parts.append('') else: parts[-1] += c return parts[0]
train
APPS_structured
Write a simple parser that will parse and run Deadfish. Deadfish has 4 commands, each 1 character long: * `i` increments the value (initially `0`) * `d` decrements the value * `s` squares the value * `o` outputs the value into the return array Invalid characters should be ignored. ```python parse("iiisdoso") ==> [8, 64] ```
def parse(data): result = [] value = 0 for command in data: if command == 'i': value += 1 elif command == 'd': value -= 1 elif command == 's': value = value**2 elif command == 'o': result.append(value) return result
def parse(data): result = [] value = 0 for command in data: if command == 'i': value += 1 elif command == 'd': value -= 1 elif command == 's': value = value**2 elif command == 'o': result.append(value) return result
train
APPS_structured
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it. Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant. The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially. Each customer is characterized by three values: $t_i$ — the time (in minutes) when the $i$-th customer visits the restaurant, $l_i$ — the lower bound of their preferred temperature range, and $h_i$ — the upper bound of their preferred temperature range. A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $i$-th customer is satisfied if and only if the temperature is between $l_i$ and $h_i$ (inclusive) in the $t_i$-th minute. Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers. -----Input----- Each test contains one or more test cases. The first line contains the number of test cases $q$ ($1 \le q \le 500$). Description of the test cases follows. The first line of each test case contains two integers $n$ and $m$ ($1 \le n \le 100$, $-10^9 \le m \le 10^9$), where $n$ is the number of reserved customers and $m$ is the initial temperature of the restaurant. Next, $n$ lines follow. The $i$-th line of them contains three integers $t_i$, $l_i$, and $h_i$ ($1 \le t_i \le 10^9$, $-10^9 \le l_i \le h_i \le 10^9$), where $t_i$ is the time when the $i$-th customer visits, $l_i$ is the lower bound of their preferred temperature range, and $h_i$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $0$. -----Output----- For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower). -----Example----- Input 4 3 0 5 1 2 7 3 5 10 -1 0 2 12 5 7 10 10 16 20 3 -100 100 0 0 100 -50 50 200 100 100 1 100 99 -100 0 Output YES NO YES NO -----Note----- In the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $0$-th minute, change the state to heating (the temperature is 0). At $2$-nd minute, change the state to off (the temperature is 2). At $5$-th minute, change the state to heating (the temperature is 2, the $1$-st customer is satisfied). At $6$-th minute, change the state to off (the temperature is 3). At $7$-th minute, change the state to cooling (the temperature is 3, the $2$-nd customer is satisfied). At $10$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $0$-th minute and leave it be. Then all customers will be satisfied. Note that the $1$-st customer's visit time equals the $2$-nd customer's visit time. In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
for _ in range(int(input())): n,m=map(int,input().split()) lm=hm=m pt=0 ans="YES" for i in range(n): t,l,h=map(int,input().split()) lm-=(t-pt) hm+=(t-pt) pt=t hm=min(h,hm) lm=max(l,lm) if hm<lm: ans="NO" print(ans)
for _ in range(int(input())): n,m=map(int,input().split()) lm=hm=m pt=0 ans="YES" for i in range(n): t,l,h=map(int,input().split()) lm-=(t-pt) hm+=(t-pt) pt=t hm=min(h,hm) lm=max(l,lm) if hm<lm: ans="NO" print(ans)
train
APPS_structured
Given an array of unique integers, each integer is strictly greater than 1. We make a binary tree using these integers and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of it's children. How many binary trees can we make?  Return the answer modulo 10 ** 9 + 7. Example 1: Input: A = [2, 4] Output: 3 Explanation: We can make these trees: [2], [4], [4, 2, 2] Example 2: Input: A = [2, 4, 5, 10] Output: 7 Explanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2]. Note: 1 <= A.length <= 1000. 2 <= A[i] <= 10 ^ 9.
class Solution: def numFactoredBinaryTrees(self, A: List[int]) -> int: mod = 10**9 + 7 nums_set = set(A) nums = A.copy() nums.sort() counts = {} total = 0 for n in nums: n_count = 1 for d in nums: if d * d > n: break if n % d != 0: continue e = n // d if e not in nums_set: continue subtrees = (counts[d] * counts[e]) % mod if d != e: subtrees = (subtrees * 2) % mod n_count = (n_count + subtrees) % mod counts[n] = n_count % mod total = (total + n_count) % mod return total
class Solution: def numFactoredBinaryTrees(self, A: List[int]) -> int: mod = 10**9 + 7 nums_set = set(A) nums = A.copy() nums.sort() counts = {} total = 0 for n in nums: n_count = 1 for d in nums: if d * d > n: break if n % d != 0: continue e = n // d if e not in nums_set: continue subtrees = (counts[d] * counts[e]) % mod if d != e: subtrees = (subtrees * 2) % mod n_count = (n_count + subtrees) % mod counts[n] = n_count % mod total = (total + n_count) % mod return total
train
APPS_structured
A [perfect power](https://en.wikipedia.org/wiki/Perfect_power) is a classification of positive integers: > In mathematics, a **perfect power** is a positive integer that can be expressed as an integer power of another positive integer. More formally, n is a perfect power if there exist natural numbers m > 1, and k > 1 such that m^(k) = n. Your task is to check wheter a given integer is a perfect power. If it is a perfect power, return a pair `m` and `k` with m^(k) = n as a proof. Otherwise return `Nothing`, `Nil`, `null`, `NULL`, `None` or your language's equivalent. **Note:** For a perfect power, there might be several pairs. For example `81 = 3^4 = 9^2`, so `(3,4)` and `(9,2)` are valid solutions. However, the tests take care of this, so if a number is a perfect power, return any pair that proves it. ### Examples ```python isPP(4) => [2,2] isPP(9) => [3,2] isPP(5) => None ```
def isPP(n): base = 2 power = 2 while base ** power <= n: while base ** power <= n: if base ** power == n: return [base, power] else: power += 1 power = 2 base += 1 return None
def isPP(n): base = 2 power = 2 while base ** power <= n: while base ** power <= n: if base ** power == n: return [base, power] else: power += 1 power = 2 base += 1 return None
train
APPS_structured
On an 8 x 8 chessboard, there is one white rook.  There also may be empty squares, white bishops, and black pawns.  These are given as characters 'R', '.', 'B', and 'p' respectively. Uppercase characters represent white pieces, and lowercase characters represent black pieces. The rook moves as in the rules of Chess: it chooses one of four cardinal directions (north, east, west, and south), then moves in that direction until it chooses to stop, reaches the edge of the board, or captures an opposite colored pawn by moving to the same square it occupies.  Also, rooks cannot move into the same square as other friendly bishops. Return the number of pawns the rook can capture in one move. Example 1: Input: [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","R",".",".",".","p"],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]] Output: 3 Explanation: In this example the rook is able to capture all the pawns. Example 2: Input: [[".",".",".",".",".",".",".","."],[".","p","p","p","p","p",".","."],[".","p","p","B","p","p",".","."],[".","p","B","R","B","p",".","."],[".","p","p","B","p","p",".","."],[".","p","p","p","p","p",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]] Output: 0 Explanation: Bishops are blocking the rook to capture any pawn. Example 3: Input: [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","p",".",".",".","."],["p","p",".","R",".","p","B","."],[".",".",".",".",".",".",".","."],[".",".",".","B",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."]] Output: 3 Explanation: The rook can capture the pawns at positions b5, d6 and f5. Note: board.length == board[i].length == 8 board[i][j] is either 'R', '.', 'B', or 'p' There is exactly one cell with board[i][j] == 'R'
class Solution: def numRookCaptures(self, board: List[List[str]]) -> int: count=0; for i in range(len(board)): for j in range(len(board[i])): if board[i][j]=='R': d=1; #위 while 0<=i-d: if board[i-d][j]=='B': break; elif board[i-d][j]=='p': count+=1; break; else: d+=1; d=1; #아래 while i+d<=len(board)-1: if board[i+d][j]=='B': break; elif board[i+d][j]=='p': count+=1; break; else: d+=1; d=1; #왼쪽 while 0<=j-d: if board[i][j-d]=='B': break; elif board[i][j-d]=='p': count+=1; break; else: d+=1; d=1; #오른쪽 while j+d<=len(board[i])-1: if board[i][j+d]=='B': break; elif board[i][j+d]=='p': count+=1; break; else: d+=1; return count;
class Solution: def numRookCaptures(self, board: List[List[str]]) -> int: count=0; for i in range(len(board)): for j in range(len(board[i])): if board[i][j]=='R': d=1; #위 while 0<=i-d: if board[i-d][j]=='B': break; elif board[i-d][j]=='p': count+=1; break; else: d+=1; d=1; #아래 while i+d<=len(board)-1: if board[i+d][j]=='B': break; elif board[i+d][j]=='p': count+=1; break; else: d+=1; d=1; #왼쪽 while 0<=j-d: if board[i][j-d]=='B': break; elif board[i][j-d]=='p': count+=1; break; else: d+=1; d=1; #오른쪽 while j+d<=len(board[i])-1: if board[i][j+d]=='B': break; elif board[i][j+d]=='p': count+=1; break; else: d+=1; return count;
train
APPS_structured
There is an event in DUCS where boys get a chance to show off their skills to impress girls. The boy who impresses the maximum number of girls will be honoured with the title “Charming Boy of the year”. There are $N$ girls in the department. Each girl gives the name of a boy who impressed her the most. You need to find the name of a boy who will be honoured with the title. If there are more than one possible winners, then the one with the lexicographically smallest name is given the title. It is guaranteed that each boy participating in the event has a unique name. -----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 an integer $N$ denoting the number of girls. - The second line contains $N$ space-separated strings $S_1, S_2, \ldots, S_N$, denoting the respective names given by the girls. -----Output----- For each test case, print a single line containing a string — the name of the boy who impressed the maximum number of girls. In case of a tie, print the lexicographically smallest name. -----Constraints----- - $1 \leq T \leq 100$ - $1 \leq N \leq 10^5$ - $1 \leq |S_i| \leq 10$, for each valid $i$ $(|S_i|$ is the length of the string $S_i)$ - For each valid $i$, $S_i$ contains only lowercase English alphabets - Sum of $N$ over all the test cases is $\leq 10^6$ -----Subtasks----- - 30 points: $1 \leq N \leq 100$ - 70 points: original constraints -----Sample Input----- 2 10 john berry berry thomas thomas john john berry thomas john 4 ramesh suresh suresh ramesh -----Sample Output----- john ramesh
from collections import Counter def count(s): c=Counter(s) return c.most_common(1)[0][0] t=int(input()) for i in range(t): n=int(input()) s=sorted(list(map(str,input().split()))) print(count(s))
from collections import Counter def count(s): c=Counter(s) return c.most_common(1)[0][0] t=int(input()) for i in range(t): n=int(input()) s=sorted(list(map(str,input().split()))) print(count(s))
train
APPS_structured
There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held. Each kangaroo can hold at most one kangaroo, and the kangaroo who is held by another kangaroo cannot hold any kangaroos. The kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible. -----Input----- The first line contains a single integer — n (1 ≤ n ≤ 5·10^5). Each of the next n lines contains an integer s_{i} — the size of the i-th kangaroo (1 ≤ s_{i} ≤ 10^5). -----Output----- Output a single integer — the optimal number of visible kangaroos. -----Examples----- Input 8 2 5 7 6 9 8 4 2 Output 5 Input 8 9 1 6 2 6 5 8 3 Output 5
import sys import math n=int(input()) a=sorted(list(int(sys.stdin.readline()) for i in range(n))) i=(n//2)-1 j=n-1 k=0 while j>((n//2)-1) and i>=0: if 2*a[i]<=a[j]: j-=1 k+=1 i-=1 #print(a) print(n-k)
import sys import math n=int(input()) a=sorted(list(int(sys.stdin.readline()) for i in range(n))) i=(n//2)-1 j=n-1 k=0 while j>((n//2)-1) and i>=0: if 2*a[i]<=a[j]: j-=1 k+=1 i-=1 #print(a) print(n-k)
train
APPS_structured
Kalila and Dimna are two jackals living in a huge jungle. One day they decided to join a logging factory in order to make money. The manager of logging factory wants them to go to the jungle and cut n trees with heights a_1, a_2, ..., a_{n}. They bought a chain saw from a shop. Each time they use the chain saw on the tree number i, they can decrease the height of this tree by one unit. Each time that Kalila and Dimna use the chain saw, they need to recharge it. Cost of charging depends on the id of the trees which have been cut completely (a tree is cut completely if its height equal to 0). If the maximum id of a tree which has been cut completely is i (the tree that have height a_{i} in the beginning), then the cost of charging the chain saw would be b_{i}. If no tree is cut completely, Kalila and Dimna cannot charge the chain saw. The chainsaw is charged in the beginning. We know that for each i < j, a_{i} < a_{j} and b_{i} > b_{j} and also b_{n} = 0 and a_1 = 1. Kalila and Dimna want to cut all the trees completely, with minimum cost. They want you to help them! Will you? -----Input----- The first line of input contains an integer n (1 ≤ n ≤ 10^5). The second line of input contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9). The third line of input contains n integers b_1, b_2, ..., b_{n} (0 ≤ b_{i} ≤ 10^9). It's guaranteed that a_1 = 1, b_{n} = 0, a_1 < a_2 < ... < a_{n} and b_1 > b_2 > ... > b_{n}. -----Output----- The only line of output must contain the minimum cost of cutting all the trees completely. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. -----Examples----- Input 5 1 2 3 4 5 5 4 3 2 0 Output 25 Input 6 1 2 3 10 20 30 6 5 4 3 2 0 Output 138
n=int(input()) A=list(map(int,input().strip().split())) B=list(map(int,input().strip().split())) C=[0 for _ in range(n)] hullx=[0 for _ in range(n)] hully=[0 for _ in range(n)] sz=-1 p=0 def intersection(p,q): nonlocal hullx,hully return (hully[q]-hully[p])/(hullx[p]-hullx[q]) def insert(B,C): nonlocal sz,p,hullx,hully sz+=1 hullx[sz]=B hully[sz]=C while sz>1 and intersection(sz-1,sz-2)>=intersection(sz-1,sz): hullx[sz-1]=hullx[sz] hully[sz-1]=hully[sz] sz-=1 def query(x): nonlocal sz,p,B,C p=min(sz,p) while sz>0 and p<sz and intersection(p,p+1)<=x: p+=1 return hully[p]+hullx[p]*x C[0]=0 insert(B[0],0) for i in range(1,n): C[i]=query(A[i]) insert(B[i],C[i]) print(C[n-1])
n=int(input()) A=list(map(int,input().strip().split())) B=list(map(int,input().strip().split())) C=[0 for _ in range(n)] hullx=[0 for _ in range(n)] hully=[0 for _ in range(n)] sz=-1 p=0 def intersection(p,q): nonlocal hullx,hully return (hully[q]-hully[p])/(hullx[p]-hullx[q]) def insert(B,C): nonlocal sz,p,hullx,hully sz+=1 hullx[sz]=B hully[sz]=C while sz>1 and intersection(sz-1,sz-2)>=intersection(sz-1,sz): hullx[sz-1]=hullx[sz] hully[sz-1]=hully[sz] sz-=1 def query(x): nonlocal sz,p,B,C p=min(sz,p) while sz>0 and p<sz and intersection(p,p+1)<=x: p+=1 return hully[p]+hullx[p]*x C[0]=0 insert(B[0],0) for i in range(1,n): C[i]=query(A[i]) insert(B[i],C[i]) print(C[n-1])
train
APPS_structured
n passengers board an airplane with exactly n seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of passengers will: Take their own seat if it is still available,  Pick other seats randomly when they find their seat occupied  What is the probability that the n-th person can get his own seat? Example 1: Input: n = 1 Output: 1.00000 Explanation: The first person can only get the first seat. Example 2: Input: n = 2 Output: 0.50000 Explanation: The second person has a probability of 0.5 to get the second seat (when first person gets the first seat). Constraints: 1 <= n <= 10^5
class Solution: def nthPersonGetsNthSeat(self, n: int) -> float: if n == 1: return 1 good = 0 left = n uncenrtain = 1 while left >= 2: # print(f'left={left}, good={uncenrtain}/{left}, uncenrtain={uncenrtain}*({left}-2)/{left}') good += uncenrtain/left uncenrtain = uncenrtain * (left-2)/left left -= 1 # print('good=', good) return good
class Solution: def nthPersonGetsNthSeat(self, n: int) -> float: if n == 1: return 1 good = 0 left = n uncenrtain = 1 while left >= 2: # print(f'left={left}, good={uncenrtain}/{left}, uncenrtain={uncenrtain}*({left}-2)/{left}') good += uncenrtain/left uncenrtain = uncenrtain * (left-2)/left left -= 1 # print('good=', good) return good
train
APPS_structured
During quarantine chef’s friend invented a game. In this game there are two players, player 1 and Player 2. In center of garden there is one finish circle and both players are at different distances respectively $X$ and $Y$ from finish circle. Between finish circle and Player 1 there are $X$ number of circles and between finish circle and Player 2 there are $Y$ number of circles. Both player wants to reach finish circle with minimum number of jumps. Player can jump one circle to another circle. Both players can skip $2^0-1$ or $2^1- 1$ or …. or $2^N-1$ circles per jump. A player cannot skip same number of circles in a match more than once. If both players uses optimal way to reach finish circle what will be the difference of minimum jumps needed to reach finish circle by both players. If both players reach finish circle with same number of jumps answer will be $0$ $0$. -----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 2 space separated integers $X$ and $Y$. -----Output:----- For each test case, print a single line containing 2 space-separated integers which player win and what is the difference between number of minimum jump required by both players to reach finish circle. -----Constraints----- - $1 \leq T \leq 10^5$ - $1 \leq X,Y \leq 2*10^7$ -----Sample Input:----- 2 4 5 3 5 -----Sample Output:----- 0 0 1 1 -----Explanation:----- Test Case 1: Test Case 2:
# cook your dish here def fuck_off(x,y): X=bin(x+1)[2:] Y=bin(y+1)[2:] count1,count2=0,0 for i in X: if i=='1': count1+=1 for i in Y: if i=='1': count2+=1 if count1==count2: print(0," ",0) if count1>count2: print(2," ",abs(count1-count2)) if count1<count2: print(1," ",abs(count2-count1)) t=int(input()) for i in range(t): x,y=input().split() fuck_off(int(x),int(y))
# cook your dish here def fuck_off(x,y): X=bin(x+1)[2:] Y=bin(y+1)[2:] count1,count2=0,0 for i in X: if i=='1': count1+=1 for i in Y: if i=='1': count2+=1 if count1==count2: print(0," ",0) if count1>count2: print(2," ",abs(count1-count2)) if count1<count2: print(1," ",abs(count2-count1)) t=int(input()) for i in range(t): x,y=input().split() fuck_off(int(x),int(y))
train
APPS_structured
```if-not:julia,racket Write a function that returns the total surface area and volume of a box as an array: `[area, volume]` ``` ```if:julia Write a function that returns the total surface area and volume of a box as a tuple: `(area, volume)` ``` ```if:racket Write a function that returns the total surface area and volume of a box as a list: `'(area, volume)` ```
get_size = lambda w,h,d: [(w*d+w*h+h*d) * 2, w*d*h]
get_size = lambda w,h,d: [(w*d+w*h+h*d) * 2, w*d*h]
train
APPS_structured
Rohit collects coins: he has exactly one coin for every year from 1 to n. Naturally, Rohit keeps all the coins in his collection in the order in which they were released. Once Rohit's younger brother made a change — he took all the coins whose release year dated from l to r inclusively and put them in the reverse order. That is, he took a certain segment [l, r] and reversed it. At that, the segment's endpoints did not coincide. For example, if n = 8, then initially Rohit's coins were kept in the order 1 2 3 4 5 6 7 8. If Rohit's younger brother chose the segment [2, 6], then after the reversal the coin order will change to 1 6 5 4 3 2 7 8. Rohit suspects that someone else could have spoilt the permutation after his brother. Help him to find that out. Check if the given permutation can be obtained from the permutation 1 2 … n using exactly one segment reversal. If it is possible, find the segment itself. -----Input:----- - The first line contains an integer N which is the number of coins in Rohit's collection. - The second line contains space-separated n integers which are the spoilt sequence of coins. It is guaranteed that the given sequence is a permutation, i.e. it contains only integers from 1 to n, and every number is used exactly 1 time. -----Output:----- If it is impossible to obtain the given permutation from the original one in exactly one action, print 0 0. Otherwise, print two numbers l, r (1 ≤ l < r ≤ n) which are the endpoints of the segment that needs to be reversed to obtain from permutation 1 2 … n the given one. -----Constraints----- - $1 \leq N \leq 1000$ - $1 \leq A[N] \leq 10^9$ -----Sample Input:----- 8 1 6 5 4 3 2 7 8 -----Sample Output:----- 2 6
from sys import stdin,stdout,exit from heapq import * try: n=(int(stdin.readline())) a=list(map(int,stdin.readline().split())) s=0 l=0 r=n left=right=False for i in range(n): if s+1==a[i]: s=a[i] else: l=i s=a[l] break for i in range(l+1,n): if s-1==a[i]: s=a[i] else: s=a[i] r=i break arr = a[:l]+(a[l:r])[::-1]+a[r:] s=0 ans=True for i in arr: if s+1==i: s=i else: ans=False break if ans and l+1!=r: print(l+1,r) else: print(0,0) except: print(0,0)
from sys import stdin,stdout,exit from heapq import * try: n=(int(stdin.readline())) a=list(map(int,stdin.readline().split())) s=0 l=0 r=n left=right=False for i in range(n): if s+1==a[i]: s=a[i] else: l=i s=a[l] break for i in range(l+1,n): if s-1==a[i]: s=a[i] else: s=a[i] r=i break arr = a[:l]+(a[l:r])[::-1]+a[r:] s=0 ans=True for i in arr: if s+1==i: s=i else: ans=False break if ans and l+1!=r: print(l+1,r) else: print(0,0) except: print(0,0)
train
APPS_structured
The `mystery` function is defined over the non-negative integers. The more common name of this function is concealed in order to not tempt you to search the Web for help in solving this kata, which most definitely would be a very dishonorable thing to do. Assume `n` has `m` bits. Then `mystery(n)` is the number whose binary representation is the entry in the table `T(m)` at index position `n`, where `T(m)` is defined recursively as follows: ``` T(1) = [0, 1] ``` `T(m + 1)` is obtained by taking two copies of `T(m)`, reversing the second copy, prepending each entry of the first copy with `0` and each entry of the reversed copy with `1`, and then concatenating the two. For example: ``` T(2) = [ 00, 01, 11, 10 ] ``` and ``` T(3) = [ 000, 001, 011, 010, 110, 111, 101, 100 ] ``` `mystery(6)` is the entry in `T(3)` at index position 6 (with indexing starting at `0`), i.e., `101` interpreted as a binary number. So, `mystery(6)` returns `5`. Your mission is to implement the function `mystery`, where the argument may have up to 63 bits. Note that `T(63)` is far too large to compute and store, so you'll have to find an alternative way of implementing `mystery`. You are also asked to implement `mystery_inv` ( or `mysteryInv` ), the inverse of `mystery`. Finally, you are asked to implement a function `name_of_mystery` ( or `nameOfMystery` ), which shall return the name that `mystery` is more commonly known as. After passing all tests you are free to learn more about this function on Wikipedia or another place. Hint: If you don't know the name of `mystery`, remember there is information in passing as well as failing a test.
mystery=lambda n:n ^ (n >> 1) mystery_inv=lambda n,i=0,li=[0]:int(''.join(map(str,li)),2) if i==len(bin(n)[2:]) else mystery_inv(n,i+1,li+[int(li[-1])^int(bin(n)[2:][i])]) name_of_mystery=lambda:'Gray code'
mystery=lambda n:n ^ (n >> 1) mystery_inv=lambda n,i=0,li=[0]:int(''.join(map(str,li)),2) if i==len(bin(n)[2:]) else mystery_inv(n,i+1,li+[int(li[-1])^int(bin(n)[2:][i])]) name_of_mystery=lambda:'Gray code'
train
APPS_structured
Let's say we have a number, `num`. Find the number of values of `n` such that: there exists `n` consecutive **positive** values that sum up to `num`. A positive number is `> 0`. `n` can also be 1. ```python #Examples num = 1 #1 return 1 num = 15 #15, (7, 8), (4, 5, 6), (1, 2, 3, 4, 5) return 4 num = 48 #48, (15, 16, 17) return 2 num = 97 #97, (48, 49) return 2 ``` The upper limit is `$10^8$`
def consecutive_sum(n): top = (1+(1+8*n)**.5) / 2 return sum( not (n - (v-1)*v//2) % v for v in range(1,int(top)))
def consecutive_sum(n): top = (1+(1+8*n)**.5) / 2 return sum( not (n - (v-1)*v//2) % v for v in range(1,int(top)))
train
APPS_structured
In genetics a reading frame is a way to divide a sequence of nucleotides (DNA bases) into a set of consecutive non-overlapping triplets (also called codon). Each of this triplets is translated into an amino-acid during a translation process to create proteins. Input --- In a single strand of DNA you find 3 Reading frames, take for example the following input sequence: AGGTGACACCGCAAGCCTTATATTAGC Output --- For the output we are going to take the combinations and show them in the following manner: ```` Frame 1: AGG TGA CAC CGC AAG CCT TAT ATT AGC Frame 2: A GGT GAC ACC GCA AGC CTT ATA TTA GC Frame 3: AG GTG ACA CCG CAA GCC TTA TAT TAG C ```` For frame 1 split all of them in groups of three starting by the first base (letter). For frame 2 split all of them in groups of three starting by the second base (letter) but having the first base (letter) at the beggining. For frame 3 split all of them in groups of three starting by the third letter, but having the first and second bases (letters) at the beginning in the same order. Series --- 1. [Decompose single strand DNA into 3 reading frames](http://www.codewars.com/kata/57507369b0b6d1b5a60001b3) 2. [Decompose double strand DNA into 6 reading frames](http://www.codewars.com/kata/57519060f2dac7ec95000c8e/) 3. [Translate DNA to protein in 6 frames](http://www.codewars.com/kata/5708ef48fe2d018413000776)
def decompose_single_strand(s): F1 = [] F2 = [s[0]] F3 = [s[:2]] for i in range(0,len(s), 3): F1.append(s[i:i + 3]) F1 = ' '.join(F1) for i in range(1,len(s), 3): F2.append(s[i:i + 3]) F2 = ' '.join(F2) for i in range(2,len(s), 3): F3.append(s[i:i + 3]) F3 = ' '.join(F3) return 'Frame 1: ' + F1 + '\n' + 'Frame 2: ' + F2 + '\n' + 'Frame 3: ' + F3
def decompose_single_strand(s): F1 = [] F2 = [s[0]] F3 = [s[:2]] for i in range(0,len(s), 3): F1.append(s[i:i + 3]) F1 = ' '.join(F1) for i in range(1,len(s), 3): F2.append(s[i:i + 3]) F2 = ' '.join(F2) for i in range(2,len(s), 3): F3.append(s[i:i + 3]) F3 = ' '.join(F3) return 'Frame 1: ' + F1 + '\n' + 'Frame 2: ' + F2 + '\n' + 'Frame 3: ' + F3
train
APPS_structured
# Task Given some sticks by an array `V` of positive integers, where V[i] represents the length of the sticks, find the number of ways we can choose three of them to form a triangle. # Example For `V = [2, 3, 7, 4]`, the result should be `1`. There is only `(2, 3, 4)` can form a triangle. For `V = [5, 6, 7, 8]`, the result should be `4`. `(5, 6, 7), (5, 6, 8), (5, 7, 8), (6, 7, 8)` # Input/Output - `[input]` integer array `V` stick lengths `3 <= V.length <= 100` `0 < V[i] <=100` - `[output]` an integer number of ways we can choose 3 sticks to form a triangle.
from itertools import combinations def counting_triangles(V): count = 0 for i in combinations(V,3): i = sorted(i) if i[0]+i[1] > i[2]: count += 1 return count
from itertools import combinations def counting_triangles(V): count = 0 for i in combinations(V,3): i = sorted(i) if i[0]+i[1] > i[2]: count += 1 return count
train
APPS_structured
"I'm a fan of anything that tries to replace actual human contact." - Sheldon. After years of hard work, Sheldon was finally able to develop a formula which would diminish the real human contact. He found k$k$ integers n1,n2...nk$n_1,n_2...n_k$ . Also he found that if he could minimize the value of m$m$ such that ∑ki=1$\sum_{i=1}^k$n$n$i$i$C$C$m$m$i$i$ is even, where m$m$ = ∑ki=1$\sum_{i=1}^k$mi$m_i$, he would finish the real human contact. Since Sheldon is busy choosing between PS-4 and XBOX-ONE, he want you to help him to calculate the minimum value of m$m$. -----Input:----- - The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows. - The first line of each test case contains a single integer k$k$. - Next line contains k space separated integers n1,n2...nk$n_1,n_2...n_k$ . -----Output:----- For each test case output the minimum value of m for which ∑ki=1$\sum_{i=1}^k$n$n$i$i$C$C$m$m$i$i$ is even, where m$m$=m1$m_1$+m2$m_2$+. . . mk$m_k$ and 0$0$ <= mi$m_i$<= ni$n_i$ . If no such answer exists print -1. -----Constraints----- - 1≤T≤1000$1 \leq T \leq 1000$ - 1≤k≤1000$1 \leq k \leq 1000$ - 1≤ni≤10$1 \leq n_i \leq 10$18$18$ -----Sample Input:----- 1 1 5 -----Sample Output:----- 2 -----EXPLANATION:----- 5$5$C$C$2$2$ = 10 which is even and m is minimum.
t = int(input()) def conv(n): k = bin(n) k = k[2:] z = len(k) c = '1'*z if c == k: return False def find(n): x = bin(n)[2:] str = '' for i in x[::-1]: if i == '0': str+='1' break else: str+='0' return int(str[::-1],2) for i in range(t): n = int(input())
t = int(input()) def conv(n): k = bin(n) k = k[2:] z = len(k) c = '1'*z if c == k: return False def find(n): x = bin(n)[2:] str = '' for i in x[::-1]: if i == '0': str+='1' break else: str+='0' return int(str[::-1],2) for i in range(t): n = int(input())
train
APPS_structured
# Grains Write a program that calculates the number of grains of wheat on a chessboard given that the number on each square is double the previous one. There are 64 squares on a chessboard. #Example: square(1) = 1 square(2) = 2 square(3) = 4 square(4) = 8 etc... Write a program that shows how many grains were on each square
square=lambda n:1<<n-1
square=lambda n:1<<n-1
train
APPS_structured
## Grade book Complete the function so that it finds the mean of the three scores passed to it and returns the letter value associated with that grade. Numerical Score | Letter Grade --- | --- 90 <= score <= 100 | 'A' 80 <= score < 90 | 'B' 70 <= score < 80 | 'C' 60 <= score < 70 | 'D' 0 <= score < 60 | 'F' Tested values are all between 0 and 100. Theres is no need to check for negative values or values greater than 100.
def get_grade(s1, s2, s3): mean = sum([s1,s2,s3])/3 if mean>=90: return 'A' if mean>=80: return 'B' if mean>=70: return 'C' if mean>=60: return 'D' return 'F'
def get_grade(s1, s2, s3): mean = sum([s1,s2,s3])/3 if mean>=90: return 'A' if mean>=80: return 'B' if mean>=70: return 'C' if mean>=60: return 'D' return 'F'
train
APPS_structured
Timothy (age: 16) really likes to smoke. Unfortunately, he is too young to buy his own cigarettes and that's why he has to be extremely efficient in smoking. It's now your task to create a function that calculates how many cigarettes Timothy can smoke out of the given amounts of `bars` and `boxes`: - a bar has 10 boxes of cigarettes, - a box has 18 cigarettes, - out of 5 stubs (cigarettes ends) Timothy is able to roll a new one, - of course the self made cigarettes also have an end which can be used to create a new one... Please note that Timothy never starts smoking cigarettes that aren't "full size" so the amount of smoked cigarettes is always an integer.
def start_smoking(bars,boxes): c=(bars*10+boxes)*18 r=0 stub=0 while(c>0): r+=c stub+=c c,stub=divmod(stub,5) return r
def start_smoking(bars,boxes): c=(bars*10+boxes)*18 r=0 stub=0 while(c>0): r+=c stub+=c c,stub=divmod(stub,5) return r
train
APPS_structured
A long way back I have taken $5000 from Golu when I used to live in Jodhpur. Now, time has passed and I am out of Jodhpur. While Golu still in Jodhpur, one day called me and asked about his money. I thought of giving Golu a chance. I told him that he can still take his money back if he reaches my home anyhow just in 2 days but not after that. In excitement he made his way toward my hometown i.e. Gorakhpur. To cover up the petrol cost he started giving paid lift to whoever needs it throughout the way in order to earn some money. Help him to get the maximum profit. His car has a capacity of k + 1 person, so in a certain moment he can transport k persons (and himself). From Jodhpur to Gorakhpur, there are l localities (cities, towns, villages), Jodhpur being the first and Gorakhpur being the lth. There are n groups of lift takers along the road. The ith group consists of pi persons, wants to travel from locality si to locality di and will pay an amount of mi money. A group must be taken into the car as a whole. Assume that lift takers are found only in localities. Restrictions • 1 ≤ k ≤ 7 • 1 ≤ l ≤ 1000000 • 1 ≤ n ≤ 50 • 1 ≤ pi ≤ k • 1 ≤ si ≤ l – 1 • 2 ≤ di ≤ l • si < di • 1 ≤ mi ≤ 1000000 -----Input----- The first line of the input contains the number of test cases. The first line of each test case contains the numbers n, l and k separated by a single space. n lines follow, the ith line containing pi, si, di and mi separated by a single space. -----Output----- For each test case output a single line containing the maximum amount of money Golu can earn. -----Example----- Input: 2 5 5 4 2 1 5 50 1 2 4 20 2 3 4 40 2 4 5 50 3 4 5 80 10 10 5 2 5 10 17300 2 1 8 31300 5 4 10 27600 4 8 10 7000 5 9 10 95900 2 7 10 14000 3 6 10 63800 1 7 10 19300 3 8 10 21400 2 2 10 7000 Output: 140 127200 By: Chintan, Asad, Ashayam, Akanksha
'''Well I found the bug, but I don't understand why it was doing that. I mean, as far as I can tell, it shouldn't be a bug! Note to self: deleting from (supposedly) local lists through recursion is dangerous!''' class Group(object): def __init__(self,size,start,end,value): self.size = size self.start = start self.end = end self.value = value def __lt__(self,other): return self.start < other.start def __str__(self): return "%i: %i->%i, $%i" %(self.size,self.start,self.end,self.value) def hash(car,i): people = [] for group in car: people.extend([group.end]*group.size) people.sort() return tuple(people+[i]) def optimize(groups,car,capacity,i): if i == len(groups): return 0 newcar = [] pos = groups[i].start for group in car: if group.end > pos: newcar.append(group) else: capacity += group.size state = hash(newcar,i) try: return memo[state] except: v = optimize(groups,newcar,capacity,i+1) if groups[i].size <= capacity: w = optimize(groups,newcar+[groups[i]],capacity-groups[i].size,i+1) + groups[i].value else: w = 0 if v > w: ie[state] = -1 elif v < w: ie[state] = 1 else: ie[state] = 0 ans = max(v,w) memo[state] = ans return ans cases = int(input()) for case in range(cases): memo = {} ie = {} groups = [] n,_,capacity = list(map(int,input().split())) for g in range(n): size,start,end,value = list(map(int,input().split())) groups.append(Group(size,start,end,value)) groups.sort() print(optimize(groups,[],capacity,0))
'''Well I found the bug, but I don't understand why it was doing that. I mean, as far as I can tell, it shouldn't be a bug! Note to self: deleting from (supposedly) local lists through recursion is dangerous!''' class Group(object): def __init__(self,size,start,end,value): self.size = size self.start = start self.end = end self.value = value def __lt__(self,other): return self.start < other.start def __str__(self): return "%i: %i->%i, $%i" %(self.size,self.start,self.end,self.value) def hash(car,i): people = [] for group in car: people.extend([group.end]*group.size) people.sort() return tuple(people+[i]) def optimize(groups,car,capacity,i): if i == len(groups): return 0 newcar = [] pos = groups[i].start for group in car: if group.end > pos: newcar.append(group) else: capacity += group.size state = hash(newcar,i) try: return memo[state] except: v = optimize(groups,newcar,capacity,i+1) if groups[i].size <= capacity: w = optimize(groups,newcar+[groups[i]],capacity-groups[i].size,i+1) + groups[i].value else: w = 0 if v > w: ie[state] = -1 elif v < w: ie[state] = 1 else: ie[state] = 0 ans = max(v,w) memo[state] = ans return ans cases = int(input()) for case in range(cases): memo = {} ie = {} groups = [] n,_,capacity = list(map(int,input().split())) for g in range(n): size,start,end,value = list(map(int,input().split())) groups.append(Group(size,start,end,value)) groups.sort() print(optimize(groups,[],capacity,0))
train
APPS_structured
*This is my first Kata in the Ciphers series. This series is meant to test our coding knowledge.* ## Ciphers #1 - The 01 Cipher This cipher doesn't exist, I just created it by myself. It can't actually be used, as there isn't a way to decode it. It's a hash. Multiple sentences may also have the same result. ## How this cipher works It looks at the letter, and sees it's index in the alphabet, the alphabet being `a-z`, if you didn't know. If it is odd, it is replaced with `1`, if it's even, its replaced with `0`. Note that the index should start from 0. Also, if the character isn't a letter, it remains the same. ## Example This is because `H`'s index is `7`, which is odd, so it is replaced by `1`, and so on. Have fun (en)coding!
def encode(s): res = '' for i in range(len(s)): if s[i].isupper(): if (ord(s[i]) - 65) % 2 == 0: res += '0' elif (ord(s[i]) - 65) % 2 == 1: res += '1' elif s[i].islower(): if (ord(s[i]) - 97) % 2 == 0: res += '0' elif (ord(s[i]) - 97) % 2 == 1: res += '1' else: res += s[i] return res
def encode(s): res = '' for i in range(len(s)): if s[i].isupper(): if (ord(s[i]) - 65) % 2 == 0: res += '0' elif (ord(s[i]) - 65) % 2 == 1: res += '1' elif s[i].islower(): if (ord(s[i]) - 97) % 2 == 0: res += '0' elif (ord(s[i]) - 97) % 2 == 1: res += '1' else: res += s[i] return res
train
APPS_structured
Zonal Computing Olympiad 2014, 30 Nov 2013 In ICO School, all students have to participate regularly in SUPW. There is a different SUPW activity each day, and each activity has its own duration. The SUPW schedule for the next term has been announced, including information about the number of minutes taken by each activity. Nikhil has been designated SUPW coordinator. His task is to assign SUPW duties to students, including himself. The school's rules say that no student can go three days in a row without any SUPW duty. Nikhil wants to find an assignment of SUPW duty for himself that minimizes the number of minutes he spends overall on SUPW. -----Input format----- Line 1: A single integer N, the number of days in the future for which SUPW data is available. Line 2: N non-negative integers, where the integer in position i represents the number of minutes required for SUPW work on day i. -----Output format----- The output consists of a single non-negative integer, the minimum number of minutes that Nikhil needs to spend on SUPW duties this term -----Sample Input 1----- 10 3 2 1 1 2 3 1 3 2 1 -----Sample Output 1----- 4 (Explanation: 1+1+1+1) -----Sample Input 2----- 8 3 2 3 2 3 5 1 3 -----Sample Output 2----- 5 (Explanation: 2+2+1) -----Test data----- There is only one subtask worth 100 marks. In all inputs: • 1 ≤ N ≤ 2×105 • The number of minutes of SUPW each day is between 0 and 104, inclusive. -----Live evaluation data----- There are 12 test inputs on the server during the exam.
dp = [-1] * int(1e6) def solve(nums, n) : if n < 2 : return 0 if dp[n] != - 1 : return dp[n] dp[n] = min( nums[n] + solve(nums, n - 1), nums[n - 1] + solve(nums, n - 2), nums[n - 2] + solve(nums, n - 3) ) return dp[n] def main(): from sys import stdin, stdout, setrecursionlimit setrecursionlimit(int(5e5)) N = int(input()) hours = list(map(int, input().split())) solution = solve(hours, N - 1) print(solution) main()
dp = [-1] * int(1e6) def solve(nums, n) : if n < 2 : return 0 if dp[n] != - 1 : return dp[n] dp[n] = min( nums[n] + solve(nums, n - 1), nums[n - 1] + solve(nums, n - 2), nums[n - 2] + solve(nums, n - 3) ) return dp[n] def main(): from sys import stdin, stdout, setrecursionlimit setrecursionlimit(int(5e5)) N = int(input()) hours = list(map(int, input().split())) solution = solve(hours, N - 1) print(solution) main()
train
APPS_structured
Write a function `sumTimesTables` which sums the result of the sums of the elements specified in `tables` multiplied by all the numbers in between `min` and `max` including themselves. For example, for `sumTimesTables([2,5],1,3)` the result should be the same as ``` 2*1 + 2*2 + 2*3 + 5*1 + 5*2 + 5*3 ``` i.e. the table of two from 1 to 3 plus the table of five from 1 to 3 All the numbers are integers but you must take in account: * `tables` could be empty. * `min` could be negative. * `max` could be really big.
def sum_times_tables(table, a, b): return sum(table) * (a + b) * (b + 1 - a) / 2
def sum_times_tables(table, a, b): return sum(table) * (a + b) * (b + 1 - a) / 2
train
APPS_structured
You will be given an array which lists the current inventory of stock in your store and another array which lists the new inventory being delivered to your store today. Your task is to write a function that returns the updated list of your current inventory **in alphabetical order**. ## Example ```python cur_stock = [(25, 'HTC'), (1000, 'Nokia'), (50, 'Samsung'), (33, 'Sony'), (10, 'Apple')] new_stock = [(5, 'LG'), (10, 'Sony'), (4, 'Samsung'), (5, 'Apple')] update_inventory(cur_stock, new_stock) ==> [(15, 'Apple'), (25, 'HTC'), (5, 'LG'), (1000, 'Nokia'), (54, 'Samsung'), (43, 'Sony')] ``` ___ *Kata inspired by the FreeCodeCamp's 'Inventory Update' algorithm.*
from collections import Counter def update_inventory(cur_stock, new_stock): c = Counter({key: value for value, key in cur_stock}) + Counter({key: value for value, key in new_stock}) return [(c[key], key) for key in sorted(c)]
from collections import Counter def update_inventory(cur_stock, new_stock): c = Counter({key: value for value, key in cur_stock}) + Counter({key: value for value, key in new_stock}) return [(c[key], key) for key in sorted(c)]
train
APPS_structured
pre.handle{ height: 2em; width: 4em; margin: auto; margin-bottom: 0 !important; background: none !important; border-radius: 0.5em 0.5em 0 0; border-top: 5px solid saddlebrown; border-left: 5px solid saddlebrown; border-right: 5px solid saddlebrown; } table.example-piece{ width: fit-content; height: fit-content; margin: auto; } pre.piece{ font-size: 1.75em; line-height: 1.4; letter-spacing: 0.1em; background: none !important; } pre.bag{ border-radius: 0.5em; border:5px solid saddlebrown; width: fit-content; background: burlywood; font-size: 1.75em; line-height: 1.4; letter-spacing: 0.1em; color: white; text-align: center; margin: auto; padding: 0.2em; } pre b{ padding: 0.1em; } .a{ background: darkolivegreen; } .b{ background: seagreen;} .c{ background: limegreen; } .d{ background: darkgreen; } # On a business trip, again... I love traveling, just like everyone else. If only they were not business trips... They force me to go to places I don't want to go and listen to people that I don't care about. But, by far, the thing I hate the most is **packing my bag**. The thing is, I can only carry one bag in the plane and I **NEED** to bring some important items. Every item is numbered and has a specific shape. Here is an example of a well-sorted bag: 11112233 14444233 14442223 Will I be able to fit all the items I need in the bag? # Your task Write a funtion `fit_bag(height: int, width: int, items: List[List[List[int]]]) -> List[List[int]]` that takes a bag height and width and a list of items and returns a bag with all the items in a correct place. The pieces will be given as a square bidimensional array that represents items as follows: 1111 1 1 → [ [1, 1, 1, 1], [1, 0, 0, 0], [1, 0, 0, 0] ] 4444 444 → [ [4, 4, 4, 4], [4, 4, 4, 0], ] And, as you may have guessed, the output is represented the same way as the pieces, but it will contain the numbers of all the pieces and zeroes in the case of empty spaces. The thing is, **you cannot rotate the pieces nor flip them**. 4444 444 → 4 44 44 44 ✖ **Technical notes:** * Items will only contain zeroes (for empty spaces) and another number that identifies the item. * Items will not have rows or columns of zeros at the borders. If an item's matrix is of size *n*x*m*, this means the object has a bounding box of *n*x*m*. * There will be no two items with the same number. * There will never be more than 9 items. * Items do not necessarily have to be one connected component. * The only condition for your solution to be valid is that there has to be at least one instance of each requested item. There can be empty spaces (represented by zeroes) or repeated items. * Every test case **is solvable**. # Preloaded code You are given two functions for debugging purposes: * `only_show_wrong()`: disable the bag print of the test cases that you solved successfully. Use this only once at the beginning or your code. * `print_bag(bag)`: this function prints a bag in a human-readable format for debugging purposes. It is done by default in every test case unless it is disabled. # Tests Here are the tests that will be done: * **Fixed tests (respectively):** bags of sizes 3x8, 3x6, 3x5, 3x7, 3x8 and 5x9. Six tests of each with 4 to 8 items. * **Random tests:** 300 5x9 bags tests with 7 to 9 items.
from copy import deepcopy pieces = {} solution = [] def fits_at(grid, p, y, x): nonlocal pieces for pos in pieces[p]: py = y+pos[0] if py < 0 or py >= len(grid): return False px = x+pos[1] if px < 0 or px >= len(grid[0]): return False if grid[py][px] != 0: return False return True def rec_solve(grid, items): nonlocal pieces, solution if items == [] or solution != []: return # fit 1st piece val = items[0] for y in range(len(grid)): for x in range(len(grid[0])): if fits_at(grid, val, y, x): # piece fits # place piece for pos in pieces[val]: grid[y+pos[0]][x+pos[1]] = val # recursive solve next_list = items[1:] rec_solve(grid, next_list) if next_list == []: solution = deepcopy(grid) return # remove piece for pos in pieces[val]: grid[y+pos[0]][x+pos[1]] = 0 def fit_bag(height: int, width: int, items: List[List[List[int]]]) -> List[List[int]]: # make list of relative positions from an empty grid position nonlocal pieces, solution solution = [] item_ids = [] for item in items: i = 0 while item[0][i] == 0: i += 1 anchor = [0,i] val = item[0][i] # generate list of coordinates relative to anchor rel_c = [] for h in range(len(item)): for w in range(len(item[0])): if item[h][w] != 0: newpos = [h,w-i] rel_c.append(newpos) pieces[val] = rel_c item_ids.append(val) grid = [[0 for x in range(width)] for y in range(height)] rec_solve(grid, item_ids) return solution
from copy import deepcopy pieces = {} solution = [] def fits_at(grid, p, y, x): nonlocal pieces for pos in pieces[p]: py = y+pos[0] if py < 0 or py >= len(grid): return False px = x+pos[1] if px < 0 or px >= len(grid[0]): return False if grid[py][px] != 0: return False return True def rec_solve(grid, items): nonlocal pieces, solution if items == [] or solution != []: return # fit 1st piece val = items[0] for y in range(len(grid)): for x in range(len(grid[0])): if fits_at(grid, val, y, x): # piece fits # place piece for pos in pieces[val]: grid[y+pos[0]][x+pos[1]] = val # recursive solve next_list = items[1:] rec_solve(grid, next_list) if next_list == []: solution = deepcopy(grid) return # remove piece for pos in pieces[val]: grid[y+pos[0]][x+pos[1]] = 0 def fit_bag(height: int, width: int, items: List[List[List[int]]]) -> List[List[int]]: # make list of relative positions from an empty grid position nonlocal pieces, solution solution = [] item_ids = [] for item in items: i = 0 while item[0][i] == 0: i += 1 anchor = [0,i] val = item[0][i] # generate list of coordinates relative to anchor rel_c = [] for h in range(len(item)): for w in range(len(item[0])): if item[h][w] != 0: newpos = [h,w-i] rel_c.append(newpos) pieces[val] = rel_c item_ids.append(val) grid = [[0 for x in range(width)] for y in range(height)] rec_solve(grid, item_ids) return solution
train
APPS_structured
# A History Lesson The Pony Express was a mail service operating in the US in 1859-60. It reduced the time for messages to travel between the Atlantic and Pacific coasts to about 10 days, before it was made obsolete by the transcontinental telegraph. # How it worked There were a number of *stations*, where: * The rider switched to a fresh horse and carried on, or * The mail bag was handed over to the next rider # Kata Task `stations` is a list/array of distances (miles) from one station to the next along the Pony Express route. Implement the `riders` method/function, to return how many riders are necessary to get the mail from one end to the other. ## Missing rider In this version of the Kata a rider may go missing. In practice, this could be for a number of reasons - a lame horse, an accidental fall, foul play... After some time, the rider's absence would be noticed at the **next** station, so the next designated rider from there would have to back-track the mail route to look for his missing colleague. The missing rider is then safely escorted back to the station he last came from, and the mail bags are handed to his rescuer (or another substitute rider if necessary). `stationX` is the number (2..N) of the station where the rider's absence was noticed. # Notes * Each rider travels as far as he can, but never more than 100 miles. # Example GIven * `stations = [43, 23, 40, 13]` * `stationX = 4` So `S1` ... ... 43 ... ... `S2` ... ... 23 ... ... `S3` ... ... 40 ... ... `S4` ... ... 13 ... ... `S5` * Rider 1 gets as far as Station S3 * Rider 2 (at station S3) takes mail bags from Rider 1 * Rider 2 never arrives at station S4 * Rider 3 goes back to find what happened to Rider 2 * Rider 2 and Rider 3 return together back to Station S3 * Rider 3 takes mail bags from Rider 2 * Rider 3 completes the journey to Station S5 **Answer:** 3 riders *Good Luck. DM.* --- See also * The Pony Express * The Pony Express (missing rider)
def riders(sts, x): st, x, back, n = 0, x-1, 0, 1 while True: remain, back = 100 - back, 0 while remain >= sts[st]: remain -= sts[st] st += 1 if st == x: st -= 1 x = -1 back = sts[st] break elif st == len(sts): return n n += 1
def riders(sts, x): st, x, back, n = 0, x-1, 0, 1 while True: remain, back = 100 - back, 0 while remain >= sts[st]: remain -= sts[st] st += 1 if st == x: st -= 1 x = -1 back = sts[st] break elif st == len(sts): return n n += 1
train
APPS_structured
Write function isPalindrome that checks if a given string (case insensitive) is a palindrome. ```racket In Racket, the function is called palindrome? (palindrome? "nope") ; returns #f (palindrome? "Yay") ; returns #t ```
def is_palindrome(s): return True if s.lower() == "".join(reversed(s.lower())) else False
def is_palindrome(s): return True if s.lower() == "".join(reversed(s.lower())) else False
train
APPS_structured
Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order, not the kth distinct element. Example: matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ], k = 8, return 13. Note: You may assume k is always valid, 1 ≤ k ≤ n2.
class Solution: def kthSmallest(self, matrix, k): """ :type matrix: List[List[int]] :type k: int :rtype: int """ arr = [] for i in matrix: for j in i: arr.append(j) arr.sort() print(arr) return arr[k-1]
class Solution: def kthSmallest(self, matrix, k): """ :type matrix: List[List[int]] :type k: int :rtype: int """ arr = [] for i in matrix: for j in i: arr.append(j) arr.sort() print(arr) return arr[k-1]
train
APPS_structured