input
stringlengths
50
13.9k
output_program
stringlengths
5
655k
output_answer
stringlengths
5
655k
split
stringclasses
1 value
dataset
stringclasses
1 value
In your class, you have started lessons about "arithmetic progression". Because you are also a programmer, you have decided to write a function. This function, arithmetic_sequence_sum(a, r, n), should return the sum of the first (n) elements of a sequence in which each element is the sum of the given integer (a), and a number of occurences of the given integer (r), based on the element's position within the sequence. For example: arithmetic_sequence_sum(2, 3, 5) should return 40: ``` 1 2 3 4 5 a + (a+r) + (a+r+r) + (a+r+r+r) + (a+r+r+r+r) 2 + (2+3) + (2+3+3) + (2+3+3+3) + (2+3+3+3+3) = 40 ```
def arithmetic_sequence_sum(a, r, n): return n * (a + a + ( n - 1) * r) / 2
def arithmetic_sequence_sum(a, r, n): return n * (a + a + ( n - 1) * r) / 2
train
APPS_structured
In this Kata, you will remove the left-most duplicates from a list of integers and return the result. ```python # Remove the 3's at indices 0 and 3 # followed by removing a 4 at index 1 solve([3, 4, 4, 3, 6, 3]) # => [4, 6, 3] ``` More examples can be found in the test cases. Good luck!
from collections import OrderedDict def solve (arr): arr = arr[::-1] arr = list(OrderedDict.fromkeys(arr))[::-1] return arr
from collections import OrderedDict def solve (arr): arr = arr[::-1] arr = list(OrderedDict.fromkeys(arr))[::-1] return arr
train
APPS_structured
Calculate the power of an army of numbers from 1 to $N$, both included. -----Input:----- - First line will contain a single integer $N$. -----Output:----- For each testcase, output in a single line containing the answer. -----Constraints----- - $1 \leq N \leq 5000$ -----Sample Input:----- 24 -----Sample Output:----- 5
# cook your dish here #powerful numbers n = int(input()) plist = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313] power = 1 for i in range(2,n+1,1): pdiv = [] count = 0 for p in plist: if i>=p and i%p==0: pdiv.append(p) for pd in pdiv: if i%(pd**2)==0: count+=1 if count==len(pdiv) and count!=0: power+=1 print(power)
# cook your dish here #powerful numbers n = int(input()) plist = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313] power = 1 for i in range(2,n+1,1): pdiv = [] count = 0 for p in plist: if i>=p and i%p==0: pdiv.append(p) for pd in pdiv: if i%(pd**2)==0: count+=1 if count==len(pdiv) and count!=0: power+=1 print(power)
train
APPS_structured
Imagine you start on the 5th floor of a building, then travel down to the 2nd floor, then back up to the 8th floor. You have travelled a total of 3 + 6 = 9 floors of distance. Given an array representing a series of floors you must reach by elevator, return an integer representing the total distance travelled for visiting each floor in the array in order. ``` // simple examples elevatorDistance([5,2,8]) = 9 elevatorDistance([1,2,3]) = 2 elevatorDistance([7,1,7,1]) = 18 // if two consecutive floors are the same, //distance travelled between them is 0 elevatorDistance([3,3]) = 0 ``` Array will always contain at least 2 floors. Random tests will contain 2-20 elements in array, and floor values between 0 and 30.
def elevator_distance(array): return sum(abs(a - b) for a, b in zip(array, array[1:]))
def elevator_distance(array): return sum(abs(a - b) for a, b in zip(array, array[1:]))
train
APPS_structured
## **Instructions** The goal of this kata is two-fold: 1.) You must produce a fibonacci sequence in the form of an array, containing a number of items equal to the input provided. 2.) You must replace all numbers in the sequence `divisible by 3` with `Fizz`, those `divisible by 5` with `Buzz`, and those `divisible by both 3 and 5` with `FizzBuzz`. For the sake of this kata, you can assume all input will be a positive integer. ## **Use Cases** Return output must be in the form of an array, with the numbers as integers and the replaced numbers (fizzbuzz) as strings. ## **Examples** Input: ```python fibs_fizz_buzz(5) ``` Output: ~~~~ [ 1, 1, 2, 'Fizz', 'Buzz' ] ~~~~ Input: ```python fibs_fizz_buzz(1) ``` Output: ~~~~ [1] ~~~~ Input: ```python fibs_fizz_buzz(20) ``` Output: ~~~~ [1,1,2,"Fizz","Buzz",8,13,"Fizz",34,"Buzz",89,"Fizz",233,377,"Buzz","Fizz",1597,2584,4181,"FizzBuzz"] ~~~~ ##Good Luck!##
def fib(n): f = [1,1] while len(f) < n: f.append(f[-2]+f[-1]) return f[:n] def fizz_buzzify(l): return ["Fizz"*(n%3==0)+"Buzz"*(n%5==0) or n for n in l] def fibs_fizz_buzz(n): return fizz_buzzify(fib(n))
def fib(n): f = [1,1] while len(f) < n: f.append(f[-2]+f[-1]) return f[:n] def fizz_buzzify(l): return ["Fizz"*(n%3==0)+"Buzz"*(n%5==0) or n for n in l] def fibs_fizz_buzz(n): return fizz_buzzify(fib(n))
train
APPS_structured
=====Function Descriptions===== One of the built-in functions of Python is divmod, which takes two arguments a and b and returns a tuple containing the quotient of first and then the remainder. =====Problem Statement===== For example: >>> print divmod(177,10) (17, 7) Here, the integer division is 177/10 => 17 and the modulo operator is 177%10 => 7. Task Read in two integers, a and b, and print three lines. The first line is the integer division a//b (While using Python2 remember to import division from __future__). The second line is the result of the modulo operator: a%b. The third line prints the divmod of a and b. =====Input Format===== The first line contains the first integer, a, and the second line contains the second integer, b. =====Output Format===== Print the result as described above.
output = divmod(int(input().strip()), int(input().strip())) print(output[0]) print(output[1]) print(output)
output = divmod(int(input().strip()), int(input().strip())) print(output[0]) print(output[1]) print(output)
train
APPS_structured
Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences.  If multiple answers exist, you may return any of them. (A string S is a subsequence of string T if deleting some number of characters from T (possibly 0, and the characters are chosen anywhere from T) results in the string S.) Example 1: Input: str1 = "abac", str2 = "cab" Output: "cabac" Explanation: str1 = "abac" is a subsequence of "cabac" because we can delete the first "c". str2 = "cab" is a subsequence of "cabac" because we can delete the last "ac". The answer provided is the shortest such string that satisfies these properties. Note: 1 <= str1.length, str2.length <= 1000 str1 and str2 consist of lowercase English letters.
class Solution: def shortestCommonSupersequence(self, str1: str, str2: str) -> str: m, n = len(str1), len(str2) dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if str1[i - 1] == str2[j - 1]: dp[i][j] = 1 + dp[i - 1][j - 1] else: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) s = [] i, j = m, n while i > 0 and j > 0: if str1[i - 1] == str2[j - 1]: s.append(str1[i - 1]) i -= 1 j -= 1 elif dp[i][j - 1] > dp[i - 1][j]: s.append(str2[j - 1]) j -= 1 else: s.append(str1[i - 1]) i -= 1 while j > 0: s.append(str2[j - 1]) j -= 1 while i > 0: s.append(str1[i - 1]) i -= 1 s.reverse() return ''.join(s)
class Solution: def shortestCommonSupersequence(self, str1: str, str2: str) -> str: m, n = len(str1), len(str2) dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if str1[i - 1] == str2[j - 1]: dp[i][j] = 1 + dp[i - 1][j - 1] else: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) s = [] i, j = m, n while i > 0 and j > 0: if str1[i - 1] == str2[j - 1]: s.append(str1[i - 1]) i -= 1 j -= 1 elif dp[i][j - 1] > dp[i - 1][j]: s.append(str2[j - 1]) j -= 1 else: s.append(str1[i - 1]) i -= 1 while j > 0: s.append(str2[j - 1]) j -= 1 while i > 0: s.append(str1[i - 1]) i -= 1 s.reverse() return ''.join(s)
train
APPS_structured
You are given a binary string S. You need to transform this string into another string of equal length consisting only of zeros, with the minimum number of operations. A single operation consists of taking some prefix of the string S and flipping all its values. That is, change all the 0s in this prefix to 1s, and all the 1s in the prefix to 0s. You can use this operation as many number of times as you want over any prefix of the string. -----Input----- The only line of the input contains the binary string, S . -----Output----- Output a single line containing one integer, the minimum number of operations that are needed to transform the given string S into the string of equal length consisting only of zeros. -----Constraints----- - 1 ≤ |S| ≤ 100,000 -----Subtasks----- - Subtask #1 (30 points): 1 ≤ |S| ≤ 2000 - Subtask #2 (70 points): Original constraints. -----Example----- Input: 01001001 Output: 6 -----Explanation----- For the given sample case, let us look at the way where we achieved minimum number of operations. Operation 1: You flip values in the prefix of length 8 and transform the string into 10110110 Operation 2: You flip values in the prefix of length 7 and transform the string into 01001000 Operation 3: You flip values in the prefix of length 5 and transform the string into 10110000 Operation 4: You flip values in the prefix of length 4 and transform the string into 01000000 Operation 5: You flip values in the prefix of length 2 and transform the string into 10000000 Operation 6: You flip values in the prefix of length 1 and finally, transform the string into 00000000
# cook your dish here S=str(input()) a=[] for i in S: a.append(i) c=0 for i in range(len(a)-1,-1,-1): if a[i]=='1': for k in range(0,i+1): if a[k]=='1': a[k]='0' else: a[k]='1' c=c+1 print(c)
# cook your dish here S=str(input()) a=[] for i in S: a.append(i) c=0 for i in range(len(a)-1,-1,-1): if a[i]=='1': for k in range(0,i+1): if a[k]=='1': a[k]='0' else: a[k]='1' c=c+1 print(c)
train
APPS_structured
You are given two jugs with capacities x and y litres. There is an infinite amount of water supply available. You need to determine whether it is possible to measure exactly z litres using these two jugs. If z liters of water is measurable, you must have z liters of water contained within one or both buckets by the end. Operations allowed: Fill any of the jugs completely with water. Empty any of the jugs. Pour water from one jug into another till the other jug is completely full or the first jug itself is empty. Example 1: (From the famous "Die Hard" example) Input: x = 3, y = 5, z = 4 Output: True Example 2: Input: x = 2, y = 6, z = 5 Output: False Credits:Special thanks to @vinod23 for adding this problem and creating all test cases.
class Solution: def canMeasureWater(self, x, y, z): """ :type x: int :type y: int :type z: int :rtype: bool """ if not x or not y: # (if x == 0 or y == 0): return (z == 0) return not z if z > x + y: return False # greatest common divisor --> Euclidian Algorithm while x != y: if x > y: x, y = x - y, y else: x, y = x, y - x return False if z % x else True
class Solution: def canMeasureWater(self, x, y, z): """ :type x: int :type y: int :type z: int :rtype: bool """ if not x or not y: # (if x == 0 or y == 0): return (z == 0) return not z if z > x + y: return False # greatest common divisor --> Euclidian Algorithm while x != y: if x > y: x, y = x - y, y else: x, y = x, y - x return False if z % x else True
train
APPS_structured
You are given a license key represented as a string S which consists only alphanumeric character and dashes. The string is separated into N+1 groups by N dashes. Given a number K, we would want to reformat the strings such that each group contains exactly K characters, except for the first group which could be shorter than K, but still must contain at least one character. Furthermore, there must be a dash inserted between two groups and all lowercase letters should be converted to uppercase. Given a non-empty string S and a number K, format the string according to the rules described above. Example 1: Input: S = "5F3Z-2e-9-w", K = 4 Output: "5F3Z-2E9W" Explanation: The string S has been split into two parts, each part has 4 characters. Note that the two extra dashes are not needed and can be removed. Example 2: Input: S = "2-5g-3-J", K = 2 Output: "2-5G-3J" Explanation: The string S has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above. Note: The length of string S will not exceed 12,000, and K is a positive integer. String S consists only of alphanumerical characters (a-z and/or A-Z and/or 0-9) and dashes(-). String S is non-empty.
class Solution: def licenseKeyFormatting(self, S, K): """ :type S: str :type K: int :rtype: str """ S = S.replace("-", "") l = len(S) res = l % K if res == 0: return "-".join([S[i*K: (i+1)*K].upper() for i in range(l//K)]) else: lst = [S[0:res].upper()] return "-".join(lst + [S[i*K + res: (i+1)*K + res].upper() for i in range(l//K)])
class Solution: def licenseKeyFormatting(self, S, K): """ :type S: str :type K: int :rtype: str """ S = S.replace("-", "") l = len(S) res = l % K if res == 0: return "-".join([S[i*K: (i+1)*K].upper() for i in range(l//K)]) else: lst = [S[0:res].upper()] return "-".join(lst + [S[i*K + res: (i+1)*K + res].upper() for i in range(l//K)])
train
APPS_structured
Now-a-days, Manish is becoming famous for bank robbery in the country because of his cleverness, he never robs own his own.He has four workers A , B, C, and D , all working under him.All of the four take some amount for that. There are total N banks in the country and Manish wants to rob all the banks with minimum amount spent on workers.Only one worker is allowed to rob the ith bank but following a condition that if one worker robs ith bank, then he can't rob (i+1) th bank. So ,Manish wants you to calculate minimum amount that he has to spend on all workers to rob all N banks. -----Input Format----- First line consists number of test cases T.For each test case, first line consists an integer N, number of banks in the country and the next N line consists 4 integers amount taken by A,B,C and D respectively to rob ith bank. -----Output format----- For each test case ,output an integer, minimum amount paid by Manish in separate line . -----Constraint----- - 1<=T<=1000 - 1<=N<=100000 - 1<=amount<=100000 -----Subtasks----- Subtask-1 (10 points) - 1<=T<=5 - 1<=N<=10 - 1<=amount<=10 Subtask-1 (30 points) - 1<=T<=100 - 1<=N<=1000 - 1<=amount<=1000 Subtask-1 (60 points) Original Constraints Sample Input 1 3 4 7 2 9 5 6 4 7 2 6 4 3 Sample Output 10
for t in range( eval(input()) ) : dp = [ [0 for i in range(4)] for j in range(2) ] ret = 1 for u in range( eval(input()) ) : c = list(map( int, input().split() )) for i in range( 4 ) : dp[u&1][i] = 1e18 for j in range( 4 ) : if j != i : dp[u&1][i] = min( dp[u&1][i], c[j] + dp[1-(u&1)][j]) ret = min(dp[u&1]) print(ret)
for t in range( eval(input()) ) : dp = [ [0 for i in range(4)] for j in range(2) ] ret = 1 for u in range( eval(input()) ) : c = list(map( int, input().split() )) for i in range( 4 ) : dp[u&1][i] = 1e18 for j in range( 4 ) : if j != i : dp[u&1][i] = min( dp[u&1][i], c[j] + dp[1-(u&1)][j]) ret = min(dp[u&1]) print(ret)
train
APPS_structured
In this kata your mission is to rotate matrix counter - clockwise N-times. So, you will have 2 inputs: 1)matrix 2)a number, how many times to turn it And an output is turned matrix. Example: matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] times_to_turn = 1 It should return this: [[4, 8, 12, 16], [3, 7, 11, 15], [2, 6, 10, 14], [1, 5, 9, 13]]) Note: all matrixes will be square. Also random tests will have big numbers in input (times to turn) Happy coding!
rotate_against_clockwise=lambda a,n:rotate_against_clockwise(list(zip(*a))[::-1],n-1) if n%4 else list(map(list,a))
rotate_against_clockwise=lambda a,n:rotate_against_clockwise(list(zip(*a))[::-1],n-1) if n%4 else list(map(list,a))
train
APPS_structured
We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 10^9 + 7. The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string. -----Input----- The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 10^6. -----Output----- Print the minimum number of steps modulo 10^9 + 7. -----Examples----- Input ab Output 1 Input aab Output 3 -----Note----- The first example: "ab" → "bba". The second example: "aab" → "abba" → "bbaba" → "bbbbaa".
s = input() cnt = 0 m=10**9 + 7 t = 0 for i in range(len(s)): if s[~i] == 'a': cnt = (cnt+t)%m t = (t*2)%m else: t += 1 print(cnt) """s = raw_input() m = 0 n = 0 twop = 1 ans = 0 mold = [0,0] isbool1 = True isbool2 = False def twopower(x): d = {0:1} if x in d: return d[x] else: if x%2 == 0: d[x] = twopower(x/2)**2 return d[x] else: d[x] = twopower(x-1)*2 return d[x] for char in s: if char == "a": m += 1 else: ans += twopower(m)-1 ans = ans%(10**9+7) print ans%(10**9+7)""" """ for char in s: if char == "a": m += 1 if isbool == True: twop *= twopower(m-mold[1]) ans += n*(twop-1) isbool = False n = 0 else: mold = [mold[1],m] n += 1 isbool = True if s[-1] == "a": print ans else: twop *= twopower(m-mold[0]) ans += n*(twop-1) print ans """
s = input() cnt = 0 m=10**9 + 7 t = 0 for i in range(len(s)): if s[~i] == 'a': cnt = (cnt+t)%m t = (t*2)%m else: t += 1 print(cnt) """s = raw_input() m = 0 n = 0 twop = 1 ans = 0 mold = [0,0] isbool1 = True isbool2 = False def twopower(x): d = {0:1} if x in d: return d[x] else: if x%2 == 0: d[x] = twopower(x/2)**2 return d[x] else: d[x] = twopower(x-1)*2 return d[x] for char in s: if char == "a": m += 1 else: ans += twopower(m)-1 ans = ans%(10**9+7) print ans%(10**9+7)""" """ for char in s: if char == "a": m += 1 if isbool == True: twop *= twopower(m-mold[1]) ans += n*(twop-1) isbool = False n = 0 else: mold = [mold[1],m] n += 1 isbool = True if s[-1] == "a": print ans else: twop *= twopower(m-mold[0]) ans += n*(twop-1) print ans """
train
APPS_structured
You are given a permutation of 1,2,...,N: p_1,p_2,...,p_N. Determine if the state where p_i=i for every i can be reached by performing the following operation any number of times: - Choose three elements p_{i-1},p_{i},p_{i+1} (2\leq i\leq N-1) such that p_{i-1}>p_{i}>p_{i+1} and reverse the order of these three. -----Constraints----- - 3 \leq N \leq 3 × 10^5 - p_1,p_2,...,p_N is a permutation of 1,2,...,N. -----Input----- Input is given from Standard Input in the following format: N p_1 : p_N -----Output----- If the state where p_i=i for every i can be reached by performing the operation, print Yes; otherwise, print No. -----Sample Input----- 5 5 2 1 4 3 -----Sample Output----- Yes The state where p_i=i for every i can be reached as follows: - Reverse the order of p_1,p_2,p_3. The sequence p becomes 1,2,5,4,3. - Reverse the order of p_3,p_4,p_5. The sequence p becomes 1,2,3,4,5.
def Split(a): no = [] for i, x in a: if no and (i == x) == (no[-1][0] == no[-1][1]): yield no no = [] no.append((i, x)) yield no for sq in Split((i + 1, int(input())) for i in range(int(input()))): tb = [0, 0] for np, goal in sq: if goal != np: if goal < tb[np < goal] or goal > sq[-1][0] or goal < sq[0][0]: print("No") return tb[np < goal] = goal print("Yes")
def Split(a): no = [] for i, x in a: if no and (i == x) == (no[-1][0] == no[-1][1]): yield no no = [] no.append((i, x)) yield no for sq in Split((i + 1, int(input())) for i in range(int(input()))): tb = [0, 0] for np, goal in sq: if goal != np: if goal < tb[np < goal] or goal > sq[-1][0] or goal < sq[0][0]: print("No") return tb[np < goal] = goal print("Yes")
train
APPS_structured
To help Lavanya learn all about binary numbers and binary sequences, her father has bought her a collection of square tiles, each of which has either a 0 or a 1 written on it. Her brother Nikhil has played a rather nasty prank. He has glued together pairs of tiles with 0 written on them. Lavanya now has square tiles with 1 on them and rectangular tiles with two 0's on them, made up of two square tiles with 0 stuck together). Thus, she can no longer make all possible binary sequences using these tiles. To amuse herself, Lavanya has decided to pick a number $N$ and try and construct as many binary sequences of length $N$ as possible using her collection of tiles. For example if $N$ = 1, she can only make the sequence 1. For $N$=2, she can make 11 and 00. For $N$=4, there are 5 possibilities: 0011, 0000, 1001, 1100 and 1111. Lavanya would like you to write a program to compute the number of arrangements possible with $N$ tiles so that she can verify that she has generated all of them. Since she cannot count beyond 15746, it is sufficient to report this number modulo 15746. -----Input:----- A single line with a single integer $N$. -----Output:----- A single integer indicating the number of binary sequences of length $N$, modulo 15746, that Lavanya can make using her tiles. -----Constraints:----- You may assume that $N \leq$ 1000000. -----Sample Input:----- 4 -----Sample Output:----- 5 -----Explanation:----- This corresponds to the example discussed above.
def fib(n): s1,s2=1,2 if n==1: return s1 elif n==2: return s2 else: for i in range(2,n): s3=(s1+s2)%15746 s1=s2 s2=s3 return s2%15746 try: n=int(input()) z=fib(n) print(z) except: pass
def fib(n): s1,s2=1,2 if n==1: return s1 elif n==2: return s2 else: for i in range(2,n): s3=(s1+s2)%15746 s1=s2 s2=s3 return s2%15746 try: n=int(input()) z=fib(n) print(z) except: pass
train
APPS_structured
# Task Given an array `arr` and a number `n`. Call a pair of numbers from the array a `Perfect Pair` if their sum is equal to `n`. Find all of the perfect pairs and return the sum of their **indices**. Note that any element of the array can only be counted in one Perfect Pair. Also if there are multiple correct answers, return the smallest one. # Example For `arr = [1, 4, 2, 3, 0, 5] and n = 7`, the result should be `11`. Since the Perfect Pairs are `(4, 3)` and `(2, 5)` with indices `1 + 3 + 2 + 5 = 11`. For `arr = [1, 3, 2, 4] and n = 4`, the result should be `1`. Since the element at `index 0` (i.e. 1) and the element at `index 1` (i.e. 3) form the only Perfect Pair. # Input/Output - `[input]` integer array `arr` array of non-negative integers. - `[input]` integer `n` positive integer - `[output]` integer sum of indices and 0 if no Perfect Pair exists.
def pairwise(arr, n): # fiond each pair of elements that add up to n in arr a, i, j, pairs = sorted(arr), 0, len(arr) - 1, [] while i < j: tot = a[i] + a[j] if tot == n: pairs.extend([a[i], a[j]]) i, j = i + 1, j - 1 elif tot < n: i += 1 else: j -= 1 pairs.sort() # Identify the lowest possible index for each element in pairs indices = [] i, last = 0, None for x in pairs: # Continue from last found if repeat value else from start of array i = (indices[-1] + 1) if x == last else 0 indices.append(arr.index(x, i)) last = x return sum(indices)
def pairwise(arr, n): # fiond each pair of elements that add up to n in arr a, i, j, pairs = sorted(arr), 0, len(arr) - 1, [] while i < j: tot = a[i] + a[j] if tot == n: pairs.extend([a[i], a[j]]) i, j = i + 1, j - 1 elif tot < n: i += 1 else: j -= 1 pairs.sort() # Identify the lowest possible index for each element in pairs indices = [] i, last = 0, None for x in pairs: # Continue from last found if repeat value else from start of array i = (indices[-1] + 1) if x == last else 0 indices.append(arr.index(x, i)) last = x return sum(indices)
train
APPS_structured
Consider the following array: ``` [1, 12, 123, 1234, 12345, 123456, 1234567, 12345678, 123456789, 12345678910, 1234567891011...] ``` If we join these blocks of numbers, we come up with an infinite sequence which starts with `112123123412345123456...`. The list is infinite. You will be given an number (`n`) and your task will be to return the element at that index in the sequence, where `1 ≤ n ≤ 10^18`. Assume the indexes start with `1`, not `0`. For example: ``` solve(1) = 1, because the first character in the sequence is 1. There is no index 0. solve(2) = 1, because the second character is also 1. solve(3) = 2, because the third character is 2. ``` More examples in the test cases. Good luck!
def cumul(n) : return n*(n+1)//2 # length of the line for the n index def length (n) : res = cumul(n) length = len(str(n)) i = 1 while length>1 : res += cumul (n-(10**i -1)) length -=1 i+=1 return res def calculindex(d) : if d <= 9 : return d index = index_old = 9 i=0 while d> index : index_old = index i+=1 index = index_old + 9*(i+1)*10**i d-= index_old if d%(i+1)== 0 : return (str(10**(i)+d//(i+1) -1)[-1]) else : return (str(10**(i)+d//(i+1))[d%(i+1)-1]) def solve(n): print(n) if n<=2: return 1 min = 1 max = n val = int(n//2)+1 while length(min)< n< length(max) and max-min>1 : if length(val)>n : max,val = val,(val+min)//2 elif length(val)< n: min,val = val,(max+val)//2 else : return int(str(val)[-1]) dist = n-length(min) return int(calculindex(dist))
def cumul(n) : return n*(n+1)//2 # length of the line for the n index def length (n) : res = cumul(n) length = len(str(n)) i = 1 while length>1 : res += cumul (n-(10**i -1)) length -=1 i+=1 return res def calculindex(d) : if d <= 9 : return d index = index_old = 9 i=0 while d> index : index_old = index i+=1 index = index_old + 9*(i+1)*10**i d-= index_old if d%(i+1)== 0 : return (str(10**(i)+d//(i+1) -1)[-1]) else : return (str(10**(i)+d//(i+1))[d%(i+1)-1]) def solve(n): print(n) if n<=2: return 1 min = 1 max = n val = int(n//2)+1 while length(min)< n< length(max) and max-min>1 : if length(val)>n : max,val = val,(val+min)//2 elif length(val)< n: min,val = val,(max+val)//2 else : return int(str(val)[-1]) dist = n-length(min) return int(calculindex(dist))
train
APPS_structured
The Padovan sequence is the sequence of integers `P(n)` defined by the initial values `P(0)=P(1)=P(2)=1` and the recurrence relation `P(n)=P(n-2)+P(n-3)` The first few values of `P(n)` are `1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37, 49, 65, 86, 114, 151, 200, 265, ...` ### Task The task is to write a method that returns i-th Padovan number ```python > padovan(0) == 1 > padovan(1) == 1 > padovan(2) == 1 > padovan(n) = padovan(n-2) + padovan(n-3) ```
from functools import lru_cache @lru_cache() def padovan(n): return 1 if n < 3 else padovan(n-2) + padovan(n-3)
from functools import lru_cache @lru_cache() def padovan(n): return 1 if n < 3 else padovan(n-2) + padovan(n-3)
train
APPS_structured
You are stacking some boxes containing gold weights on top of each other. If a box contains more weight than the box below it, it will crash downwards and combine their weights. e.g. If we stack [2] on top of [1], it will crash downwards and become a single box of weight [3] ``` [2] [1] --> [3] ``` Given an array of arrays, return the bottom row (i.e. the last array) after all crashings are complete. ``` crashing_weights([[1, 2, 3], --> [[1, 2, ], [[1, , ]], [2, 3, 1], --> [2, 3, 4], --> [2, 2, ], [3, 1, 2]]) [3, 1, 2]] --> [3, 4, 6]] therefore return [3, 4, 6] ``` ## More details boxes can be stacked to any height, and the crashing effect can snowball: ``` [3] [2] [5] [4] --> [4] --> [9] ``` Crashing should always start from as high up as possible -- this can alter the outcome! e.g. ``` [3] [3] [2] [5] [2] [3] [1] --> [1] --> [6], not [1] --> [3] ``` Weights will always be integers. The matrix (array of arrays) may have any height or width > 1, and may not be square, but it will always be "nice" (all rows will have the same number of columns, etc).
from functools import reduce def crashing_weights(weights): return reduce(crash_if_heavier, weights) def crash_if_heavier(upper_row, lower_row): return [wl if wu <= wl else wu + wl for wu, wl in zip(upper_row, lower_row)]
from functools import reduce def crashing_weights(weights): return reduce(crash_if_heavier, weights) def crash_if_heavier(upper_row, lower_row): return [wl if wu <= wl else wu + wl for wu, wl in zip(upper_row, lower_row)]
train
APPS_structured
**Background** You most probably know, that the *kilo* used by IT-People differs from the *kilo* used by the rest of the world. Whereas *kilo* in kB is (mostly) intrepreted as 1024 Bytes (especially by operating systems) the non-IT *kilo* denotes the factor 1000 (as in "1 kg is 1000g"). The same goes for the prefixes mega, giga, tera, peta and so on. To avoid misunderstandings (like your hardware shop selling you a 1E+12 Byte harddisk as 1 TB, whereas your Windows states that it has only 932 GB, because the shop uses factor 1000 whereas operating systems use factor 1024 by default) the International Electrotechnical Commission has proposed to use **kibibyte** for 1024 Byte.The according unit symbol would be **KiB**. Other Prefixes would be respectivly: ``` 1 MiB = 1024 KiB 1 GiB = 1024 MiB 1 TiB = 1024 GiB ``` **Task** Your task is to write a conversion function between the kB and the KiB-Units. The function receives as parameter a memory size including a unit and converts into the corresponding unit of the other system: ``` memorysizeConversion ( "10 KiB") -> "10.24 kB" memorysizeConversion ( "1 kB") -> "0.977 KiB" memorysizeConversion ( "10 TB") -> "9.095 TiB" memorysizeConversion ( "4.1 GiB") -> "4.402 GB" ``` **Hints** - the parameter always contains a (fractioned) number, a whitespace and a valid unit - units are case sensitive, valid units are **kB MB GB TB KiB MiB GiB TiB** - result must be rounded to 3 decimals (round half up,no trailing zeros) see examples above **Resources** If you want to read more on ...ibi-Units: https://en.wikipedia.org/wiki/Kibibyte
DCT_TO_IB = { unit: 1.024**p for unit,p in zip('KMGT',range(1,5)) } def memorysize_conversion(s): toB = s[-2]=='i' v,u = s.split() unit = (u[0]!='K' and u[0] or 'k')+u[-1] if toB else u[0].upper()+"i"+u[-1] out = float(v) * DCT_TO_IB[u[0].upper()]**(toB or -1) out = f'{ out :.3f}'.rstrip('0') return f'{out} {unit}'
DCT_TO_IB = { unit: 1.024**p for unit,p in zip('KMGT',range(1,5)) } def memorysize_conversion(s): toB = s[-2]=='i' v,u = s.split() unit = (u[0]!='K' and u[0] or 'k')+u[-1] if toB else u[0].upper()+"i"+u[-1] out = float(v) * DCT_TO_IB[u[0].upper()]**(toB or -1) out = f'{ out :.3f}'.rstrip('0') return f'{out} {unit}'
train
APPS_structured
You are given a sequence D_1, D_2, ..., D_N of length N. The values of D_i are all distinct. Does a tree with N vertices that satisfies the following conditions exist? - The vertices are numbered 1,2,..., N. - The edges are numbered 1,2,..., N-1, and Edge i connects Vertex u_i and v_i. - For each vertex i, the sum of the distances from i to the other vertices is D_i, assuming that the length of each edge is 1. If such a tree exists, construct one such tree. -----Constraints----- - 2 \leq N \leq 100000 - 1 \leq D_i \leq 10^{12} - D_i are all distinct. -----Input----- Input is given from Standard Input in the following format: N D_1 D_2 : D_N -----Output----- If a tree with n vertices that satisfies the conditions does not exist, print -1. If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted. -----Sample Input----- 7 10 15 13 18 11 14 19 -----Sample Output----- 1 2 1 3 1 5 3 4 5 6 6 7 The tree shown below satisfies the conditions.
n = int(input()) d = [int(input()) for i in range(n)] if sum(d)%2 > 0: print((-1)) return d = sorted([(dd, i) for i, dd in enumerate(d)], reverse = True) d_to_i = {dd:i for dd, i in d} n_child = [1]*n d_child = [0]*n ans = [] for dd, i in d: d_i = dd+2*n_child[i]-n if d_i in list(d_to_i.keys()): i_next = d_to_i[d_i] ans.append((i+1, i_next+1)) n_child[i_next] += n_child[i] d_child[i_next] += d_child[i] + n_child[i] if n_child[i_next] == n: break else: print((-1)) return d_min, i_min = d[-1] if d_min == d_child[i_min]: for a in ans: print((*a)) else: print((-1))
n = int(input()) d = [int(input()) for i in range(n)] if sum(d)%2 > 0: print((-1)) return d = sorted([(dd, i) for i, dd in enumerate(d)], reverse = True) d_to_i = {dd:i for dd, i in d} n_child = [1]*n d_child = [0]*n ans = [] for dd, i in d: d_i = dd+2*n_child[i]-n if d_i in list(d_to_i.keys()): i_next = d_to_i[d_i] ans.append((i+1, i_next+1)) n_child[i_next] += n_child[i] d_child[i_next] += d_child[i] + n_child[i] if n_child[i_next] == n: break else: print((-1)) return d_min, i_min = d[-1] if d_min == d_child[i_min]: for a in ans: print((*a)) else: print((-1))
train
APPS_structured
The auditorium of Stanford University is made up of L*R matrix (assume each coordinate has a chair). On the occasion of an event Chef was called as a chief guest. The auditorium was filled with males (M) and females (F), occupying one chair each. Our Chef is very curious guy, so he asks the gatekeeper some queries. The queries were as follows: Is there any K*K sub-matrix in the auditorium which contains all Males or Females. -----Input----- - The first line contains three space-separated integers L, R and Q describing the dimension of the auditorium and the number of questions Chef will ask. - Each of next L lines contains R characters (M or F). - Next Q lines contains K and a character (M or F). -----Output----- - For each query output "yes" (without quotes) if there exist any K*K sub-matrix in the auditorium which contains all Males (if he asks about Male) or Females (if he asks about Female), otherwise output "no" (without quotes). -----Constraints and Subtasks----- - 1 <= L, R, K <= 1000 - 1 <= Q <= 1e6 Subtask 1: 30 points - 1 <= L, R, Q <= 200 Subtask 2: 70 points - Original Contraints -----Example----- Input: 4 3 3 MMF MMM FFM FFM 2 F 3 M 1 M Output: yes no yes
read = lambda: list(map(int, input().split())) read_s = lambda: list(map(str, input().split())) def found (K, gender, L, R): ans = [] for i in range(K): ans.append(gender * K) for i in range(L - K + 1): for j in range(R - K + 1): Query_list = [] for qq in range(K): Query_list.append(grid[i + qq][j : j + K]) if Query_list == ans: return True return False L, R, Q = read() grid = [] for i in range(L): grid.append(str(input())) for i in range(Q): K, gender = input().split() K, gender = int(K), str(gender) print('yes' if found(K, gender, L, R) else 'no')
read = lambda: list(map(int, input().split())) read_s = lambda: list(map(str, input().split())) def found (K, gender, L, R): ans = [] for i in range(K): ans.append(gender * K) for i in range(L - K + 1): for j in range(R - K + 1): Query_list = [] for qq in range(K): Query_list.append(grid[i + qq][j : j + K]) if Query_list == ans: return True return False L, R, Q = read() grid = [] for i in range(L): grid.append(str(input())) for i in range(Q): K, gender = input().split() K, gender = int(K), str(gender) print('yes' if found(K, gender, L, R) else 'no')
train
APPS_structured
Consider the following well known rules: - A number is divisible by 3 if the sum of its digits is divisible by 3. Let's call '3' a "1-sum" prime - For 37, we take numbers in groups of threes from the right and check if the sum of these groups is divisible by 37. Example: 37 * 123456787 = 4567901119 => 4 + 567 + 901 + 119 = 1591 = 37 * 43. Let's call this a "3-sum" prime because we use groups of 3. - For 41, we take numbers in groups of fives from the right and check if the sum of these groups is divisible by 41. This is a "5-sum" prime. - Other examples: 239 is a "7-sum" prime (groups of 7), while 199 is a "99-sum" prime (groups of 99). Let's look at another type of prime: - For 11, we need to add all digits by alternating their signs from the right. Example: 11 * 123456 = 1358016 => 6-1+0-8+5-3+1 = 0, which is divible by 11. Let's call this a "1-altsum" prime - For 7, we need to group the digits into threes from the right and add all groups by alternating their signs. Example: 7 * 1234567891234 = 8641975238638 => 638 - 238 + 975 - 641 + 8 = 742/7 = 106. - 7 is a "3-altsum" prime because we use groups of threes. 47 is a "23-altsum" (groups of 23), while 73 is a "4-altsum" prime (groups of 4). You will be given a prime number `p` and your task is to find the smallest positive integer `n` such that `p’s` divisibility testing is `n-sum` or `n-altsum`. For example: ``` solve(3) = "1-sum" solve(7) = "3-altsum" ``` Primes will not exceed `50,000,000`. More examples in test cases. You can get some insight from [Fermat's little theorem](https://en.wikipedia.org/wiki/Fermat%27s_little_theorem). Good luck!
from math import floor, sqrt def solve(p): def powmod(x, n): res, cur = 1, x while n: if n & 1 == 1: res = (res * cur) % p cur = (cur * cur) % p n = n >> 1 return res def invert(x): return powmod(x, p - 2) BLOCK = 1000 base = 10 baby = dict() bcur = base % p for i in range(1, BLOCK): if bcur not in baby: baby[bcur] = i else: break bcur = (bcur * base) % p step = invert(powmod(base, BLOCK)) pcur = 1 for j in range(0, p, BLOCK): ans = [] def try_use(num, typ): if num in baby: totnum = j + baby[num] if totnum > 0: ans.append((totnum, typ)) if num == 1 and j > 0: ans.append((j, typ)) try_use(pcur, 'sum') try_use(((p - 1) * pcur) % p, 'altsum') if ans: return '%d-%s' % min(ans) pcur = (pcur * step) % p
from math import floor, sqrt def solve(p): def powmod(x, n): res, cur = 1, x while n: if n & 1 == 1: res = (res * cur) % p cur = (cur * cur) % p n = n >> 1 return res def invert(x): return powmod(x, p - 2) BLOCK = 1000 base = 10 baby = dict() bcur = base % p for i in range(1, BLOCK): if bcur not in baby: baby[bcur] = i else: break bcur = (bcur * base) % p step = invert(powmod(base, BLOCK)) pcur = 1 for j in range(0, p, BLOCK): ans = [] def try_use(num, typ): if num in baby: totnum = j + baby[num] if totnum > 0: ans.append((totnum, typ)) if num == 1 and j > 0: ans.append((j, typ)) try_use(pcur, 'sum') try_use(((p - 1) * pcur) % p, 'altsum') if ans: return '%d-%s' % min(ans) pcur = (pcur * step) % p
train
APPS_structured
# Pythagorean Triples A Pythagorean triplet is a set of three numbers a, b, and c where `a^2 + b^2 = c^2`. In this Kata, you will be tasked with finding the Pythagorean triplets whose product is equal to `n`, the given argument to the function `pythagorean_triplet`. ## Your task In this Kata, you will be tasked with finding the Pythagorean triplets whose product is equal to `n`, the given argument to the function, where `0 < n < 10000000` ## Examples One such triple is `3, 4, 5`. For this challenge, you would be given the value `60` as the argument to your function, and then it would return the Pythagorean triplet in an array `[3, 4, 5]` which is returned in increasing order. `3^2 + 4^2 = 5^2` since `9 + 16 = 25` and then their product (`3 * 4 * 5`) is `60`. More examples: | **argument** | **returns** | | ---------|---------| | 60 | [3, 4, 5] | | 780 | [5, 12, 13] | | 2040 | [8, 15, 17] |
def pythagorean_triplet(n): for z in range(1, int(n**0.5) + 1): # z is hypotenuse y = n / z # y is a * b if y.is_integer(): x = (z**2 + 2*y) ** 0.5 # (a + b) if x.is_integer(): for a in range(1, int(x)): b = x - a if a*b == y: return sorted([a,b,z])
def pythagorean_triplet(n): for z in range(1, int(n**0.5) + 1): # z is hypotenuse y = n / z # y is a * b if y.is_integer(): x = (z**2 + 2*y) ** 0.5 # (a + b) if x.is_integer(): for a in range(1, int(x)): b = x - a if a*b == y: return sorted([a,b,z])
train
APPS_structured
and Bengali as well. There are N$N$ cats (numbered 1$1$ through N$N$) and M$M$ rats (numbered 1$1$ through M$M$) on a line. Each cat and each rat wants to move from some point to some (possibly the same) point on this line. Naturally, the cats also want to eat the rats when they get a chance. Both the cats and the rats can only move with constant speed 1$1$. For each valid i$i$, the i$i$-th cat is initially sleeping at a point a_i$a_i$. At a time s_i$s_i$, this cat wakes up and starts moving to a final point b_i$b_i$ with constant velocity and without any detours (so it arrives at this point at the time e_i = s_i + |a_i-b_i|$e_i = s_i + |a_i-b_i|$). After it arrives at the point b_i$b_i$, it falls asleep again. For each valid i$i$, the i$i$-th rat is initially hiding at a point c_i$c_i$. At a time r_i$r_i$, this rat stops hiding and starts moving to a final point d_i$d_i$ in the same way as the cats ― with constant velocity and without any detours, arriving at the time q_i = r_i + |c_i-d_i|$q_i = r_i + |c_i-d_i|$ (if it does not get eaten). After it arrives at the point d_i$d_i$, it hides again. If a cat and a rat meet each other (they are located at the same point at the same time), the cat eats the rat, the rat disappears and cannot be eaten by any other cat. A sleeping cat cannot eat a rat and a hidden rat cannot be eaten ― formally, cat i$i$ can eat rat j$j$ only if they meet at a time t$t$ satisfying s_i \le t \le e_i$s_i \le t \le e_i$ and r_j \le t \le q_j$r_j \le t \le q_j$. Your task is to find out which rats get eaten by which cats. It is guaranteed that no two cats will meet a rat at the same time. -----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 two space-separated integers N$N$ and M$M$. - N$N$ lines follow. For each i$i$ (1 \le i \le N$1 \le i \le N$), the i$i$-th of these lines contains three space-separated integers a_i$a_i$, b_i$b_i$ and s_i$s_i$. - M$M$ more lines follow. For each i$i$ (1 \le i \le M$1 \le i \le M$), the i$i$-th of these lines contains three space-separated integers c_i$c_i$, d_i$d_i$ and r_i$r_i$. -----Output----- For each test case, print M$M$ lines. For each valid i$i$, the i$i$-th of these lines should contain a single integer ― the number of the cat that will eat the i$i$-th rat, or -1$-1$ if no cat will eat this rat. -----Constraints----- - 1 \le T \le 10$1 \le T \le 10$ - 0 \le N \le 1,000$0 \le N \le 1,000$ - 1 \le M \le 1,000$1 \le M \le 1,000$ - 1 \le a_i, b_i, s_i \le 10^9$1 \le a_i, b_i, s_i \le 10^9$ for each valid i$i$ - 1 \le c_i, d_i, r_i \le 10^9$1 \le c_i, d_i, r_i \le 10^9$ for each valid i$i$ - all initial and final positions of all cats and rats are pairwise distinct -----Example Input----- 2 8 7 2 5 1 1 4 1 9 14 10 20 7 9 102 99 1 199 202 1 302 299 3 399 402 3 6 3 1 10 15 10 100 101 1 201 200 1 300 301 5 401 400 5 1000 1010 1020 8 8 2 8 2 12 18 2 22 28 4 32 38 4 48 42 2 58 52 3 68 62 1 78 72 3 3 6 3 13 19 3 21 25 3 31 39 3 46 43 4 59 53 2 65 61 4 79 71 2 -----Example Output----- 1 4 5 6 7 8 -1 1 2 3 4 5 6 7 8
# cook your dish here class Animal: def __init__(self): start, end, starting_time = map(int, input().split()) self.ending_time = starting_time + abs(start - end) self.velocity = 1 if end >= start else -1 self.eaten_by = -1, 10 ** 10 self.start = start self.end = end self.starting_time = starting_time def will_collide(self, z): if self.starting_time > z.ending_time or self.ending_time < z.starting_time: return False if self.velocity == z.velocity: if self.starting_time > z.starting_time: self, z = z, self if z.start == self.start + self.velocity * (z.starting_time - self.starting_time): return z.starting_time else: return False if self.velocity == -1: self, z = z, self t = ( z.start - self.start + z.starting_time + self.starting_time ) / 2 return t if self.starting_time <= t <= self.ending_time and z.starting_time <= t <= z.ending_time else False def main(): for _ in range(int(input())): no_cats, no_rats = map(int, input().split()) Cats = [Animal() for i in range(no_cats)] for i in range(no_rats): rat = Animal() for j in range(no_cats): time = rat.will_collide(Cats[j]) if time: # print(time) if time < rat.eaten_by[1]: rat.eaten_by = j + 1, time print(rat.eaten_by[0]) main()
# cook your dish here class Animal: def __init__(self): start, end, starting_time = map(int, input().split()) self.ending_time = starting_time + abs(start - end) self.velocity = 1 if end >= start else -1 self.eaten_by = -1, 10 ** 10 self.start = start self.end = end self.starting_time = starting_time def will_collide(self, z): if self.starting_time > z.ending_time or self.ending_time < z.starting_time: return False if self.velocity == z.velocity: if self.starting_time > z.starting_time: self, z = z, self if z.start == self.start + self.velocity * (z.starting_time - self.starting_time): return z.starting_time else: return False if self.velocity == -1: self, z = z, self t = ( z.start - self.start + z.starting_time + self.starting_time ) / 2 return t if self.starting_time <= t <= self.ending_time and z.starting_time <= t <= z.ending_time else False def main(): for _ in range(int(input())): no_cats, no_rats = map(int, input().split()) Cats = [Animal() for i in range(no_cats)] for i in range(no_rats): rat = Animal() for j in range(no_cats): time = rat.will_collide(Cats[j]) if time: # print(time) if time < rat.eaten_by[1]: rat.eaten_by = j + 1, time print(rat.eaten_by[0]) main()
train
APPS_structured
Well met with Fibonacci bigger brother, AKA Tribonacci. As the name may already reveal, it works basically like a Fibonacci, but summing the last 3 (instead of 2) numbers of the sequence to generate the next. And, worse part of it, regrettably I won't get to hear non-native Italian speakers trying to pronounce it :( So, if we are to start our Tribonacci sequence with `[1, 1, 1]` as a starting input (AKA *signature*), we have this sequence: ``` [1, 1 ,1, 3, 5, 9, 17, 31, ...] ``` But what if we started with `[0, 0, 1]` as a signature? As starting with `[0, 1]` instead of `[1, 1]` basically *shifts* the common Fibonacci sequence by once place, you may be tempted to think that we would get the same sequence shifted by 2 places, but that is not the case and we would get: ``` [0, 0, 1, 1, 2, 4, 7, 13, 24, ...] ``` Well, you may have guessed it by now, but to be clear: you need to create a fibonacci function that given a **signature** array/list, returns **the first n elements - signature included** of the so seeded sequence. Signature will always contain 3 numbers; n will always be a non-negative number; if `n == 0`, then return an empty array (except in C return NULL) and be ready for anything else which is not clearly specified ;) If you enjoyed this kata more advanced and generalized version of it can be found in the Xbonacci kata *[Personal thanks to Professor Jim Fowler on Coursera for his awesome classes that I really recommend to any math enthusiast and for showing me this mathematical curiosity too with his usual contagious passion :)]*
def tribonacci(signature,n): return signature[:n] if n<=len(signature) else tribonacci(signature + [sum(signature[-3:])],n)
def tribonacci(signature,n): return signature[:n] if n<=len(signature) else tribonacci(signature + [sum(signature[-3:])],n)
train
APPS_structured
Alice and Bob take turns playing a game, with Alice starting first. Initially, there are n stones in a pile.  On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile. Also, if a player cannot make a move, he/she loses the game. Given a positive integer n. Return True if and only if Alice wins the game otherwise return False, assuming both players play optimally. Example 1: Input: n = 1 Output: true Explanation: Alice can remove 1 stone winning the game because Bob doesn't have any moves. Example 2: Input: n = 2 Output: false Explanation: Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0). Example 3: Input: n = 4 Output: true Explanation: n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0). Example 4: Input: n = 7 Output: false Explanation: Alice can't win the game if Bob plays optimally. If Alice starts removing 4 stones, Bob will remove 1 stone then Alice should remove only 1 stone and finally Bob removes the last one (7 -> 3 -> 2 -> 1 -> 0). If Alice starts removing 1 stone, Bob will remove 4 stones then Alice only can remove 1 stone and finally Bob removes the last one (7 -> 6 -> 2 -> 1 -> 0). Example 5: Input: n = 17 Output: false Explanation: Alice can't win the game if Bob plays optimally. Constraints: 1 <= n <= 10^5
import math class Solution: squares=[0] dp=[False] def winnerSquareGame(self, n: int) -> bool: sqt=int(math.sqrt(n)) for i in range(len(self.squares),sqt+1): self.squares.append(i*i) if n+1<=len(self.dp): return self.dp[n] old_len=len(self.dp) for i in range(old_len,n+1): self.dp.append(False) for i in range(old_len,n+1): flag=0 # print(\"in loop i\") for j in range(1,int(math.sqrt(i))+1): # print(\"i and j are\",i,j) if not self.dp[i-self.squares[j]]: self.dp[i]=True flag=1 break if flag==0: self.dp[i]=False # print(dp) return self.dp[n]
import math class Solution: squares=[0] dp=[False] def winnerSquareGame(self, n: int) -> bool: sqt=int(math.sqrt(n)) for i in range(len(self.squares),sqt+1): self.squares.append(i*i) if n+1<=len(self.dp): return self.dp[n] old_len=len(self.dp) for i in range(old_len,n+1): self.dp.append(False) for i in range(old_len,n+1): flag=0 # print(\"in loop i\") for j in range(1,int(math.sqrt(i))+1): # print(\"i and j are\",i,j) if not self.dp[i-self.squares[j]]: self.dp[i]=True flag=1 break if flag==0: self.dp[i]=False # print(dp) return self.dp[n]
train
APPS_structured
Chef loves to play with arrays by himself. Today, he has an array A consisting of N distinct integers. He wants to perform the following operation on his array A. - Select a pair of adjacent integers and remove the larger one of these two. This decreases the array size by 1. Cost of this operation will be equal to the smaller of them. Find out minimum sum of costs of operations needed to convert the array into a single element. -----Input----- First line of input contains a single integer T denoting the number of test cases. First line of each test case starts with an integer N denoting the size of the array A. Next line of input contains N space separated integers, where the ith integer denotes the value Ai. -----Output----- For each test case, print the minimum cost required for the transformation. -----Constraints----- - 1 ≤ T ≤ 10 - 2 ≤ N ≤ 50000 - 1 ≤ Ai ≤ 105 -----Subtasks----- - Subtask 1 : 2 ≤ N ≤ 15 : 35 pts - Subtask 2 : 2 ≤ N ≤ 100 : 25 pts - Subtask 3 : 2 ≤ N ≤ 50000 : 40 pts -----Example----- Input 2 2 3 4 3 4 2 5 Output 3 4 -----Explanation-----Test 1 : Chef will make only 1 move: pick up both the elements (that is, 3 and 4), remove the larger one (4), incurring a cost equal to the smaller one (3).
t=int(input()) for i in range(t): n=int(input()) a=list(map(int,input().split())) a.sort() s=0 while(len(a)>1): a.remove(a[1]) s=s+a[0] print(s)
t=int(input()) for i in range(t): n=int(input()) a=list(map(int,input().split())) a.sort() s=0 while(len(a)>1): a.remove(a[1]) s=s+a[0] print(s)
train
APPS_structured
We need a function ```prime_bef_aft()``` that gives the largest prime below a certain given value ```n```, ```befPrime or bef_prime``` (depending on the language), and the smallest prime larger than this value, ```aftPrime/aft_prime``` (depending on the language). The result should be output in a list like the following: ```python prime_bef_aft(n) == [befPrime, aftPrime] ``` If n is a prime number it will give two primes, n will not be included in the result. Let's see some cases: ```python prime_bef_aft(100) == [97, 101] prime_bef_aft(97) == [89, 101] prime_bef_aft(101) == [97, 103] ``` Range for the random tests: ```1000 <= n <= 200000``` (The extreme and special case n = 2 will not be considered for the tests. Thanks Blind4Basics) Happy coding!!
def prime_bef_aft(num): res = [] for i in range(num, 0, -1): if len([x for x in range(1, i+1) if i % x == 0 and i != num]) == 2: res.append(i) break i = num while len(res) != 2: i += 1 if len([x for x in range(1, i+1) if i % x == 0 and i != num]) == 2: res.append(i) break return res
def prime_bef_aft(num): res = [] for i in range(num, 0, -1): if len([x for x in range(1, i+1) if i % x == 0 and i != num]) == 2: res.append(i) break i = num while len(res) != 2: i += 1 if len([x for x in range(1, i+1) if i % x == 0 and i != num]) == 2: res.append(i) break return res
train
APPS_structured
# Introduction The ragbaby cipher is a substitution cipher that encodes/decodes a text using a keyed alphabet and their position in the plaintext word they are a part of. To encrypt the text `This is an example.` with the key `cipher`, first construct a keyed alphabet: ``` c i p h e r a b d f g j k l m n o q s t u v w x y z ``` Then, number the letters in the text as follows: ``` T h i s i s a n e x a m p l e . 1 2 3 4 1 2 1 2 1 2 3 4 5 6 7 ``` To obtain the encoded text, replace each character of the word with the letter in the keyed alphabet the corresponding number of places to the right of it (wrapping if necessary). Non-alphabetic characters are preserved to mark word boundaries. Our ciphertext is then `Urew pu bq rzfsbtj.` # Task Wirate functions `encode` and `decode` which accept 2 parameters: - `text` - string - a text to encode/decode - `key` - string - a key # Notes - handle lower and upper case in `text` string - `key` consists of only lowercase characters
from string import ascii_lowercase as AL import re def f(op): def g(s, key): a = "".join(dict.fromkeys(key + AL)) d = {x: i for i, x in enumerate(a)} def f(s): s, r = s[0], [] for i, x in enumerate(s, 1): y = a[(op(d[x.lower()], i)) % len(a)] if x.isupper(): y = y.upper() r.append(y) return "".join(r) return re.sub(r"\w+", f, s) return g encode = f(int.__add__) decode = f(int.__sub__)
from string import ascii_lowercase as AL import re def f(op): def g(s, key): a = "".join(dict.fromkeys(key + AL)) d = {x: i for i, x in enumerate(a)} def f(s): s, r = s[0], [] for i, x in enumerate(s, 1): y = a[(op(d[x.lower()], i)) % len(a)] if x.isupper(): y = y.upper() r.append(y) return "".join(r) return re.sub(r"\w+", f, s) return g encode = f(int.__add__) decode = f(int.__sub__)
train
APPS_structured
I will give you two strings. I want you to transform stringOne into stringTwo one letter at a time. Example:
from collections import OrderedDict def mutate_my_strings(s1,s2): return '\n'.join(OrderedDict.fromkeys((s2[:i] + s1[i:] for i in range(len(s1) + 1)))) + '\n'
from collections import OrderedDict def mutate_my_strings(s1,s2): return '\n'.join(OrderedDict.fromkeys((s2[:i] + s1[i:] for i in range(len(s1) + 1)))) + '\n'
train
APPS_structured
Write a function that takes in a binary string and returns the equivalent decoded text (the text is ASCII encoded). Each 8 bits on the binary string represent 1 character on the ASCII table. The input string will always be a valid binary string. Characters can be in the range from "00000000" to "11111111" (inclusive) Note: In the case of an empty binary string your function should return an empty string.
binary_to_string = lambda b: "".join([[chr(l) for l in range(0, 127)][m] for m in [int(b[n: n+8],2) for n in range(0, len(b), 8)]])
binary_to_string = lambda b: "".join([[chr(l) for l in range(0, 127)][m] for m in [int(b[n: n+8],2) for n in range(0, len(b), 8)]])
train
APPS_structured
We need to write some code to return the original price of a product, the return type must be of type decimal and the number must be rounded to two decimal places. We will be given the sale price (discounted price), and the sale percentage, our job is to figure out the original price. ### For example: Given an item at $75 sale price after applying a 25% discount, the function should return the original price of that item before applying the sale percentage, which is ($100.00) of course, rounded to two decimal places. DiscoverOriginalPrice(75, 25) => 100.00M where 75 is the sale price (discounted price), 25 is the sale percentage and 100 is the original price
def discover_original_price(discounted_price, sale_percentage): #your code here return round(discounted_price / (1 - (sale_percentage / 100.00)), 2)
def discover_original_price(discounted_price, sale_percentage): #your code here return round(discounted_price / (1 - (sale_percentage / 100.00)), 2)
train
APPS_structured
### Happy Holidays fellow Code Warriors! Now, Dasher! Now, Dancer! Now, Prancer, and Vixen! On, Comet! On, Cupid! On, Donder and Blitzen! That's the order Santa wanted his reindeer...right? What do you mean he wants them in order by their last names!? Looks like we need your help Code Warrior! ### Sort Santa's Reindeer Write a function that accepts a sequence of Reindeer names, and returns a sequence with the Reindeer names sorted by their last names. ### Notes: * It's guaranteed that each string is composed of two words * In case of two identical last names, keep the original order ### Examples For this input: ``` [ "Dasher Tonoyan", "Dancer Moore", "Prancer Chua", "Vixen Hall", "Comet Karavani", "Cupid Foroutan", "Donder Jonker", "Blitzen Claus" ] ``` You should return this output: ``` [ "Prancer Chua", "Blitzen Claus", "Cupid Foroutan", "Vixen Hall", "Donder Jonker", "Comet Karavani", "Dancer Moore", "Dasher Tonoyan", ] ```
def sort_reindeer(reindeer_names): reindeer_names.sort(key = lambda x: x.split()[-1]) return reindeer_names
def sort_reindeer(reindeer_names): reindeer_names.sort(key = lambda x: x.split()[-1]) return reindeer_names
train
APPS_structured
The Fair Nut is going to travel to the Tree Country, in which there are $n$ cities. Most of the land of this country is covered by forest. Furthermore, the local road system forms a tree (connected graph without cycles). Nut wants to rent a car in the city $u$ and go by a simple path to city $v$. He hasn't determined the path, so it's time to do it. Note that chosen path can consist of only one vertex. A filling station is located in every city. Because of strange law, Nut can buy only $w_i$ liters of gasoline in the $i$-th city. We can assume, that he has infinite money. Each road has a length, and as soon as Nut drives through this road, the amount of gasoline decreases by length. Of course, Nut can't choose a path, which consists of roads, where he runs out of gasoline. He can buy gasoline in every visited city, even in the first and the last. He also wants to find the maximum amount of gasoline that he can have at the end of the path. Help him: count it. -----Input----- The first line contains a single integer $n$ ($1 \leq n \leq 3 \cdot 10^5$) — the number of cities. The second line contains $n$ integers $w_1, w_2, \ldots, w_n$ ($0 \leq w_{i} \leq 10^9$) — the maximum amounts of liters of gasoline that Nut can buy in cities. Each of the next $n - 1$ lines describes road and contains three integers $u$, $v$, $c$ ($1 \leq u, v \leq n$, $1 \leq c \leq 10^9$, $u \ne v$), where $u$ and $v$ — cities that are connected by this road and $c$ — its length. It is guaranteed that graph of road connectivity is a tree. -----Output----- Print one number — the maximum amount of gasoline that he can have at the end of the path. -----Examples----- Input 3 1 3 3 1 2 2 1 3 2 Output 3 Input 5 6 3 2 5 0 1 2 10 2 3 3 2 4 1 1 5 1 Output 7 -----Note----- The optimal way in the first example is $2 \to 1 \to 3$. [Image] The optimal way in the second example is $2 \to 4$. [Image]
import sys input = sys.stdin.readline n = int(input()) a = list(map(int, input().split())) adj = [[] for i in range(n)] for i in range(n-1): u, v, w = map(int, input().split()) u -= 1 v -= 1 adj[u].append((v, w)) adj[v].append((u, w)) best = [0] * n ans = 0 def dfs(u): stack = list() visit = [False] * n stack.append((u, -1)) while stack: u, par = stack[-1] if not visit[u]: visit[u] = True for v, w in adj[u]: if v != par: stack.append((v, u)) else: cand = [] for v, w in adj[u]: if v != par: cand.append(best[v] + a[v] - w) cand.sort(reverse=True) cur = a[u] for i in range(2): if i < len(cand) and cand[i] > 0: cur += cand[i] nonlocal ans ans = max(ans, cur) best[u] = cand[0] if len(cand) > 0 and cand[0] > 0 else 0 stack.pop() dfs(0) print(ans)
import sys input = sys.stdin.readline n = int(input()) a = list(map(int, input().split())) adj = [[] for i in range(n)] for i in range(n-1): u, v, w = map(int, input().split()) u -= 1 v -= 1 adj[u].append((v, w)) adj[v].append((u, w)) best = [0] * n ans = 0 def dfs(u): stack = list() visit = [False] * n stack.append((u, -1)) while stack: u, par = stack[-1] if not visit[u]: visit[u] = True for v, w in adj[u]: if v != par: stack.append((v, u)) else: cand = [] for v, w in adj[u]: if v != par: cand.append(best[v] + a[v] - w) cand.sort(reverse=True) cur = a[u] for i in range(2): if i < len(cand) and cand[i] > 0: cur += cand[i] nonlocal ans ans = max(ans, cur) best[u] = cand[0] if len(cand) > 0 and cand[0] > 0 else 0 stack.pop() dfs(0) print(ans)
train
APPS_structured
So the Chef has become health conscious and is now lifting weights at the gym. But its his first time so the trainer gives him a simple job to do. He has been given a weight lifting rod and N heavy weights, each weighing 20, 21, .... , 2n-1. He has to stick each of the "N" weights on the rod, one after another, in such a way that the right side is never heavier than the left side. At each step he chooses one of the weights that has not yet been fixed on the rod, and fix it on either the left side of the rod or the right, until all of the weights have been placed. Now help the chef and find out, in how many ways the chef can accomplish this? -----Input----- First line of input contains an integer T, the number of test cases. Then T test cases follow. Each line of test case contains one integer, N denoting the number of weights -----Output----- The output contains T lines, each containing an integer denoting all possible combinations -----Example----- Input: 3 2 5 18 Output: 3 945 221643095476699771875
def D(n): return n and (2*n-1)*D(n-1) or 1 def N(n): return n and (4*n*n-8*n+3)*N(n-2)+7*D(n-2) or 1 n=eval(input()) for i in range(n): n = eval(input()) print(D(n))
def D(n): return n and (2*n-1)*D(n-1) or 1 def N(n): return n and (4*n*n-8*n+3)*N(n-2)+7*D(n-2) or 1 n=eval(input()) for i in range(n): n = eval(input()) print(D(n))
train
APPS_structured
Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get. For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4). Note: You may assume that n is not less than 2 and not larger than 58. Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
class Solution: def integerBreak(self, n): """ :type n: int :rtype: int """ if n==2:return 1 if n==3:return 2 res=1 while n>4: n=n-3 res*=3 return res*n
class Solution: def integerBreak(self, n): """ :type n: int :rtype: int """ if n==2:return 1 if n==3:return 2 res=1 while n>4: n=n-3 res*=3 return res*n
train
APPS_structured
-----Problem Statement----- Levy's conjecture, named after Hyman Levy, states that all odd integers greater than 5 can be represented as the sum of an odd prime number and an even semiprime. To put it algebraically, 2n + 1 = p + 2q always has a solution in primes p and q (not necessary to be distinct) for n > 2. (Source: Wikipedia) In this problem, given a positive integer N (not necessary to be odd integer greater than 5). Your task is to calculate how many distinct ordered pairs (p, q) such that N = p + 2q, where p and q are primes. -----Input----- The first line of input contains an integer T, denoting the number of test cases. Then T test cases follow. Each test case consists of exactly one line containing an integer N. -----Constraints----- - 1 ≤ T ≤ 100000 (105) - 1 ≤ N ≤ 10000 (104) -----Output----- For each test case, output the number of ordered pairs (p, q) of primes such that N = p + 2q. -----Example----- Input: 3 2 7 11 Output: 0 1 2 -----Explanation----- Case #1: There are no ordered pairs (p, q) such that p + 2q = 2. Case #2: There is only one ordered pair (p, q) = (3, 2) such that p + 2q = 7. Case #3: There are two ordered pairs (p, q) = (7, 2), (5, 3) such that p + 2q = 11.
import math MAX = 10001 PRIME=[] A=[1 for i in range(MAX)] A[0] = 0 A[1] = 0 B=[0 for i in range(MAX)] for i in range(2,int(math.sqrt(MAX))+1): if A[i] is 1: for j in range(i*i,MAX,i): A[j] = 0 for i in range(MAX): if A[i] is 1: PRIME.append(i) for p in PRIME: for q in PRIME: if p+(2*q)>=MAX: break B[p+(2*q)]+=1 for _ in range(int(input())): n=int(input()) print(B[n])
import math MAX = 10001 PRIME=[] A=[1 for i in range(MAX)] A[0] = 0 A[1] = 0 B=[0 for i in range(MAX)] for i in range(2,int(math.sqrt(MAX))+1): if A[i] is 1: for j in range(i*i,MAX,i): A[j] = 0 for i in range(MAX): if A[i] is 1: PRIME.append(i) for p in PRIME: for q in PRIME: if p+(2*q)>=MAX: break B[p+(2*q)]+=1 for _ in range(int(input())): n=int(input()) print(B[n])
train
APPS_structured
There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, then A is an indirect friend of C. And we defined a friend circle is a group of students who are direct or indirect friends. Given a N*N matrix M representing the friend relationship between students in the class. If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not. And you have to output the total number of friend circles among all the students. Example 1: Input: [[1,1,0], [1,1,0], [0,0,1]] Output: 2 Explanation:The 0th and 1st students are direct friends, so they are in a friend circle. The 2nd student himself is in a friend circle. So return 2. Example 2: Input: [[1,1,0], [1,1,1], [0,1,1]] Output: 1 Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends, so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1. Note: N is in range [1,200]. M[i][i] = 1 for all students. If M[i][j] = 1, then M[j][i] = 1.
class Solution: def dfs(self, M, cur): for i in range(len(M)): if flag[i]: continue if M[cur][i]: flag[i] = True self.dfs(M, i) def findCircleNum(self, M): """ :type M: List[List[int]] :rtype: int """ nonlocal flag flag = [False] * len(M) circle = 0 for i in range(len(M)): if flag[i]: continue flag[i] = True circle += 1 self.dfs(M, i) return circle
class Solution: def dfs(self, M, cur): for i in range(len(M)): if flag[i]: continue if M[cur][i]: flag[i] = True self.dfs(M, i) def findCircleNum(self, M): """ :type M: List[List[int]] :rtype: int """ nonlocal flag flag = [False] * len(M) circle = 0 for i in range(len(M)): if flag[i]: continue flag[i] = True circle += 1 self.dfs(M, i) return circle
train
APPS_structured
Let f(x) be the number of zeroes at the end of x!. (Recall that x! = 1 * 2 * 3 * ... * x, and by convention, 0! = 1.) For example, f(3) = 0 because 3! = 6 has no zeroes at the end, while f(11) = 2 because 11! = 39916800 has 2 zeroes at the end. Given K, find how many non-negative integers x have the property that f(x) = K. Example 1: Input: K = 0 Output: 5 Explanation: 0!, 1!, 2!, 3!, and 4! end with K = 0 zeroes. Example 2: Input: K = 5 Output: 0 Explanation: There is no x such that x! ends in K = 5 zeroes. Note: K will be an integer in the range [0, 10^9].
class Solution: def canTransform(self, start, end): """ :type start: str :type end: str :rtype: bool """ if len(start)!=len(end) or start.replace('X','')!=end.replace('X',''): return False l,ll,r,rr=0,0,0,0 for i in range(len(start)): if start[i]=='L': l+=1 elif start[i]=='R': r+=1 if end[i]=='L': ll+=1 elif end[i]=='R': rr+=1 if l>ll or r<rr: return False return True
class Solution: def canTransform(self, start, end): """ :type start: str :type end: str :rtype: bool """ if len(start)!=len(end) or start.replace('X','')!=end.replace('X',''): return False l,ll,r,rr=0,0,0,0 for i in range(len(start)): if start[i]=='L': l+=1 elif start[i]=='R': r+=1 if end[i]=='L': ll+=1 elif end[i]=='R': rr+=1 if l>ll or r<rr: return False return True
train
APPS_structured
Count the number of divisors of a positive integer `n`. Random tests go up to `n = 500000`. ## Examples ```python divisors(4) == 3 # 1, 2, 4 divisors(5) == 2 # 1, 5 divisors(12) == 6 # 1, 2, 3, 4, 6, 12 divisors(30) == 8 # 1, 2, 3, 5, 6, 10, 15, 30 ```
def divisors(n): z = 0 i = 1 while i <= n: if n % i == 0: z+=1 i+=1 return z
def divisors(n): z = 0 i = 1 while i <= n: if n % i == 0: z+=1 i+=1 return z
train
APPS_structured
Your task in this kata is to implement a function that calculates the sum of the integers inside a string. For example, in the string "The30quick20brown10f0x1203jumps914ov3r1349the102l4zy dog", the sum of the integers is 3635. *Note: only positive integers will be tested.*
import re def sum_of_integers_in_string(s): return sum(int(i) for i in re.findall('\d+', s))
import re def sum_of_integers_in_string(s): return sum(int(i) for i in re.findall('\d+', s))
train
APPS_structured
*** Nova polynomial multiply*** This kata is from a series on polynomial handling. ( [#1](http://www.codewars.com/kata/nova-polynomial-1-add-1) [#2](http://www.codewars.com/kata/570eb07e127ad107270005fe) [#3](http://www.codewars.com/kata/5714041e8807940ff3001140 ) [#4](http://www.codewars.com/kata/571a2e2df24bdfd4e20001f5)) Consider a polynomial in a list where each element in the list element corresponds to the factors. The factor order is the position in the list. The first element is the zero order factor (the constant). p = [a0, a1, a2, a3] signifies the polynomial a0 + a1x + a2x^2 + a3*x^3 In this kata multiply two polynomials: ```python poly_multiply([1, 2], [1] ) = [1, 2] poly_multiply([2, 4], [4, 5] ) = [8, 26, 20] ``` The first kata of this series is preloaded in the code and can be used: [poly_add](http://www.codewars.com/kata/nova-polynomial-1-add-1)
def poly_multiply(p1,p2): r,s={},[] for i in range(len(p1)): for j in range(len(p2)): r[i+j]= r[i+j]+p1[i]*p2[j] if i+j in r else p1[i]*p2[j] for i in r: s.append(r[i]) return s
def poly_multiply(p1,p2): r,s={},[] for i in range(len(p1)): for j in range(len(p2)): r[i+j]= r[i+j]+p1[i]*p2[j] if i+j in r else p1[i]*p2[j] for i in r: s.append(r[i]) return s
train
APPS_structured
You might know some pretty large perfect squares. But what about the NEXT one? Complete the `findNextSquare` method that finds the next integral perfect square after the one passed as a parameter. Recall that an integral perfect square is an integer n such that sqrt(n) is also an integer. If the parameter is itself not a perfect square then `-1` should be returned. You may assume the parameter is positive. **Examples:** ``` findNextSquare(121) --> returns 144 findNextSquare(625) --> returns 676 findNextSquare(114) --> returns -1 since 114 is not a perfect ```
def find_next_square(sq): x = sq**0.5 return -1 if x % 1 else (x+1)**2
def find_next_square(sq): x = sq**0.5 return -1 if x % 1 else (x+1)**2
train
APPS_structured
My little sister came back home from school with the following task: given a squared sheet of paper she has to cut it in pieces which, when assembled, give squares the sides of which form an increasing sequence of numbers. At the beginning it was lot of fun but little by little we were tired of seeing the pile of torn paper. So we decided to write a program that could help us and protects trees. ## Task Given a positive integral number n, return a **strictly increasing** sequence (list/array/string depending on the language) of numbers, so that the sum of the squares is equal to n². If there are multiple solutions (and there will be), return as far as possible the result with the largest possible values: ## Examples `decompose(11)` must return `[1,2,4,10]`. Note that there are actually two ways to decompose 11², 11² = 121 = 1 + 4 + 16 + 100 = 1² + 2² + 4² + 10² but don't return `[2,6,9]`, since 9 is smaller than 10. For `decompose(50)` don't return `[1, 1, 4, 9, 49]` but `[1, 3, 5, 8, 49]` since `[1, 1, 4, 9, 49]` doesn't form a strictly increasing sequence. ## Note Neither `[n]` nor `[1,1,1,…,1]` are valid solutions. If no valid solution exists, return `nil`, `null`, `Nothing`, `None` (depending on the language) or `"[]"` (C) ,`{}` (C++), `[]` (Swift, Go). The function "decompose" will take a positive integer n and return the decomposition of N = n² as: - [x1 ... xk] or - "x1 ... xk" or - Just [x1 ... xk] or - Some [x1 ... xk] or - {x1 ... xk} or - "[x1,x2, ... ,xk]" depending on the language (see "Sample tests") # Note for Bash ``` decompose 50 returns "1,3,5,8,49" decompose 4 returns "Nothing" ``` # Hint Very often `xk` will be `n-1`.
def decompose(n, a=None): if a == None: a = n*n if a == 0: return [] for m in range(min(n-1, int(a ** .5)), 0, -1): sub = decompose(m, a - m*m) if sub != None: return sub + [m]
def decompose(n, a=None): if a == None: a = n*n if a == 0: return [] for m in range(min(n-1, int(a ** .5)), 0, -1): sub = decompose(m, a - m*m) if sub != None: return sub + [m]
train
APPS_structured
Two fishing vessels are sailing the open ocean, both on a joint ops fishing mission. On a high stakes, high reward expidition - the ships have adopted the strategy of hanging a net between the two ships. The net is **40 miles long**. Once the straight-line distance between the ships is greater than 40 miles, the net will tear, and their valuable sea harvest will be lost! We need to know how long it will take for this to happen. Given the bearing of each ship, find the time **in minutes** at which the straight-line distance between the two ships reaches **40 miles**. Both ships travel at **90 miles per hour**. At time 0, assume the ships have the same location. Bearings are defined as **degrees from north, counting clockwise**. These will be passed to your function as integers between **0 and 359** degrees. Round your result to **2 decmal places**. If the net never breaks, return float('inf') Happy sailing!
from math import cos, hypot, radians, sin def find_time_to_break(a, b): a, b = radians(a), radians(b) d = hypot(cos(a) - cos(b), sin(a) - sin(b)) return 40 / (90 / 60) / d if d else float('inf')
from math import cos, hypot, radians, sin def find_time_to_break(a, b): a, b = radians(a), radians(b) d = hypot(cos(a) - cos(b), sin(a) - sin(b)) return 40 / (90 / 60) / d if d else float('inf')
train
APPS_structured
Taxis of Kharagpur are famous for making sharp turns. You are given the coordinates where a particular taxi was on a 2-D planes at N different moments: (x1, y1), (x2, y2), ..., (xN, yN). In between these coordinates, the taxi moves on a straight line. A turn at the i-th (2 ≤ i ≤ N-1) coordinate is said to be a sharp turn if the angle by which it turns at Point B = (xi, yi) when going from coordinates A = (xi-1, yi-1) to C = (xi+1, yi+1) via (xi, yi) is greater than 45 degrees. ie. suppose you extend the line segment AB further till a point D, then the angle DBC would be greater than 45 degrees. You have to identify whether the taxi made a sharp turn somewhere or not (Please look at Output section for details). If it made a sharp turn, also identify whether it is possible to change the coordinates at one of the N moments to make sure that the taxi doesn't make any sharp turn. Note that all the N pairs of coordinates (including the new coordinates) should be integers and distinct and should have their x and y coordinates at least 0 and at most 50. -----Input----- - The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. - The first line of each test case contains a single integer N denoting the number of moments at which you are given the information of the taxi's coordinates. - Each of the next N lines contains two space-separated integers xi and yi denoting the x and y coordinates of the taxi at i-th moment. -----Output----- - For each test case, print a single line containing two space-separated strings, either of which can be a "yes" or "no" (without quotes). If there was no sharp turn, the first string should be "yes", and if there was a sharp turn, the first string should be "no". For the second string, you should tell whether it is possible to modify at most one coordinate in such a way that taxi doesn't make a sharp turn. Note that if the first string is "yes", then the second string would always be "yes". -----Constraints----- - 1 ≤ T ≤ 50 - 3 ≤ N ≤ 50 - 0 ≤ xi, yi ≤ 50 - It's guaranteed that all (xi, yi) pairs are distinct. -----Example----- Input 5 3 0 0 1 1 2 1 3 0 0 1 0 6 1 3 0 0 1 0 1 1 4 0 0 1 0 1 1 6 1 6 0 0 1 0 1 1 2 1 2 2 3 2 Output yes yes yes yes no yes no yes no no -----Explanation----- Example 1. You can see that taxi is never making a sharp turn. Example 3 You can see that taxi is making a sharp turn of 90 degrees, an angle greater than 45'. However, you can change the coordinates of the third points to (2, 1) to ensure that the angle remains <= 45'.
import math import copy try: import psyco psyco.full() except ImportError: pass def isSharp(ang): return ang > math.pi/4 + 0.00001 def unitVector(p2, p1): d0 = p2[0] - p1[0] d1 = p2[1] - p1[1] d = math.sqrt(d0*d0 + d1*d1) if d != 0: return [d0/d, d1/d] return [0, 0] def compVectors(P): V = [] for i in range(1,len(P)): v = unitVector(P[i], P[i-1]) if v[0] == 0 and v[1] == 0: return None V.append(v) return V def angle(v2, v1): d = v2[0]*v1[0] + v2[1]*v1[1] if d > 1: d = 1 if d < -1: d = -1 return math.acos(d) def compAngles(V): A = [] for i in range(len(V)-1): A.append(angle(V[i+1], V[i])) return A def updateAngles(i, P, V, A): if i-1 >= 0: V[i-1] = unitVector(P[i], P[i-1]) if i+1 < len(P): V[i] = unitVector(P[i+1], P[i]) if i-2 >= 0: A[i-2] = angle(V[i-1], V[i-2]) if i-1 >= 0 and i+1 < len(P): A[i-1] = angle(V[i], V[i-1]) if i+2 < len(P): A[i] = angle(V[i+1], V[i]) def checkMoves(check, P, V, A, filled): for i in check: if i < 0 or i >= len(P): break x, y = P[i] for j in range(51): for k in range(51): P[i][0] = j P[i][1] = k if str(P[i]) in filled: continue updateAngles(i, P, V, A) fixed = True if i-2 >= 0: if isSharp(A[i-2]): fixed = False if i-1 >= 0 and i-1 < len(A): if isSharp(A[i-1]): fixed = False if i < len(A): if isSharp(A[i]): fixed = False if fixed: return True P[i] = [x, y] updateAngles(i, P, V, A) return False def canFix(first, last, P, V, A, filled): d = last - first if d > 2: return False if d == 2: check = [first+2] if d == 1: check = [first+1, first+2] if d == 0: check = [first, first+1, first+2] if checkMoves(check, P, V, A, filled): return True return False T=int(input()) for i in range(T): N=int(input()) P=[] V=[] filled={} for i in range(N): P.append(list(map(int,input().split()))) filled[str(P[i])] = 1 V = compVectors(P) A = compAngles(V) blunt = True first = -1 last = -1 for i in range(len(A)): if isSharp(A[i]): blunt = False last = i if first < 0: first = i if blunt: print('yes yes') else: if canFix(first, last, P, V, A, filled): print('no yes') else: print('no no')
import math import copy try: import psyco psyco.full() except ImportError: pass def isSharp(ang): return ang > math.pi/4 + 0.00001 def unitVector(p2, p1): d0 = p2[0] - p1[0] d1 = p2[1] - p1[1] d = math.sqrt(d0*d0 + d1*d1) if d != 0: return [d0/d, d1/d] return [0, 0] def compVectors(P): V = [] for i in range(1,len(P)): v = unitVector(P[i], P[i-1]) if v[0] == 0 and v[1] == 0: return None V.append(v) return V def angle(v2, v1): d = v2[0]*v1[0] + v2[1]*v1[1] if d > 1: d = 1 if d < -1: d = -1 return math.acos(d) def compAngles(V): A = [] for i in range(len(V)-1): A.append(angle(V[i+1], V[i])) return A def updateAngles(i, P, V, A): if i-1 >= 0: V[i-1] = unitVector(P[i], P[i-1]) if i+1 < len(P): V[i] = unitVector(P[i+1], P[i]) if i-2 >= 0: A[i-2] = angle(V[i-1], V[i-2]) if i-1 >= 0 and i+1 < len(P): A[i-1] = angle(V[i], V[i-1]) if i+2 < len(P): A[i] = angle(V[i+1], V[i]) def checkMoves(check, P, V, A, filled): for i in check: if i < 0 or i >= len(P): break x, y = P[i] for j in range(51): for k in range(51): P[i][0] = j P[i][1] = k if str(P[i]) in filled: continue updateAngles(i, P, V, A) fixed = True if i-2 >= 0: if isSharp(A[i-2]): fixed = False if i-1 >= 0 and i-1 < len(A): if isSharp(A[i-1]): fixed = False if i < len(A): if isSharp(A[i]): fixed = False if fixed: return True P[i] = [x, y] updateAngles(i, P, V, A) return False def canFix(first, last, P, V, A, filled): d = last - first if d > 2: return False if d == 2: check = [first+2] if d == 1: check = [first+1, first+2] if d == 0: check = [first, first+1, first+2] if checkMoves(check, P, V, A, filled): return True return False T=int(input()) for i in range(T): N=int(input()) P=[] V=[] filled={} for i in range(N): P.append(list(map(int,input().split()))) filled[str(P[i])] = 1 V = compVectors(P) A = compAngles(V) blunt = True first = -1 last = -1 for i in range(len(A)): if isSharp(A[i]): blunt = False last = i if first < 0: first = i if blunt: print('yes yes') else: if canFix(first, last, P, V, A, filled): print('no yes') else: print('no no')
train
APPS_structured
Sereja have array A' that contain N integers. Now Sereja want to permute elements of the array, he want to use some permutation p, such that A[i] = A'[p[i]], where A - new array. Lets function f(A,i) = S - A[i] - A[i +1] - ... - A[j], where j is the maximum possible index, such that A[i] + A[i + 1] + ... + A[j] <= S, if A[i] > S, f(A, i) = S. Help Sereja to find such permutation p, such that (f(A, 1) + f(A, 2) + ... f(A, k))/k will be as low as possible. -----Input----- First line of input contain integer T - number of testcases. Next lines contain T testcases. First line of each testcase contain three integers N, k, S. Next line contain N integers - array A'. -----Output----- For each testcase output N numbers in one line - permutation p. -----Constraints----- - 1 ≤ T ≤ 10 - 1 ≤ N ≤ 2000 - 1 ≤ k ≤ N - 1 ≤ A'[i] ≤ 10^4 - 1 ≤ S ≤ 10^9 -----Example----- Input: 2 3 2 4 3 4 1 4 4 1 1 1 1 1 Output: 2 1 3 4 3 2 1 -----Scoring----- Suppose Sum will be sum of yours (f(A, 1) + f(A, 2) + ... f(A, k))/k per each testcase. Lets B will be the smallest such sum. Your score will be equal to B/Sum. Lower scores will earn more points. We have 20 official test files. You must correctly solve all test files to receive OK. During the contest, your overall score is the sum of the scores on the first 4 test files. After the contest, all solutions will be rescored by the sum of the scores on the rest 16 test files. Note, that public part of the tests may not contain some border cases.
import random t = int(input()) while t>0: t -= 1 n, k, s = list(map(int, input().split())) arr = list(map(int, input().split())) temp = sorted(list(range(n)), key=lambda x:arr[x]) arr.sort() for i in range(n-1): if arr[i]+arr[i+1] <= s: arr[i], arr[i+1] = arr[i+1], arr[i] temp[i], temp[i+1] = temp[i+1], temp[i] ans = [str(i+1) for i in temp] print(' '.join(ans))
import random t = int(input()) while t>0: t -= 1 n, k, s = list(map(int, input().split())) arr = list(map(int, input().split())) temp = sorted(list(range(n)), key=lambda x:arr[x]) arr.sort() for i in range(n-1): if arr[i]+arr[i+1] <= s: arr[i], arr[i+1] = arr[i+1], arr[i] temp[i], temp[i+1] = temp[i+1], temp[i] ans = [str(i+1) for i in temp] print(' '.join(ans))
train
APPS_structured
Balanced strings are those who have equal quantity of 'L' and 'R' characters. Given a balanced string s split it in the maximum amount of balanced strings. Return the maximum amount of splitted balanced strings. Example 1: Input: s = "RLRRLLRLRL" Output: 4 Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'. Example 2: Input: s = "RLLLLRRRLR" Output: 3 Explanation: s can be split into "RL", "LLLRRR", "LR", each substring contains same number of 'L' and 'R'. Example 3: Input: s = "LLLLRRRR" Output: 1 Explanation: s can be split into "LLLLRRRR". Example 4: Input: s = "RLRRRLLRLL" Output: 2 Explanation: s can be split into "RL", "RRRLLRLL", since each substring contains an equal number of 'L' and 'R' Constraints: 1 <= s.length <= 1000 s[i] = 'L' or 'R'
class Solution: def balancedStringSplit(self, s: str) -> int: count1 = 0 count2 = 0 counter = 0 for i in s: if i == 'R': count1 +=1 else: count2 +=1 if count1 == count2: counter +=1 return counter
class Solution: def balancedStringSplit(self, s: str) -> int: count1 = 0 count2 = 0 counter = 0 for i in s: if i == 'R': count1 +=1 else: count2 +=1 if count1 == count2: counter +=1 return counter
train
APPS_structured
Given a sequence of items and a specific item in that sequence, return the item immediately following the item specified. If the item occurs more than once in a sequence, return the item after the first occurence. This should work for a sequence of any type. When the item isn't present or nothing follows it, the function should return nil in Clojure and Elixir, Nothing in Haskell, undefined in JavaScript, None in Python. ```python next_item([1, 2, 3, 4, 5, 6, 7], 3) # => 4 next_item(['Joe', 'Bob', 'Sally'], 'Bob') # => "Sally" ```
def next_item(xs, item): flag = False for el in xs: if flag: return el if el == item: flag = True
def next_item(xs, item): flag = False for el in xs: if flag: return el if el == item: flag = True
train
APPS_structured
For an integer n, we call k>=2 a good base of n, if all digits of n base k are 1. Now given a string representing n, you should return the smallest good base of n in string format. Example 1: Input: "13" Output: "3" Explanation: 13 base 3 is 111. Example 2: Input: "4681" Output: "8" Explanation: 4681 base 8 is 11111. Example 3: Input: "1000000000000000000" Output: "999999999999999999" Explanation: 1000000000000000000 base 999999999999999999 is 11. Note: The range of n is [3, 10^18]. The string representing n is always valid and will not have leading zeros.
# # [483] Smallest Good Base # # https://leetcode.com/problems/smallest-good-base/description/ # # algorithms # Hard (33.74%) # Total Accepted: 6.7K # Total Submissions: 20K # Testcase Example: '"13"' # # For an integer n, we call k>=2 a good base of n, if all digits of n base k # are 1. # Now given a string representing n, you should return the smallest good base # of n in string format. # # Example 1: # # Input: "13" # Output: "3" # Explanation: 13 base 3 is 111. # # # # Example 2: # # Input: "4681" # Output: "8" # Explanation: 4681 base 8 is 11111. # # # # Example 3: # # Input: "1000000000000000000" # Output: "999999999999999999" # Explanation: 1000000000000000000 base 999999999999999999 is 11. # # # # Note: # # The range of n is [3, 10^18]. # The string representing n is always valid and will not have leading zeros. # # # from math import log class Solution: def smallestGoodBase(self, n): """ :type n: str :rtype: str """ num = int(n) bit = int(log(num, 2)) for b in range(bit, 1, -1) : base = int(num ** b ** -1) # print(b, base) if (base ** (b + 1) - 1) // (base - 1) == num : return str(base) return str(num - 1)
# # [483] Smallest Good Base # # https://leetcode.com/problems/smallest-good-base/description/ # # algorithms # Hard (33.74%) # Total Accepted: 6.7K # Total Submissions: 20K # Testcase Example: '"13"' # # For an integer n, we call k>=2 a good base of n, if all digits of n base k # are 1. # Now given a string representing n, you should return the smallest good base # of n in string format. # # Example 1: # # Input: "13" # Output: "3" # Explanation: 13 base 3 is 111. # # # # Example 2: # # Input: "4681" # Output: "8" # Explanation: 4681 base 8 is 11111. # # # # Example 3: # # Input: "1000000000000000000" # Output: "999999999999999999" # Explanation: 1000000000000000000 base 999999999999999999 is 11. # # # # Note: # # The range of n is [3, 10^18]. # The string representing n is always valid and will not have leading zeros. # # # from math import log class Solution: def smallestGoodBase(self, n): """ :type n: str :rtype: str """ num = int(n) bit = int(log(num, 2)) for b in range(bit, 1, -1) : base = int(num ** b ** -1) # print(b, base) if (base ** (b + 1) - 1) // (base - 1) == num : return str(base) return str(num - 1)
train
APPS_structured
Motu and Tomu are very good friends who are always looking for new games to play against each other and ways to win these games. One day, they decided to play a new type of game with the following rules: - The game is played on a sequence $A_0, A_1, \dots, A_{N-1}$. - The players alternate turns; Motu plays first, since he's earlier in lexicographical order. - Each player has a score. The initial scores of both players are $0$. - On his turn, the current player has to pick the element of $A$ with the lowest index, add its value to his score and delete that element from the sequence $A$. - At the end of the game (when $A$ is empty), Tomu wins if he has strictly greater score than Motu. Otherwise, Motu wins the game. In other words, Motu starts by selecting $A_0$, adding it to his score and then deleting it; then, Tomu selects $A_1$, adds its value to his score and deletes it, and so on. Motu and Tomu already chose a sequence $A$ for this game. However, since Tomu plays second, he is given a different advantage: before the game, he is allowed to perform at most $K$ swaps in $A$; afterwards, the two friends are going to play the game on this modified sequence. Now, Tomu wants you to determine if it is possible to perform up to $K$ swaps in such a way that he can win this game. -----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 $K$ denoting the number of elements in the sequence and the maximum number of swaps Tomu can perform. - The second line contains $N$ space-separated integers $A_0, A_1, \dots, A_{N-1}$. -----Output----- For each test case, print a single line containing the string "YES" if Tomu can win the game or "NO" otherwise (without quotes). -----Constraints----- - $1 \le T \le 100$ - $1 \le N \le 10,000$ - $0 \le K \le 10,000$ - $1 \le A_i \le 10,000$ for each valid $i$ -----Subtasks----- Subtask #1 (20 points): $1 \le N \le 100$ Subtask #2 (80 points): original constraints -----Example Input----- 2 6 0 1 1 1 1 1 1 5 1 2 4 6 3 4 -----Example Output----- NO YES -----Explanation----- Example case 1: At the end of the game, both Motu and Tomu will have scores $1+1+1 = 3$. Tomu is unable to win that game, so the output is "NO". Example case 2: If no swaps were performed, Motu's score would be $2+6+4 = 12$ and Tomu's score would be $4+3 = 7$. However, Tomu can swap the elements $A_2 = 6$ and $A_3 = 3$, which makes Motu's score at the end of the game equal to $2+3+4 = 9$ and Tomu's score equal to $4+6 = 10$. Tomu managed to score higher than Motu, so the output is "YES".
t=int(input()) for _ in range(t): n,k=list(map(int,input().split())) l=list(map(int,input().split())) a=l[0::2] b=l[1::2] al=len(a) bl=len(b) if(al>bl): ll=bl else: ll=al b.sort() a.sort(reverse=True) i=0 while(sum(a)>sum(b) and k>0 and i<ll): t=a[i] a[i]=b[i] b[i]=t i=i+1 k=k-1 if(sum(b)>sum(a)): print('YES') else: print('NO')
t=int(input()) for _ in range(t): n,k=list(map(int,input().split())) l=list(map(int,input().split())) a=l[0::2] b=l[1::2] al=len(a) bl=len(b) if(al>bl): ll=bl else: ll=al b.sort() a.sort(reverse=True) i=0 while(sum(a)>sum(b) and k>0 and i<ll): t=a[i] a[i]=b[i] b[i]=t i=i+1 k=k-1 if(sum(b)>sum(a)): print('YES') else: print('NO')
train
APPS_structured
While surfing in web I found interesting math problem called "Always perfect". That means if you add 1 to the product of four consecutive numbers the answer is ALWAYS a perfect square. For example we have: 1,2,3,4 and the product will be 1X2X3X4=24. If we add 1 to the product that would become 25, since the result number is a perfect square the square root of 25 would be 5. So now lets write a function which takes numbers separated by commas in string format and returns the number which is a perfect square and the square root of that number. If string contains other characters than number or it has more or less than 4 numbers separated by comma function returns "incorrect input". If string contains 4 numbers but not consecutive it returns "not consecutive".
import re def check_root(string): if not re.fullmatch(r"(-?\d+,){3}-?\d+", string): return 'incorrect input' a, b, c, d = list(map(int, string.split(","))) if not d == c + 1 == b + 2 == a + 3: return 'not consecutive' return f"{a * b * c * d + 1}, {abs(b ** 2 + a)}"
import re def check_root(string): if not re.fullmatch(r"(-?\d+,){3}-?\d+", string): return 'incorrect input' a, b, c, d = list(map(int, string.split(","))) if not d == c + 1 == b + 2 == a + 3: return 'not consecutive' return f"{a * b * c * d + 1}, {abs(b ** 2 + a)}"
train
APPS_structured
You have invented a time-machine which has taken you back to ancient Rome. Caeser is impressed with your programming skills and has appointed you to be the new information security officer. Caeser has ordered you to write a Caeser cipher to prevent Asterix and Obelix from reading his emails. A Caeser cipher shifts the letters in a message by the value dictated by the encryption key. Since Caeser's emails are very important, he wants all encryptions to have upper-case output, for example: If key = 3 "hello" -> KHOOR If key = 7 "hello" -> OLSSV Input will consist of the message to be encrypted and the encryption key.
def caeser(message, key): return''.join('ABCDEFGHIJKLMNOPQRSTUVWXYZ'[('ABCDEFGHIJKLMNOPQRSTUVWXYZ'.index(el)+key)%len('ABCDEFGHIJKLMNOPQRSTUVWXYZ')] if el in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' else el for el in message.upper())
def caeser(message, key): return''.join('ABCDEFGHIJKLMNOPQRSTUVWXYZ'[('ABCDEFGHIJKLMNOPQRSTUVWXYZ'.index(el)+key)%len('ABCDEFGHIJKLMNOPQRSTUVWXYZ')] if el in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' else el for el in message.upper())
train
APPS_structured
# Task Given a rectangular matrix containing only digits, calculate the number of different `2 × 2` squares in it. # Example For ``` matrix = [[1, 2, 1], [2, 2, 2], [2, 2, 2], [1, 2, 3], [2, 2, 1]] ``` the output should be `6`. Here are all 6 different 2 × 2 squares: ``` 1 2 2 2 2 1 2 2 2 2 2 2 2 2 1 2 2 2 2 3 2 3 2 1 ``` # Input/Output - `[input]` 2D integer array `matrix` Constraints: `1 ≤ matrix.length ≤ 100,` `1 ≤ matrix[i].length ≤ 100,` `0 ≤ matrix[i][j] ≤ 9.` - `[output]` an integer The number of different `2 × 2` squares in matrix.
def different_squares(matrix): result = [] for i in range(len(matrix) - 1): for j in range(len(matrix[0]) - 1): one = [ matrix[i][j:j + 2], matrix[i + 1][j:j + 2] ] if one not in result: result.append(one) return len(result)
def different_squares(matrix): result = [] for i in range(len(matrix) - 1): for j in range(len(matrix[0]) - 1): one = [ matrix[i][j:j + 2], matrix[i + 1][j:j + 2] ] if one not in result: result.append(one) return len(result)
train
APPS_structured
You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x. Notice that x does not have to be an element in nums. Return x if the array is special, otherwise, return -1. It can be proven that if nums is special, the value for x is unique. Example 1: Input: nums = [3,5] Output: 2 Explanation: There are 2 values (3 and 5) that are greater than or equal to 2. Example 2: Input: nums = [0,0] Output: -1 Explanation: No numbers fit the criteria for x. If x = 0, there should be 0 numbers >= x, but there are 2. If x = 1, there should be 1 number >= x, but there are 0. If x = 2, there should be 2 numbers >= x, but there are 0. x cannot be greater since there are only 2 numbers in nums. Example 3: Input: nums = [0,4,3,0,4] Output: 3 Explanation: There are 3 values that are greater than or equal to 3. Example 4: Input: nums = [3,6,7,7,0] Output: -1 Constraints: 1 <= nums.length <= 100 0 <= nums[i] <= 1000
class Solution: def specialArray(self, nums: List[int]) -> int: res = -1 nums.sort() for i in range(0, len(nums)): temp = 0 for j in range(0, len(nums)): if nums[j] >= i+1 and nums[j] != 0: temp += 1 if i+1 == temp: res = i+1 if i+1 > res else res return res
class Solution: def specialArray(self, nums: List[int]) -> int: res = -1 nums.sort() for i in range(0, len(nums)): temp = 0 for j in range(0, len(nums)): if nums[j] >= i+1 and nums[j] != 0: temp += 1 if i+1 == temp: res = i+1 if i+1 > res else res return res
train
APPS_structured
The mean and standard deviation of a sample of data can be thrown off if the sample contains one or many outlier(s) : (image source) For this reason, it is usually a good idea to check for and remove outliers before computing the mean or the standard deviation of a sample. To this aim, your function will receive a list of numbers representing a sample of data. Your function must remove any outliers and return the mean of the sample, rounded to two decimal places (round only at the end). Since there is no objective definition of "outlier" in statistics, your function will also receive a cutoff, in standard deviation units. So for example if the cutoff is 3, then any value that is more than 3 standard deviations above or below the mean must be removed. Notice that, once outlying values are removed in a first "sweep", other less extreme values may then "become" outliers, that you'll have to remove as well! Example : ```python sample = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100] cutoff = 3 clean_mean(sample, cutoff) → 5.5 ``` Formula for the mean : (where n is the sample size) Formula for the standard deviation : (where N is the sample size, xi is observation i and x̄ is the sample mean) Note : since we are not computing the sample standard deviation for inferential purposes, the denominator is n, not n - 1.
from statistics import mean, pstdev def clean_mean(sample, cutoff): cond = True while cond: _mean = mean(sample) _stdev = pstdev(sample) cut = [x for x in sample if abs(x-_mean)/_stdev <= cutoff] cond = len(sample) != len(cut) sample = cut return round(mean(sample),2)
from statistics import mean, pstdev def clean_mean(sample, cutoff): cond = True while cond: _mean = mean(sample) _stdev = pstdev(sample) cut = [x for x in sample if abs(x-_mean)/_stdev <= cutoff] cond = len(sample) != len(cut) sample = cut return round(mean(sample),2)
train
APPS_structured
Validate if a given string is numeric. Some examples: "0" => true " 0.1 " => true "abc" => false "1 a" => false "2e10" => true Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. Update (2015-02-10): The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.
class Solution: def isNumber(self, s): try: float(s) return True except: return False
class Solution: def isNumber(self, s): try: float(s) return True except: return False
train
APPS_structured
Hooray! Polycarp turned $n$ years old! The Technocup Team sincerely congratulates Polycarp! Polycarp celebrated all of his $n$ birthdays: from the $1$-th to the $n$-th. At the moment, he is wondering: how many times he turned beautiful number of years? According to Polycarp, a positive integer is beautiful if it consists of only one digit repeated one or more times. For example, the following numbers are beautiful: $1$, $77$, $777$, $44$ and $999999$. The following numbers are not beautiful: $12$, $11110$, $6969$ and $987654321$. Of course, Polycarpus uses the decimal numeral system (i.e. radix is 10). Help Polycarpus to find the number of numbers from $1$ to $n$ (inclusive) that are beautiful. -----Input----- The first line contains an integer $t$ ($1 \le t \le 10^4$) — the number of test cases in the input. Then $t$ test cases follow. Each test case consists of one line, which contains a positive integer $n$ ($1 \le n \le 10^9$) — how many years Polycarp has turned. -----Output----- Print $t$ integers — the answers to the given test cases in the order they are written in the test. Each answer is an integer: the number of beautiful years between $1$ and $n$, inclusive. -----Example----- Input 6 18 1 9 100500 33 1000000000 Output 10 1 9 45 12 81 -----Note----- In the first test case of the example beautiful years are $1$, $2$, $3$, $4$, $5$, $6$, $7$, $8$, $9$ and $11$.
t=int(input()) for i in range(t): n=int(input()) count=0 for j in range(1,10): s=str(j) while int(s)<=n: s=s+str(j) count+=1 print(count)
t=int(input()) for i in range(t): n=int(input()) count=0 for j in range(1,10): s=str(j) while int(s)<=n: s=s+str(j) count+=1 print(count)
train
APPS_structured
You've arrived at a carnival and head straight for the duck shooting tent. Why wouldn't you? You will be given a set amount of ammo, and an aim rating of between 1 and 0. No your aim is not always perfect - hey maybe someone fiddled with the sights on the gun... Anyway your task is to calculate how many successful shots you will be able to make given the available ammo and your aim score, then return a string representing the pool of ducks, with those ducks shot marked with 'X' and those that survived left unchanged. You will always shoot left to right. Example of start and end duck string with two successful shots: Start ---> |~~~~~22~2~~~~~| **Bang!! Bang!!** End ---> |~~~~~XX~2~~~~~| All inputs will be correct type and never empty.
duck_shoot=lambda a,b,c:c.replace('2','X',int(a*b))
duck_shoot=lambda a,b,c:c.replace('2','X',int(a*b))
train
APPS_structured
Many people choose to obfuscate their email address when displaying it on the Web. One common way of doing this is by substituting the `@` and `.` characters for their literal equivalents in brackets. Example 1: ``` [email protected] => user_name [at] example [dot] com ``` Example 2: ``` [email protected] => af5134 [at] borchmore [dot] edu ``` Example 3: ``` [email protected] => jim [dot] kuback [at] ennerman-hatano [dot] com ``` Using the examples above as a guide, write a function that takes an email address string and returns the obfuscated version as a string that replaces the characters `@` and `.` with `[at]` and `[dot]`, respectively. >Notes >* Input (`email`) will always be a string object. Your function should return a string. >* Change only the `@` and `.` characters. >* Email addresses may contain more than one `.` character. >* Note the additional whitespace around the bracketed literals in the examples!
def obfuscate(email): return email.replace('.', ' [dot] ').replace('@', ' [at] ')
def obfuscate(email): return email.replace('.', ' [dot] ').replace('@', ' [at] ')
train
APPS_structured
Chef likes strings a lot but he likes palindromic strings more. Today, Chef has two strings A and B, each consisting of lower case alphabets. Chef is eager to know whether it is possible to choose some non empty strings s1 and s2 where s1 is a substring of A, s2 is a substring of B such that s1 + s2 is a palindromic string. Here '+' denotes the concatenation between the strings. Note: A string is a palindromic string if it can be read same both forward as well as backward. To know more about palindromes click here. -----Input----- - First line of input contains a single integer T denoting the number of test cases. - For each test case: - First line contains the string A - Second line contains the string B. -----Output----- For each test case, Print "Yes" (without quotes) if it possible to choose such strings s1 & s2. Print "No" (without quotes) otherwise. -----Constraints----- - 1 ≤ T ≤ 10 - 1 ≤ |A|, |B| ≤ 1000 -----Subtasks----- - Subtask 1: 1 ≤ |A|, |B| ≤ 10 : ( 40 pts ) - Subtask 2: 1 ≤ |A|, |B| ≤ 1000 : ( 60 pts ) -----Example-----Input 3 abc abc a b abba baab Output Yes No Yes -----Explanation----- - Test 1: One possible way of choosing s1 & s2 is s1 = "ab", s2 = "a" such that s1 + s2 i.e "aba" is a palindrome. - Test 2: There is no possible way to choose s1 & s2 such that s1 + s2 is a palindrome. - Test 3: You can figure it out yourself.
# cook your dish here t = int(input()) for z in range(t) : a = input() b = input() s1 = set(a) s2 = set(b) if s1&s2 : print("Yes") else: print("No")
# cook your dish here t = int(input()) for z in range(t) : a = input() b = input() s1 = set(a) s2 = set(b) if s1&s2 : print("Yes") else: print("No")
train
APPS_structured
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a $r \times c$ grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad. Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say $a$, passes by another country $b$, they change the dominant religion of country $b$ to the dominant religion of country $a$. In particular, a single use of your power is this: You choose a horizontal $1 \times x$ subgrid or a vertical $x \times 1$ subgrid. That value of $x$ is up to you; You choose a direction $d$. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; You choose the number $s$ of steps; You command each country in the subgrid to send a missionary group that will travel $s$ steps towards direction $d$. In each step, they will visit (and in effect convert the dominant religion of) all $s$ countries they pass through, as detailed above. The parameters $x$, $d$, $s$ must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a $1 \times 4$ subgrid, the direction NORTH, and $s = 2$ steps. [Image] You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country. What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism? With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so. -----Input----- The first line of input contains a single integer $t$ ($1 \le t \le 2\cdot 10^4$) denoting the number of test cases. The first line of each test case contains two space-separated integers $r$ and $c$ denoting the dimensions of the grid ($1 \le r, c \le 60$). The next $r$ lines each contains $c$ characters describing the dominant religions in the countries. In particular, the $j$-th character in the $i$-th line describes the dominant religion in the country at the cell with row $i$ and column $j$, where: "A" means that the dominant religion is Beingawesomeism; "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the $r \cdot c$ in a single file is at most $3 \cdot 10^6$. -----Output----- For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so. -----Example----- Input 4 7 8 AAPAAAAA PPPPAAAA PPPPAAAA APAAPPPP APAPPAPP AAAAPPAP AAAAPPAA 6 5 AAAAA AAAAA AAPAA AAPAP AAAPP AAAPP 4 4 PPPP PPPP PPPP PPPP 3 4 PPPP PAAP PPPP Output 2 1 MORTAL 4 -----Note----- In the first test case, it can be done in two usages, as follows: Usage 1: [Image] Usage 2: [Image] In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL".
import sys input = sys.stdin.readline t = int(input()) for _ in range(t): h, w = list(map(int, input().split())) grid = [] for _ in range(h): line = input().rstrip('\n') tmp = [line[i] == 'A' for i in range(w)] grid.append(tmp) ok = 0 all_A = 1 for i in range(h): for j in range(w): if grid[i][j]: ok = 1 else: all_A = 0 if not ok: print('MORTAL') continue if all_A: print(0) continue all_True = 1 for i in range(w): if not grid[0][i]: all_True = 0 break if all_True: print(1) continue all_True = 1 for i in range(w): if not grid[-1][i]: all_True = 0 break if all_True: print(1) continue all_True = 1 for i in range(h): if not grid[i][0]: all_True = 0 break if all_True: print(1) continue all_True = 1 for i in range(h): if not grid[i][-1]: all_True = 0 break if all_True: print(1) continue if grid[0][0] | grid[0][-1] | grid[-1][0] | grid[-1][-1]: print(2) continue flg = 0 for i in range(1, h-1): if sum(grid[i]) == w: flg = 1 break for i in range(1, w-1): ok = 1 for k in range(h): if not grid[k][i]: ok = 0 break if ok: flg = 1 break if flg: print(2) continue any_True = 0 for i in range(w): if grid[0][i]: any_True = 1 break if grid[-1][i]: any_True = 1 break for i in range(h): if grid[i][0]: any_True = 1 break if grid[i][-1]: any_True = 1 break if any_True: print(3) continue print(4)
import sys input = sys.stdin.readline t = int(input()) for _ in range(t): h, w = list(map(int, input().split())) grid = [] for _ in range(h): line = input().rstrip('\n') tmp = [line[i] == 'A' for i in range(w)] grid.append(tmp) ok = 0 all_A = 1 for i in range(h): for j in range(w): if grid[i][j]: ok = 1 else: all_A = 0 if not ok: print('MORTAL') continue if all_A: print(0) continue all_True = 1 for i in range(w): if not grid[0][i]: all_True = 0 break if all_True: print(1) continue all_True = 1 for i in range(w): if not grid[-1][i]: all_True = 0 break if all_True: print(1) continue all_True = 1 for i in range(h): if not grid[i][0]: all_True = 0 break if all_True: print(1) continue all_True = 1 for i in range(h): if not grid[i][-1]: all_True = 0 break if all_True: print(1) continue if grid[0][0] | grid[0][-1] | grid[-1][0] | grid[-1][-1]: print(2) continue flg = 0 for i in range(1, h-1): if sum(grid[i]) == w: flg = 1 break for i in range(1, w-1): ok = 1 for k in range(h): if not grid[k][i]: ok = 0 break if ok: flg = 1 break if flg: print(2) continue any_True = 0 for i in range(w): if grid[0][i]: any_True = 1 break if grid[-1][i]: any_True = 1 break for i in range(h): if grid[i][0]: any_True = 1 break if grid[i][-1]: any_True = 1 break if any_True: print(3) continue print(4)
train
APPS_structured
In the evenings Donkey would join Shrek to look at the stars. They would sit on a log, sipping tea and they would watch the starry sky. The sky hung above the roof, right behind the chimney. Shrek's stars were to the right of the chimney and the Donkey's stars were to the left. Most days the Donkey would just count the stars, so he knew that they are exactly n. This time he wanted a challenge. He imagined a coordinate system: he put the origin of the coordinates at the intersection of the roof and the chimney, directed the OX axis to the left along the roof and the OY axis — up along the chimney (see figure). The Donkey imagined two rays emanating from he origin of axes at angles α_1 and α_2 to the OX axis. [Image] Now he chooses any star that lies strictly between these rays. After that he imagines more rays that emanate from this star at the same angles α_1 and α_2 to the OX axis and chooses another star that lies strictly between the new rays. He repeats the operation as long as there still are stars he can choose between the rays that emanate from a star. [Image] As a result, the Donkey gets a chain of stars. He can consecutively get to each star if he acts by the given rules. Your task is to find the maximum number of stars m that the Donkey's chain can contain. Note that the chain must necessarily start in the point of the origin of the axes, that isn't taken into consideration while counting the number m of stars in the chain. -----Input----- The first line contains an integer n (1 ≤ n ≤ 10^5) — the number of stars. The second line contains simple fractions representing relationships "a/b c/d", such that $\frac{a}{b} = \frac{\operatorname{sin} \alpha_{1}}{\operatorname{cos} \alpha_{1}}$ and $\frac{c}{d} = \frac{\operatorname{sin} \alpha_{2}}{\operatorname{cos} \alpha}$ (0 ≤ a, b, c, d ≤ 10^5; $0^{\circ} \leq \alpha_{1} < \alpha_{2} \leq 90^{\circ}$; $\frac{a}{b} \neq \frac{0}{0}$; $\frac{c}{d} \neq \frac{0}{0}$). The given numbers a, b, c, d are integers. Next n lines contain pairs of integers x_{i}, y_{i} (1 ≤ x_{i}, y_{i} ≤ 10^5)— the stars' coordinates. It is guaranteed that all stars have distinct coordinates. -----Output----- In a single line print number m — the answer to the problem. -----Examples----- Input 15 1/3 2/1 3 1 6 2 4 2 2 5 4 5 6 6 3 4 1 6 2 1 7 4 9 3 5 3 1 3 15 5 12 4 Output 4 -----Note----- In the sample the longest chain the Donkey can build consists of four stars. Note that the Donkey can't choose the stars that lie on the rays he imagines. [Image]
from bisect import * from math import * n = int(input()) a, b, c, d = list(map(int,input().replace('/',' ').split())) alpha = atan2(c,d) - atan2(a,b) tan_alpha = tan(alpha) lis = [] for x,y in sorted((y/tan_alpha - x,y) for x,y in [ (x,y) for x,y in [(b*x + a*y,-a*x + b*y) for x, y in [list(map(int,input().split())) for _ in range(n)] if a*x - b*y <= 0 and d*y - c*x <= 0]]): pos = bisect_left(lis,-y) if pos == len(lis): lis.append(-y) else: lis[pos] = -y print(len(lis))
from bisect import * from math import * n = int(input()) a, b, c, d = list(map(int,input().replace('/',' ').split())) alpha = atan2(c,d) - atan2(a,b) tan_alpha = tan(alpha) lis = [] for x,y in sorted((y/tan_alpha - x,y) for x,y in [ (x,y) for x,y in [(b*x + a*y,-a*x + b*y) for x, y in [list(map(int,input().split())) for _ in range(n)] if a*x - b*y <= 0 and d*y - c*x <= 0]]): pos = bisect_left(lis,-y) if pos == len(lis): lis.append(-y) else: lis[pos] = -y print(len(lis))
train
APPS_structured
Indian National Olympiad in Informatics 2014 Due to resurfacing work, all north-south traffic on the highway is being diverted through the town of Siruseri. Siruseri is a modern, planned town and the section of roads used for the diversion forms a rectangular grid where all cars enter at the top-left intersection (north- west) and leave at the bottom-right intersection (south-east). All roads within the grid are one-way, allowing traffic to move north to south (up-down) and west to east (left-right) only. The town authorities are concerned about highway drivers overspeeding through the town. To slow them down, they have made a rule that no car may travel more than d consecutive road segments in the same direction without turning. (Closed-circuit TV cameras have been installed to enforce this rule.) Of course, there is also repair work going on within the town, so some intersections are blocked and cars cannot pass through these. You are given the layout of the rectangular grid of roads within Siruseri and the constraint on how many consecutive road segments you may travel in the same direction. Your task is to compute the total number of paths from the entry (top-left) to the exit (bottom-right). For instance, suppose there are 3 rows and 4 columns of intersec- tions, numbered from (1,1) at the top-left to (3,4) at the bottom-right, as shown on the right. Intersection (2,1) in the second row, first column is blocked, and no car may travel more than 2 consecutive road seg- ments in the same direction. Here, (1,1) → (1,2) → (2,2) → (3,2) → (3,3) → (3,4) is a valid path from (1,1) to (3,4), but (1,1) → (1,2) → (1,3) → (1,4) → (2,4) → (3,4) is not, because this involves 3 consecutive road segments from left to right. The path (1, 1) → (2, 1) → (2, 2) → (2, 3) → (3, 3) → (3, 4) is ruled out because it goes through a blocked intersection. In this example, you can check that the total number of valid paths is 5. -----Input format----- • Line 1: Three space-separated integers, R, C and d, where R is the number of rows in the grid, C is the number of columns in the grid and d is the maximum number of consecutive segments you can travel in any direction. • Lines 2 to R+1: Each line contains C integers, each of which is 0 or 1, describing one row of intersections in the grid. An intersection marked 0 is blocked and an intersection marked 1 is available to pass through. The start (top-left) and finish (bottom-right) intersections are always marked 1. -----Output format----- A single integer—the number of paths from the top-left intersection to the bottom-right intersection that go only down and right, and obey the d constraint. Since the final answer may not fit in a variable of type int, report your answer modulo 20011. Be careful to avoid overflows in intermediate computations. -----Test Data----- The testdata is grouped into three subtasks. In all subtasks, 1 ≤ R ≤ 300, 1 ≤ C ≤ 300 and 1 ≤ d ≤ 300. In addition, each subtask has the following constraints on the inputs. • Subtask 1 [20 points]: d = max(R, C) − 1. (In other words, there is no limit on the number of consecutive segments you can travel in one direction.) • Subtask 2 [30 points]: d=2. • Subtask 3 [50 points]: No additional constraint on d. -----Example----- Here is the sample input and output corresponding to the example above. -----Sample input----- 3 4 2 1 1 1 1 0 1 1 1 1 1 1 1 -----Sample output----- 5 Note: Your program should not print anything other than what is specified in the output format. Please remove all diagnostic print statements before making your final submission. A program with extraneous output will be treated as incorrect!
class PathNode: def __init__(self, row, col, st_x, st_y, p_count=0): self.x = row self.y = col self.pathCount = p_count def __str__(self): return str(self.x) + " | " + str(self.y) + " | " + str(self.pathCount) class GraphUtil: def __init__(self, mat, R,C, d): self.mat = mat self.R = R self.C = C self.d = d self.tab = {} def isValidMove(self, r, c, blockVal): return r < self.R and c < self.C and self.mat[r][c] != blockVal def possbilePathUtil(self, r, c, blockVal, step,direction): if(not self.isValidMove(r, c, 0)): return 0 if (r == self.R - 1 and c == self.C - 1): return 1 if ((r,c,step,direction) in self.tab): return self.tab[(r,c,step,direction)] result = 0 if direction == 1: if step < self.d: result = (result + self.possbilePathUtil(r, c + 1, blockVal, step + 1,1)) % 20011 result = (result + self.possbilePathUtil(r+1, c, blockVal, 1,2)) % 20011 else: if step < self.d: result = (result + self.possbilePathUtil(r + 1, c, blockVal, step + 1, 2)) % 20011 result = (result + self.possbilePathUtil(r, c + 1, blockVal, 1,1)) % 20011 self.tab[(r,c,step,direction)] = result return result def possbilePath(self): if (not self.mat or len(self.mat) < 1): return 0 return self.possbilePathUtil(0, 0, 0,0,2) numbers = [int(n) for n in input().split()] mat = [[int(n) for n in input().split()] for r in range(0, numbers[0])] result = GraphUtil(mat, numbers[0], numbers[1], numbers[2]) print(result.possbilePath()) # print(result.count)
class PathNode: def __init__(self, row, col, st_x, st_y, p_count=0): self.x = row self.y = col self.pathCount = p_count def __str__(self): return str(self.x) + " | " + str(self.y) + " | " + str(self.pathCount) class GraphUtil: def __init__(self, mat, R,C, d): self.mat = mat self.R = R self.C = C self.d = d self.tab = {} def isValidMove(self, r, c, blockVal): return r < self.R and c < self.C and self.mat[r][c] != blockVal def possbilePathUtil(self, r, c, blockVal, step,direction): if(not self.isValidMove(r, c, 0)): return 0 if (r == self.R - 1 and c == self.C - 1): return 1 if ((r,c,step,direction) in self.tab): return self.tab[(r,c,step,direction)] result = 0 if direction == 1: if step < self.d: result = (result + self.possbilePathUtil(r, c + 1, blockVal, step + 1,1)) % 20011 result = (result + self.possbilePathUtil(r+1, c, blockVal, 1,2)) % 20011 else: if step < self.d: result = (result + self.possbilePathUtil(r + 1, c, blockVal, step + 1, 2)) % 20011 result = (result + self.possbilePathUtil(r, c + 1, blockVal, 1,1)) % 20011 self.tab[(r,c,step,direction)] = result return result def possbilePath(self): if (not self.mat or len(self.mat) < 1): return 0 return self.possbilePathUtil(0, 0, 0,0,2) numbers = [int(n) for n in input().split()] mat = [[int(n) for n in input().split()] for r in range(0, numbers[0])] result = GraphUtil(mat, numbers[0], numbers[1], numbers[2]) print(result.possbilePath()) # print(result.count)
train
APPS_structured
Chef has a number N, Cheffina challenges the chef to check the divisibility of all the permutation of N by 2. If any of the permutations is divisible by 2 then print 1 else print 0. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, $N$. -----Output:----- For each test case, output in a single line answer 1 or 0. -----Constraints----- - $1 \leq T \leq 10^6$ - $1 \leq N \leq 10^6$ -----Sample Input:----- 2 19 385 -----Sample Output:----- 0 1
import sys from math import log2 from itertools import combinations #input = sys.stdin.readline #sys.stdin.readline() #sys.stdout.write("\n") # # For getting input from input.txt file # sys.stdin = open('Python_input1.txt', 'r') # # Printing the Output to output.txt file # sys.stdout = open('Python_output1.txt', 'w') for _ in range(int(sys.stdin.readline())): n =str(sys.stdin.readline()) n = n[:-1] #print(n) temp =0 #print(n[0]) for i in range(len(n)): #print(n[i]) if int(n[i])%2== 0: temp = 1 if temp: print(1) else: print(0)
import sys from math import log2 from itertools import combinations #input = sys.stdin.readline #sys.stdin.readline() #sys.stdout.write("\n") # # For getting input from input.txt file # sys.stdin = open('Python_input1.txt', 'r') # # Printing the Output to output.txt file # sys.stdout = open('Python_output1.txt', 'w') for _ in range(int(sys.stdin.readline())): n =str(sys.stdin.readline()) n = n[:-1] #print(n) temp =0 #print(n[0]) for i in range(len(n)): #print(n[i]) if int(n[i])%2== 0: temp = 1 if temp: print(1) else: print(0)
train
APPS_structured
Some new animals have arrived at the zoo. The zoo keeper is concerned that perhaps the animals do not have the right tails. To help her, you must correct the broken function to make sure that the second argument (tail), is the same as the last letter of the first argument (body) - otherwise the tail wouldn't fit! If the tail is right return true, else return false. The arguments will always be strings, and normal letters.
def correct_tail(body, tail): index = [letter for letter in body] if index[-1] == tail: return True else: return False
def correct_tail(body, tail): index = [letter for letter in body] if index[-1] == tail: return True else: return False
train
APPS_structured
You are given an array $A$ of $N$ positive and pairwise distinct integers. You can permute the elements in any way you want. The cost of an ordering $(A_1, A_2, \ldots, A_N)$ is defined as $ (((A_1 \bmod A_2) \bmod A_3)......) \bmod A_N$ where $X \bmod Y$ means the remainder when $X$ is divided by $Y$. You need to find the maximum cost which can be attained through any possible ordering of the elements. -----Input:----- - The first line contains $T$ denoting the number of test cases. - The first line of each testcase contains a single integer $N$. - The second line of each testcase contains $N$ space-separated integers, the elements of $A$. -----Output:----- - For each testcase, output the maximum possible cost in a new line. -----Constraints----- - $1 \leq T \leq 5*10^5$ - $2 \leq N \leq 5*10^5$ - $1 \leq A_i \leq 10^9$ - Sum of $N$ over all testcases is less than or equal to $10^6$ - All elements in a single testcase are distinct. -----Subtasks----- - 100 points : Original constraints. -----Sample Input:----- 1 2 7 12 -----Sample Output:----- 7 -----Explanation:----- The two possible ways to order the elements are [7, 12] and [12, 7]. In the first case, the cost is $7 \bmod 12 = 7$ and in the second case the cost is $12 \bmod 7 = 5$. Clearly the answer is 7.
for i in range(int(input())): n=int(input()) l=list(map(int,input().split())) print(min(l))
for i in range(int(input())): n=int(input()) l=list(map(int,input().split())) print(min(l))
train
APPS_structured
Teddy and Tracy like to play a game based on strings. The game is as follows. Initially, Tracy writes a long random string on a whiteboard. Then, each player starting with Teddy makes turn alternately. Each turn, the player must erase a contiguous substring that exists in the dictionary. The dictionary consists of N words. Of course, the player that can't erase any substring in his turn loses the game, and the other player is declared the winner. Note that after a substring R is erased, the remaining substring becomes separated, i.e. they cannot erase a word that occurs partially to the left of R and partially to the right of R. Determine the winner of the game, assuming that both players play optimally. -----Input----- The first line contains a single integer T, the number of test cases. T test cases follow. The first line of each testcase contains a string S, the string Tracy writes on the whiteboard. The next line contains a single integer N. N lines follow. The i-th line contains a single string wi, the i-th word in the dictionary. -----Output----- For each test case, output a single line containing the name of the winner of the game. -----Example----- Input: 3 codechef 2 code chef foo 1 bar mississippi 4 ssissi mippi mi ppi Output: Tracy Tracy Teddy -----Constraints----- - 1 <= T <= 5 - 1 <= N <= 30 - 1 <= |S| <= 30 - 1 <= |wi| <= 30 - S and wi contain only characters 'a'-'z'
#!/usr/bin/env python def memo(func): cache = {} def f(*args): if args in cache: return cache[args] r = func(*args) cache[args] = r return r return f def doit(): s = input().strip() words = set([input().strip() for x in range(eval(input()))]) @memo def g(start, end): num = set([]) if start >= end: return 0 for w in words: x = start while x + len(w) <= end: r = s.find(w, x, end) if r == -1: break num.add(g(start, r) ^ g(r + len(w), end)) x = r + 1 x = 0 while x in num: x += 1 return x return g(0, len(s)) > 0 n = eval(input()) for x in range(n): if doit(): print('Teddy') else: print('Tracy')
#!/usr/bin/env python def memo(func): cache = {} def f(*args): if args in cache: return cache[args] r = func(*args) cache[args] = r return r return f def doit(): s = input().strip() words = set([input().strip() for x in range(eval(input()))]) @memo def g(start, end): num = set([]) if start >= end: return 0 for w in words: x = start while x + len(w) <= end: r = s.find(w, x, end) if r == -1: break num.add(g(start, r) ^ g(r + len(w), end)) x = r + 1 x = 0 while x in num: x += 1 return x return g(0, len(s)) > 0 n = eval(input()) for x in range(n): if doit(): print('Teddy') else: print('Tracy')
train
APPS_structured
**Getting Familiar:** LEET: (sometimes written as "1337" or "l33t"), also known as eleet or leetspeak, is another alphabet for the English language that is used mostly on the internet. It uses various combinations of ASCII characters to replace Latinate letters. For example, leet spellings of the word leet include 1337 and l33t; eleet may be spelled 31337 or 3l33t. GREEK: The Greek alphabet has been used to write the Greek language since the 8th century BC. It was derived from the earlier Phoenician alphabet, and was the first alphabetic script to have distinct letters for vowels as well as consonants. It is the ancestor of the Latin and Cyrillic scripts.Apart from its use in writing the Greek language, both in its ancient and its modern forms, the Greek alphabet today also serves as a source of technical symbols and labels in many domains of mathematics, science and other fields. **Your Task :** You have to create a function **GrεεκL33t** which takes a string as input and returns it in the form of (L33T+Grεεκ)Case. Note: The letters which are not being converted in (L33T+Grεεκ)Case should be returned in the lowercase. **(L33T+Grεεκ)Case:** A=α (Alpha) B=β (Beta) D=δ (Delta) E=ε (Epsilon) I=ι (Iota) K=κ (Kappa) N=η (Eta) O=θ (Theta) P=ρ (Rho) R=π (Pi) T=τ (Tau) U=μ (Mu) V=υ (Upsilon) W=ω (Omega) X=χ (Chi) Y=γ (Gamma) **Examples:** GrεεκL33t("CodeWars") = "cθδεωαπs" GrεεκL33t("Kata") = "κατα"
def gr33k_l33t(s): doc = { 'a':'α', 'b':'β', 'd':'δ', 'e':'ε', 'i':'ι', 'k':'κ', 'n':'η', 'o':'θ', 'p':'ρ', 'r':'π', 't':'τ', 'u':'μ', 'v':'υ', 'w':'ω', 'x':'χ', 'y':'γ' } return ''.join(doc.get(e ,e) for e in s.lower())
def gr33k_l33t(s): doc = { 'a':'α', 'b':'β', 'd':'δ', 'e':'ε', 'i':'ι', 'k':'κ', 'n':'η', 'o':'θ', 'p':'ρ', 'r':'π', 't':'τ', 'u':'μ', 'v':'υ', 'w':'ω', 'x':'χ', 'y':'γ' } return ''.join(doc.get(e ,e) for e in s.lower())
train
APPS_structured
In this Kata, you will be given a number `n` (`n > 0`) and your task will be to return the smallest square number `N` (`N > 0`) such that `n + N` is also a perfect square. If there is no answer, return `-1` (`nil` in Clojure, `Nothing` in Haskell, `None` in Rust). ```clojure solve 13 = 36 ; because 36 is the smallest perfect square that can be added to 13 to form a perfect square => 13 + 36 = 49 solve 3 = 1 ; 3 + 1 = 4, a perfect square solve 12 = 4 ; 12 + 4 = 16, a perfect square solve 9 = 16 solve 4 = nil ``` ```csharp solve(13) = 36 //because 36 is the smallest perfect square that can be added to 13 to form a perfect square => 13 + 36 = 49 solve(3) = 1 // 3 + 1 = 4, a perfect square solve(12) = 4 // 12 + 4 = 16, a perfect square solve(9) = 16 solve(4) = -1 ``` ```haskell solve 13 = Just 36 -- because 36 is the smallest perfect square that can be added to 13 to form a perfect square => 13 + 36 = 49 solve 3 = Just 1 -- 3 + 1 = 4, a perfect square solve 12 = Just 4 -- 12 + 4 = 16, a perfect square solve 9 = Just 16 solve 4 = Nothing ``` ```python solve(13) = 36 # because 36 is the smallest perfect square that can be added to 13 to form a perfect square => 13 + 36 = 49 solve(3) = 1 # 3 + 1 = 4, a perfect square solve(12) = 4 # 12 + 4 = 16, a perfect square solve(9) = 16 solve(4) = -1 ``` More examples in test cases. Good luck!
#let N be a^2 #n + N = M^2 (our answer) #n + a^2 = m^2 #stuff in slimesquad chat to read from import math def solve(n): d = math.ceil(math.sqrt(n)) - 1 #find the last biggest root we can use thats not the same number #now we need to go backwards because it cant be bigger than root N #we need to find a pair of factors for n (which is equal to x*y in discord) that are the same even and odd #or else A wouldnt be even print(d) for a in range(d, 0, -1):#the last argument is to go backwards #if we have Found a factor of N that is below the root(N) (finding the closest factors) #We go down from Root (N) because the further we go down, the more further apart the factors are #and if the difference gets bigger, we will have a bigger square number because the number #we need to find is the difference divided by 2 if (n % a == 0): #then find the second factor it could be #we can do this easily e = (n/a) - a print((a,e)) if e % 2 == 0: p = e / 2 return p*p return -1
#let N be a^2 #n + N = M^2 (our answer) #n + a^2 = m^2 #stuff in slimesquad chat to read from import math def solve(n): d = math.ceil(math.sqrt(n)) - 1 #find the last biggest root we can use thats not the same number #now we need to go backwards because it cant be bigger than root N #we need to find a pair of factors for n (which is equal to x*y in discord) that are the same even and odd #or else A wouldnt be even print(d) for a in range(d, 0, -1):#the last argument is to go backwards #if we have Found a factor of N that is below the root(N) (finding the closest factors) #We go down from Root (N) because the further we go down, the more further apart the factors are #and if the difference gets bigger, we will have a bigger square number because the number #we need to find is the difference divided by 2 if (n % a == 0): #then find the second factor it could be #we can do this easily e = (n/a) - a print((a,e)) if e % 2 == 0: p = e / 2 return p*p return -1
train
APPS_structured
# Task A noob programmer was given two simple tasks: sum and sort the elements of the given array `arr` = [a1, a2, ..., an]. He started with summing and did it easily, but decided to store the sum he found in some random position of the original array which was a bad idea. Now he needs to cope with the second task, sorting the original array arr, and it's giving him trouble since he modified it. Given the array `shuffled`, consisting of elements a1, a2, ..., an, and their sumvalue in random order, return the sorted array of original elements a1, a2, ..., an. # Example For `shuffled = [1, 12, 3, 6, 2]`, the output should be `[1, 2, 3, 6]`. `1 + 3 + 6 + 2 = 12`, which means that 1, 3, 6 and 2 are original elements of the array. For `shuffled = [1, -3, -5, 7, 2]`, the output should be `[-5, -3, 2, 7]`. # Input/Output - `[input]` integer array `shuffled` Array of at least two integers. It is guaranteed that there is an index i such that shuffled[i] = shuffled[0] + ... + shuffled[i - 1] + shuffled[i + 1] + ... + shuffled[n]. Constraints: `2 ≤ shuffled.length ≤ 30,` `-300 ≤ shuffled[i] ≤ 300.` - `[output]` an integer array A `sorted` array of shuffled.length - 1 elements.
def shuffled_array(s): s.sort() for i in range(len(s)): if s[i] == sum(s[:i]+s[i+1:]): return s[:i]+s[i+1:]
def shuffled_array(s): s.sort() for i in range(len(s)): if s[i] == sum(s[:i]+s[i+1:]): return s[:i]+s[i+1:]
train
APPS_structured
In this Kata, you will count the number of times the first string occurs in the second. ```Haskell solve("zaz","zazapulz") = 4 because they are ZAZapulz, ZAzapulZ, ZazApulZ, zaZApulZ ``` More examples in test cases. Good luck! Please also try [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2)
from functools import lru_cache def solve(a, b): l_a, l_b, rec = len(a), len(b), lru_cache(maxsize=None)(lambda x,y: (x == l_a) or sum(rec(x+1, i+1) for i in range(y, l_b) if b[i] == a[x])) return rec(0, 0)
from functools import lru_cache def solve(a, b): l_a, l_b, rec = len(a), len(b), lru_cache(maxsize=None)(lambda x,y: (x == l_a) or sum(rec(x+1, i+1) for i in range(y, l_b) if b[i] == a[x])) return rec(0, 0)
train
APPS_structured
per nextum in unam tum XI conscribementis fac sic vestibulo perlegementum da varo. morde varo. seqis cumula varum. cis per nextum in unam tum XI conscribementis fac sic seqis decumulamenta da varo. varum privamentum fodementum da aresulto. varum tum III elevamentum tum V multiplicamentum da bresulto. aresultum tum bresultum addementum da resulto. si CD tum resultum non praestantiam fac sic dictum sic f(%d) = %.2f cis tum varum tum resultum egresso describe. novumversum egresso scribe. cis si CD tum resultum praestantiam fac sic dictum sic f(%d) = MAGNA NIMIS! cis tum varum egresso describe. novumversum egresso scribe. cis cis -----Input----- The input consists of several integers, one per line. Each integer is between -50 and 50, inclusive. -----Output----- As described in the problem statement. -----Example----- Input 0 1 -2 -3 -4 -5 -6 -7 -8 -9 10 Output f(10) = MAGNA NIMIS! f(-9) = -3642.00 f(-8) = -2557.17 f(-7) = -1712.35 f(-6) = -1077.55 f(-5) = -622.76 f(-4) = -318.00 f(-3) = -133.27 f(-2) = -38.59 f(1) = 6.00 f(0) = 0.00
l = [int(input()) for i in range(11)] for i in range(11): x = l.pop() a = abs(x)**0.5 b = x**3 * 5 r = a + b if r > 400: print('f({}) = MAGNA NIMIS!'.format(x)) else: print('f({}) = {:.2f}'.format(x, r))
l = [int(input()) for i in range(11)] for i in range(11): x = l.pop() a = abs(x)**0.5 b = x**3 * 5 r = a + b if r > 400: print('f({}) = MAGNA NIMIS!'.format(x)) else: print('f({}) = {:.2f}'.format(x, r))
train
APPS_structured
Given an integer array, find three numbers whose product is maximum and output the maximum product. Example 1: Input: [1,2,3] Output: 6 Example 2: Input: [1,2,3,4] Output: 24 Note: The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000]. Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer.
class Solution: def maximumProduct(self, nums): """ :type nums: List[int] :rtype: int """ h, m, l = -float('inf'), -float('inf'), -float('inf') lowest, second_lowest = float('inf'), float('inf') for num in nums: if num > h: l = m m = h h= num elif num > m: l = m m = num elif num > l: l = num if num < lowest: second_lowest = lowest lowest = num elif num < second_lowest: second_lowest = num return max(h*m*l, h*lowest*second_lowest)
class Solution: def maximumProduct(self, nums): """ :type nums: List[int] :rtype: int """ h, m, l = -float('inf'), -float('inf'), -float('inf') lowest, second_lowest = float('inf'), float('inf') for num in nums: if num > h: l = m m = h h= num elif num > m: l = m m = num elif num > l: l = num if num < lowest: second_lowest = lowest lowest = num elif num < second_lowest: second_lowest = num return max(h*m*l, h*lowest*second_lowest)
train
APPS_structured
You're given an ancient book that unfortunately has a few pages in the wrong position, fortunately your computer has a list of every page number in order from ``1`` to ``n``. You're supplied with an array of numbers, and should return an array with each page number that is out of place. Incorrect page numbers will not appear next to each other. Duplicate incorrect page numbers are possible. Example: ```Given: list = [1,2,10,3,4,5,8,6,7] ``` ``Return: [10,8] `` Your returning list should have the incorrect page numbers in the order they were found.
def find_page_number(p): res = []; x = 1 for v in p: if v != x: res.append(v) else: x += 1 return res
def find_page_number(p): res = []; x = 1 for v in p: if v != x: res.append(v) else: x += 1 return res
train
APPS_structured
Given a matrix represented as a list of string, such as ``` ###..... ..###... ....###. .....### .....### ....###. ..###... ###..... ``` write a function ```if:javascript `rotateClockwise(matrix)` ``` ```if:ruby,python `rotate_clockwise(matrix)` ``` that return its 90° clockwise rotation, for our example: ``` #......# #......# ##....## .#....#. .##..##. ..####.. ..####.. ...##... ``` > /!\ You must return a **rotated copy** of `matrix`! (`matrix` must be the same before and after calling your function) > Note that the matrix isn't necessarily a square, though it's always a rectangle! > Please also note that the equality `m == rotateClockwise(rotateClockwise(rotateClockwise(rotateClockwise(m))));` (360° clockwise rotation), is not always true because `rotateClockwise([''])` => `[]` and `rotateClockwise(['','',''])` => `[]` (empty lines information is lost)
def rotate_clockwise(matrix): return [''.join(l)[::-1] for l in zip(*matrix)]
def rotate_clockwise(matrix): return [''.join(l)[::-1] for l in zip(*matrix)]
train
APPS_structured
Today Chef wants to evaluate the dishes of his $N$ students. He asks each one to cook a dish and present it to him. Chef loves his secret ingredient, and only likes dishes with at least $X$ grams of it. Given $N$, $X$ and the amount of secret ingredient used by each student $A_i$, find out whether Chef will like at least one dish. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - The first line of each testcase contains two integers $N$ (number of students) and $X$ (minimum amount of secret ingredient that a dish must contain for Chef to like it). - The next line contains $N$ space separated integers, $A_i$ denoting the amount of secret ingredient used by the students in their dishes. -----Output:----- For each testcase, print a single string "YES" if Chef likes at least one dish. Otherwise, print "NO". (Without quotes). -----Constraints:----- - $1 \leq T \leq 100$ - $1 \leq N \leq 1000$ - $1 \leq X \leq 1000000$ - $1 \leq A_i \leq 1000000$ -----Sample Input:----- 3 5 100 11 22 33 44 55 5 50 10 20 30 40 50 5 45 12 24 36 48 60 -----Sample Output:----- NO YES YES
# cook your dish here for _ in range(int(input())): n,x=map(int,input().split()) f=list(map(int,input().split())) d=0 for i in f: if i>=x: d=1 break if d==1: print("YES") else: print("NO")
# cook your dish here for _ in range(int(input())): n,x=map(int,input().split()) f=list(map(int,input().split())) d=0 for i in f: if i>=x: d=1 break if d==1: print("YES") else: print("NO")
train
APPS_structured
Given a string of integers, count how many times that integer repeats itself, then return a string showing the count and the integer. Example: `countMe('1123')` (`count_me` in Ruby) - Here 1 comes twice so `` will be `"21"` - then 2 comes once so `` will be `"12"` - then 3 comes once so `` will be `"13"` hence output string will be `"211213"`. Similarly `countMe('211213')` will return `'1221121113'` (1 time 2, 2 times 1, 1 time 2, 1 time 1, 1 time 3) Return `""` for empty, nil or non numeric strings
count_me = lambda s: (__import__("re").sub(r"(\d)\1*", lambda x: f"{len(x.group())}{x.group(1)}", s)) * s.isdigit()
count_me = lambda s: (__import__("re").sub(r"(\d)\1*", lambda x: f"{len(x.group())}{x.group(1)}", s)) * s.isdigit()
train
APPS_structured
Given the root of a binary tree, each node has a value from 0 to 25 representing the letters 'a' to 'z': a value of 0 represents 'a', a value of 1 represents 'b', and so on. Find the lexicographically smallest string that starts at a leaf of this tree and ends at the root. (As a reminder, any shorter prefix of a string is lexicographically smaller: for example, "ab" is lexicographically smaller than "aba".  A leaf of a node is a node that has no children.) Example 1: Input: [0,1,2,3,4,3,4] Output: "dba" Example 2: Input: [25,1,3,1,3,0,2] Output: "adz" Example 3: Input: [2,2,1,null,1,0,null,0] Output: "abc" Note: The number of nodes in the given tree will be between 1 and 8500. Each node in the tree will have a value between 0 and 25.
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right def helper(root: TreeNode) -> str: if root is None: return [\"\"] s = chr(ord('a') + root.val) if root.left is None and root.right is None: return [s] elif root.left is None: return [_ + s for _ in helper(root.right)] elif root.right is None: return [_ + s for _ in helper(root.left)] else: left = [_ + s for _ in helper(root.left)] right = [_ + s for _ in helper(root.right)] return left + right class Solution: def smallestFromLeaf(self, root: TreeNode) -> str: return min(helper(root))
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right def helper(root: TreeNode) -> str: if root is None: return [\"\"] s = chr(ord('a') + root.val) if root.left is None and root.right is None: return [s] elif root.left is None: return [_ + s for _ in helper(root.right)] elif root.right is None: return [_ + s for _ in helper(root.left)] else: left = [_ + s for _ in helper(root.left)] right = [_ + s for _ in helper(root.right)] return left + right class Solution: def smallestFromLeaf(self, root: TreeNode) -> str: return min(helper(root))
train
APPS_structured
Note : This question carries $100$ $points$ CodeLand is celebrating a festival by baking cakes! In order to avoid wastage, families follow a unique way of distributing cakes. For $T$ families in the locality, $i$-th family (1 <= $i$ <= $T$) has $N$ members. They baked $S$ slices of cakes. The smallest member of the family gets $K$ slices of cakes. Each family has a lucky number of $R$ and they agree to distribute the slices such that the member gets $R$ times more slices than the member just smaller than them. Since the family is busy in festival preparations, find out if the number of slices would be sufficient for the family or not. Also, find how many extra slices they have or how many slices are they short of. Also, the locality is kind and believes in sharing. So, you also need to determine if each family would have sufficient slices if families shared their cakes among each other! -----Input :----- - First line of input will have a single integer $T$ i.e. the number of families in the locality - For next $T$ lines, each line will describe one family through 4 integers i.e. $S$, $N$, $K$, $R$ separated by spaces -----Output----- - First $T$ lines of output will show if slices are enough for the family or not, followed by extra or required slices. For example, if slices are sufficient, the output would be $POSSIBLE$ $10$ which implies 10 slices are extra. If slices are insufficient, the output would be $IMPOSSIBLE$ $15$ which implies 15 slices are required to fulfill the requirement. - Last line of output would be $IMPOSSIBLE$ or $POSSIBLE$ depending on whether each family would get enough slices after sharing. -----Constraints:----- - 1 ≤ $T$ ≤ 50 - 1 ≤ $N$ ≤ 15 - 1 ≤ $S$ ≤ 10^9 - 1 ≤ $K$ ≤ 5 - 1 ≤ $R$ ≤ 5 -----Sample Input:----- 5 100 4 2 2 100 4 3 2 100 4 3 3 200 4 4 2 10 3 2 2 -----Sample Output:----- POSSIBLE 70 POSSIBLE 55 IMPOSSIBLE 20 POSSIBLE 140 IMPOSSIBLE 4 POSSIBLE -----Explanation----- For the first home, the youngest member has got 2 slices, the one older than them gets 2 times more slices, and so forth. So, first home needs 2 + 4 + 8 + 16 = 30 slices. But since they made 100, they have 70 extra, hence we print 'POSSIBLE 70'. Doing the same for other houses, we find 20 + 4 = 24 slices extra are required so that all families have enough slices. In this case we have 70 + 55 + 140 = 265 extra slices which is > 24, so we print 'POSSIBLE' in last line.
fam=int(input()) extra,req=0,0 for i in range(fam): s,n,k,r=list(map(int,input().split())) if r>1: sm=(k*(r**n-1))//(r-1) else: sm=k*n if sm<=s: print("POSSIBLE",s-sm) extra+=(s-sm) else: print("IMPOSSIBLE",abs(s-sm)) req+=(abs(s-sm)) #print(extra,req) if extra>=req: print("POSSIBLE") else: print("IMPOSSIBLE")
fam=int(input()) extra,req=0,0 for i in range(fam): s,n,k,r=list(map(int,input().split())) if r>1: sm=(k*(r**n-1))//(r-1) else: sm=k*n if sm<=s: print("POSSIBLE",s-sm) extra+=(s-sm) else: print("IMPOSSIBLE",abs(s-sm)) req+=(abs(s-sm)) #print(extra,req) if extra>=req: print("POSSIBLE") else: print("IMPOSSIBLE")
train
APPS_structured
Now we will confect a reagent. There are eight materials to choose from, numbered 1,2,..., 8 respectively. We know the rules of confect: ``` material1 and material2 cannot be selected at the same time material3 and material4 cannot be selected at the same time material5 and material6 must be selected at the same time material7 or material8 must be selected(at least one, or both) ``` # Task You are given a integer array `formula`. Array contains only digits 1-8 that represents material 1-8. Your task is to determine if the formula is valid. Returns `true` if it's valid, `false` otherwise. # Example For `formula = [1,3,7]`, The output should be `true`. For `formula = [7,1,2,3]`, The output should be `false`. For `formula = [1,3,5,7]`, The output should be `false`. For `formula = [1,5,6,7,3]`, The output should be `true`. For `formula = [5,6,7]`, The output should be `true`. For `formula = [5,6,7,8]`, The output should be `true`. For `formula = [6,7,8]`, The output should be `false`. For `formula = [7,8]`, The output should be `true`. # Note - All inputs are valid. Array contains at least 1 digit. Each digit appears at most once. - Happy Coding `^_^`
def isValid(formula): if 1 in formula and 2 in formula: return False if 3 in formula and 4 in formula: return False if 5 in formula and 6 not in formula: return False if 5 not in formula and 6 in formula: return False if 7 not in formula and 8 not in formula: return False return True
def isValid(formula): if 1 in formula and 2 in formula: return False if 3 in formula and 4 in formula: return False if 5 in formula and 6 not in formula: return False if 5 not in formula and 6 in formula: return False if 7 not in formula and 8 not in formula: return False return True
train
APPS_structured
Let's define a periodic infinite sequence S$S$ (0$0$-indexed) with period K$K$ using the formula Si=(i%K)+1$S_i = (i \% K) + 1$. Chef has found a sequence of positive integers A$A$ with length N$N$ buried underground. He suspects that it is a contiguous subsequence of some periodic sequence. Unfortunately, some elements of A$A$ are unreadable. Can you tell Chef the longest possible period K$K$ of an infinite periodic sequence which contains A$A$ (after suitably filling in the unreadable elements) as a contiguous subsequence? -----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 N$N$. - The second line contains N$N$ space-separated integers A1,A2,…,AN$A_1, A_2, \dots, A_N$. Unreadable elements are denoted by −1$-1$. -----Output----- For each test case, print a single line. - If the period can be arbitrarily large, this line should contain a single string "inf". - Otherwise, if A$A$ cannot be a contiguous subsequence of a periodic sequence, it should contain a single string "impossible". - Otherwise, it should contain a single integer — the maximum possible period. -----Constraints----- - 1≤T≤100$1 \le T \le 100$ - 2≤N≤105$2 \le N \le 10^5$ - the sum of N$N$ over all test cases does not exceed 106$10^6$ - for each valid i$i$, 1≤Ai≤106$1 \le A_i \le 10^6$ or Ai=−1$A_i = -1$ -----Subtasks----- Subtask #1 (50 points): - 2≤N≤1,000$2 \le N \le 1,000$ - the sum of N$N$ over all test cases does not exceed 10,000$10,000$ Subtask #2 (50 points): original constraints -----Example Input----- 3 3 -1 -1 -1 5 1 -1 -1 4 1 4 4 6 7 -1 -----Example Output----- inf 4 impossible
# cook your dish here from math import gcd for _ in range(int(input())): n,a,k,min_k,e = int(input()),[int(i) for i in input().split()],0,0,-1 for j in range(n): if(a[j] != -1):break for i in range(j,n): if min_k==0:min_k,e = a[i],a[i]+1 else: if min_k < a[i]:min_k = a[i] if(a[i] == -1):pass else: if(a[i] == e):pass else: if( k == 0):k = e-a[i] else: new_k = e-a[i] if(new_k < 0):k = -1 else:k = gcd(k,new_k) if(k<min_k or k<0): k = -1; break if k != 0 and a[i]!=-1: e = a[i]%k+1 else:e += 1 if(k == -1):print("impossible") elif k == 0 :print("inf") else:print(k)
# cook your dish here from math import gcd for _ in range(int(input())): n,a,k,min_k,e = int(input()),[int(i) for i in input().split()],0,0,-1 for j in range(n): if(a[j] != -1):break for i in range(j,n): if min_k==0:min_k,e = a[i],a[i]+1 else: if min_k < a[i]:min_k = a[i] if(a[i] == -1):pass else: if(a[i] == e):pass else: if( k == 0):k = e-a[i] else: new_k = e-a[i] if(new_k < 0):k = -1 else:k = gcd(k,new_k) if(k<min_k or k<0): k = -1; break if k != 0 and a[i]!=-1: e = a[i]%k+1 else:e += 1 if(k == -1):print("impossible") elif k == 0 :print("inf") else:print(k)
train
APPS_structured
Write a function `reverse` which reverses a list (or in clojure's case, any list-like data structure) (the dedicated builtin(s) functionalities are deactivated)
def reverse(lst): out = list() while lst: out.append(lst.pop(-1)) return out
def reverse(lst): out = list() while lst: out.append(lst.pop(-1)) return out
train
APPS_structured
# Task Given a square `matrix`, your task is to reverse the order of elements on both of its longest diagonals. The longest diagonals of a square matrix are defined as follows: * the first longest diagonal goes from the top left corner to the bottom right one; * the second longest diagonal goes from the top right corner to the bottom left one. # Example For the matrix ``` 1, 2, 3 4, 5, 6 7, 8, 9 ``` the output should be: ``` 9, 2, 7 4, 5, 6 3, 8, 1 ``` # Input/Output - `[input]` 2D integer array `matrix` Constraints: `1 ≤ matrix.length ≤ 10, matrix.length = matrix[i].length, 1 ≤ matrix[i][j] ≤ 1000` - `[output]` 2D integer array Matrix with the order of elements on its longest diagonals reversed.
def reverse_on_diagonals(matrix): # Modifies the matrix in place. Only way to get O(n) diag1 = [matrix[i][i] for i in range(len(matrix))] diag2 = [matrix[i][~i] for i in range(len(matrix))] for i, n in enumerate(reversed(diag1)): matrix[i][i] = n for i, n in enumerate(reversed(diag2)): matrix[i][~i] = n return matrix
def reverse_on_diagonals(matrix): # Modifies the matrix in place. Only way to get O(n) diag1 = [matrix[i][i] for i in range(len(matrix))] diag2 = [matrix[i][~i] for i in range(len(matrix))] for i, n in enumerate(reversed(diag1)): matrix[i][i] = n for i, n in enumerate(reversed(diag2)): matrix[i][~i] = n return matrix
train
APPS_structured
Zonal Computing Olympiad 2013, 10 Nov 2012 Little Red Riding Hood is carrying a basket with berries through the forest to her grandmother's house. The forest is arranged in the form of a square N × N grid of cells. The top left corner cell, where Little Red Riding Hood starts her journey, is numbered (1,1) and the bottom right corner cell, where her grandmother lives, is numbered (N,N). In each step, she can move either one position right or one position down. The forest is full of dangerous wolves and she is looking for a safe path to reach her destination. Little Red Riding Hood's fairy godmother has placed some special anti-wolf magical charms in some of the cells in the grid. Each charm has a strength. If the charm in cell (i,j) has strength k then its zone of influence is all the cells within k steps of (i,j); that is, all cells (i',j') such that |i - i'| + |j - j'| ≤ k. A cell within the zone of influence of a charm is safe from wolves. A safe path from (1,1) to (N,N) is one in which every cell along the path is safe. Little Red Riding Hood is carrying a basket with berries. In each cell, she drops some berries while pushing her way through the thick forest. However, sometimes she is also able to pick up fresh berries. Each cell is labelled with an integer that indicates the net change in the number of berries in her basket on passing through the cell; that is, the number of berries she picks up in that cell minus the number of berries she drops. You can assume that there are enough berries in her basket to start with so that the basket never becomes empty. Little Red Riding Hood knows the positions and strengths of all the magic charms and is looking for a safe path along which the number of berries she has in the basket when she reaches her grandmother's house is maximized. As an example consider the following grid: 3 3 2 4 3 2 1 -1 -2 2 -1 2 4 3 -3 -2 2 3 2 1 3 -1 2 -1 2 Suppose there are 3 magic charms, at position (1,2) with strength 2, at position (4,5) with strength 2 and one at position (4,2) with strength 1. The positions within the zone of influence of these three charms are indicated in the three grids below using X's. X X X X . . . . . . . . . . . X X X . . . . . . X . . . . . . X . . . . . . X X . X . . . . . . . . . . X X X X X X . . . . . . . . . . X X . X . . . Putting these together, the cells that are under the zone of influence of at least one charm are marked with X below. X X X X . X X X . X . X . X X X X X X X . X . X X Here are two examples of safe paths in this grid, marked using Y's. Y Y X X . Y X X X . X Y X . X Y Y X . X . Y . X X . Y . X X X Y Y Y Y X Y Y Y X . X . X Y . X . Y Y Along the first path, she accumulates 19 berries while on the second path she collects 16 berries. You can verify that among all safe paths, the maximum number of berries she can collect is 19. Your task is to help Little Red Riding Hood find out if there is at least one safe path and, if so, compute the maximum number of berries she can collect among all safe paths (which may be a negative number, in which case it is the minimum number of berries she will lose among all safe paths). -----Input format----- Line 1: Two space separated integers N and M, giving the dimension of the grid and the number of magic charms, respectively Lines 2 to N+1: These N lines desribe the grid. Line i+1 contains N space separated integers, describing the net change in berries in the N cells along row i of the grid. Lines N+2 to N+M+1: These M lines describe the magic charms. Each of these lines has 3 integers: the first two integers describe the position of the charm in the grid and the third integer describes its strength. -----Output format----- The first line of output must either consist of the word YES, if there are safe paths, or the word NO, if there are no safe paths. If the output on the first line is YES then the second line should contain a single integer giving the maximum number of berries Little Red Riding Hood can collect among all safe paths. -----Sample Input----- 5 3 3 3 2 4 3 2 1 -1 -2 2 -1 2 4 3 -3 -2 2 3 2 1 3 -1 2 -1 2 1 2 2 4 5 2 4 2 1 -----Sample Output----- YES 19 -----Test data----- In all subtasks, you may assume that 2 ≤ N ≤ 500. Each value on the grid is guaranteed to have absolute value not more than 1000. Let K denote the maximum strength among all the magic charms. - Subtask 1 (30 marks) : 1 ≤ M ≤ 10, 1 ≤ K ≤ 1,000. - Subtask 2 (70 marks) : 1 ≤ M ≤ 10,000, 1 ≤ K ≤ 10. -----Live evaluation data----- - Subtask 1: Testcases 0,1,2,3,4. - Subtask 2: Testcases 5,6,7,8.
n , m = map(int, input().split()) grid = [] grid_charm = [] cost = [] for i in range(n): hehe = [0 for jj in range(n)] maggi = [0 for jj in range(n)] row = list(map(int , input().split())) grid.append(row) grid_charm.append(hehe) cost.append(maggi) for i in range(m): x , y , k = map(int, input().split()) x , y = x-1 , y-1 for j in range(k+1): for z in range(k +1): if not j + z <= k: break alpha , beta , gamma, lol = x-j , y-z , x + j , y + z if alpha >=0: if beta >=0: grid_charm[alpha][beta] = 1 if lol < n: grid_charm[alpha][lol] = 1 if beta >= 0: if gamma < n: grid_charm[gamma][beta] = 1 if gamma < n: if lol < n: grid_charm[gamma][lol] = 1 # for i in grid_charm: # print(*i) cost[0][0] = grid[0][0] for i in range(n): for j in range(n): lol = -999999999999 if i > 0: if grid_charm[i-1][j] == 1 and cost[i-1][j] != -999999999999: lol = max(lol , grid[i][j] + cost[i-1][j]) if j > 0: if grid_charm[i][j-1] == 1 and cost[i][j-1] != -999999999999: lol = max(lol , grid[i][j] + cost[i][j-1]) if grid_charm[i][j] == 0: cost[i][j] = -999999999999 else: if not(i == 0 and j ==0): cost[i][j] = lol # for i in cost: # print(*i) if cost[n-1][n-1] == -999999999999: print('NO') else: print('YES') print(cost[n-1][n-1])
n , m = map(int, input().split()) grid = [] grid_charm = [] cost = [] for i in range(n): hehe = [0 for jj in range(n)] maggi = [0 for jj in range(n)] row = list(map(int , input().split())) grid.append(row) grid_charm.append(hehe) cost.append(maggi) for i in range(m): x , y , k = map(int, input().split()) x , y = x-1 , y-1 for j in range(k+1): for z in range(k +1): if not j + z <= k: break alpha , beta , gamma, lol = x-j , y-z , x + j , y + z if alpha >=0: if beta >=0: grid_charm[alpha][beta] = 1 if lol < n: grid_charm[alpha][lol] = 1 if beta >= 0: if gamma < n: grid_charm[gamma][beta] = 1 if gamma < n: if lol < n: grid_charm[gamma][lol] = 1 # for i in grid_charm: # print(*i) cost[0][0] = grid[0][0] for i in range(n): for j in range(n): lol = -999999999999 if i > 0: if grid_charm[i-1][j] == 1 and cost[i-1][j] != -999999999999: lol = max(lol , grid[i][j] + cost[i-1][j]) if j > 0: if grid_charm[i][j-1] == 1 and cost[i][j-1] != -999999999999: lol = max(lol , grid[i][j] + cost[i][j-1]) if grid_charm[i][j] == 0: cost[i][j] = -999999999999 else: if not(i == 0 and j ==0): cost[i][j] = lol # for i in cost: # print(*i) if cost[n-1][n-1] == -999999999999: print('NO') else: print('YES') print(cost[n-1][n-1])
train
APPS_structured
Correct this code so that it takes one argument, `x`, and returns "`x` is more than zero" if `x` is positive (and nonzero), and otherwise, returns "`x` is equal to or less than zero." In both cases, replace `x` with the actual value of `x`.
def corrections(x): return f"{x} is {'more' if x>0 else 'equal to or less'} than zero."
def corrections(x): return f"{x} is {'more' if x>0 else 'equal to or less'} than zero."
train
APPS_structured
You may be familiar with the concept of combinations: for example, if you take 5 cards from a 52 cards deck as you would playing poker, you can have a certain number (2,598,960, would you say?) of different combinations. In mathematics the number of *k* combinations you can have taking from a set of *n* elements is called the [binomial coefficient](https://en.wikipedia.org/wiki/Binomial_coefficient) of n and k, more popularly called **n choose k**. The formula to compute it is relatively simple: `n choose k`==`n!/(k!*(n-k)!)`, where `!` of course denotes the factorial operator. You are now to create a choose function that computes the binomial coefficient, like this: ``` choose(1,1)==1 choose(5,4)==5 choose(10,5)==252 choose(10,20)==0 choose(52,5)==2598960 ``` Be warned: a certain degree of optimization is expected, both to deal with larger numbers precision (and their rounding errors in languages like JS) and computing time.
def choose(n,k): def factorial(num): #a nested function for computing the factorial of the # n, k arguments of the choose function ra = reversed(list(range(1,num))) for r in ra: num = num * r return num # a little of exception handling and conditional reasoning # to make deal with edge cases involving negative values # and ZeroDivisionError try: choose = factorial(n)/(factorial(k)*factorial((n-k))) except ZeroDivisionError: choose = n/k if choose < 0: return 0 else: return choose
def choose(n,k): def factorial(num): #a nested function for computing the factorial of the # n, k arguments of the choose function ra = reversed(list(range(1,num))) for r in ra: num = num * r return num # a little of exception handling and conditional reasoning # to make deal with edge cases involving negative values # and ZeroDivisionError try: choose = factorial(n)/(factorial(k)*factorial((n-k))) except ZeroDivisionError: choose = n/k if choose < 0: return 0 else: return choose
train
APPS_structured
Create a function that transforms any positive number to a string representing the number in words. The function should work for all numbers between 0 and 999999. ### Examples ``` number2words(0) ==> "zero" number2words(1) ==> "one" number2words(9) ==> "nine" number2words(10) ==> "ten" number2words(17) ==> "seventeen" number2words(20) ==> "twenty" number2words(21) ==> "twenty-one" number2words(45) ==> "forty-five" number2words(80) ==> "eighty" number2words(99) ==> "ninety-nine" number2words(100) ==> "one hundred" number2words(301) ==> "three hundred one" number2words(799) ==> "seven hundred ninety-nine" number2words(800) ==> "eight hundred" number2words(950) ==> "nine hundred fifty" number2words(1000) ==> "one thousand" number2words(1002) ==> "one thousand two" number2words(3051) ==> "three thousand fifty-one" number2words(7200) ==> "seven thousand two hundred" number2words(7219) ==> "seven thousand two hundred nineteen" number2words(8330) ==> "eight thousand three hundred thirty" number2words(99999) ==> "ninety-nine thousand nine hundred ninety-nine" number2words(888888) ==> "eight hundred eighty-eight thousand eight hundred eighty-eight" ```
X = ("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen") Y = (None, None, "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety") def number2words(n): if n < 20: return X[n] if n < 100: return f"{Y[n//10]}-{X[n%10]}" if n%10 else Y[n//10] if n < 1000: return f"{X[n//100]} hundred{f' {number2words(n%100)}' if n%100 else ''}" return f"{number2words(n//1000)} thousand{f' {number2words(n%1000)}' if n%1000 else ''}"
X = ("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen") Y = (None, None, "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety") def number2words(n): if n < 20: return X[n] if n < 100: return f"{Y[n//10]}-{X[n%10]}" if n%10 else Y[n//10] if n < 1000: return f"{X[n//100]} hundred{f' {number2words(n%100)}' if n%100 else ''}" return f"{number2words(n//1000)} thousand{f' {number2words(n%1000)}' if n%1000 else ''}"
train
APPS_structured
You need to find the largest value in each row of a binary tree. Example: Input: 1 / \ 3 2 / \ \ 5 3 9 Output: [1, 3, 9]
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def largestValues(self, root): """ :type root: TreeNode :rtype: List[int] """ level = [] if root == None: return [] level.append(root) ans = [] while len(level) != 0: level_max = float("-inf") next_level = [] while len(level) != 0: cur_node = level.pop(0) level_max = max(cur_node.val, level_max) if cur_node.left != None: next_level.append(cur_node.left) if cur_node.right != None: next_level.append(cur_node.right) ans.append(level_max) level = next_level return ans
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def largestValues(self, root): """ :type root: TreeNode :rtype: List[int] """ level = [] if root == None: return [] level.append(root) ans = [] while len(level) != 0: level_max = float("-inf") next_level = [] while len(level) != 0: cur_node = level.pop(0) level_max = max(cur_node.val, level_max) if cur_node.left != None: next_level.append(cur_node.left) if cur_node.right != None: next_level.append(cur_node.right) ans.append(level_max) level = next_level return ans
train
APPS_structured
Given a string representing a code snippet, you need to implement a tag validator to parse the code and return whether it is valid. A code snippet is valid if all the following rules hold: The code must be wrapped in a valid closed tag. Otherwise, the code is invalid. A closed tag (not necessarily valid) has exactly the following format : <TAG_NAME>TAG_CONTENT</TAG_NAME>. Among them, <TAG_NAME> is the start tag, and </TAG_NAME> is the end tag. The TAG_NAME in start and end tags should be the same. A closed tag is valid if and only if the TAG_NAME and TAG_CONTENT are valid. A valid TAG_NAME only contain upper-case letters, and has length in range [1,9]. Otherwise, the TAG_NAME is invalid. A valid TAG_CONTENT may contain other valid closed tags, cdata and any characters (see note1) EXCEPT unmatched <, unmatched start and end tag, and unmatched or closed tags with invalid TAG_NAME. Otherwise, the TAG_CONTENT is invalid. A start tag is unmatched if no end tag exists with the same TAG_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested. A < is unmatched if you cannot find a subsequent >. And when you find a < or </, all the subsequent characters until the next > should be parsed as TAG_NAME (not necessarily valid). The cdata has the following format : <![CDATA[CDATA_CONTENT]]>. The range of CDATA_CONTENT is defined as the characters between <![CDATA[ and the first subsequent ]]>. CDATA_CONTENT may contain any characters. The function of cdata is to forbid the validator to parse CDATA_CONTENT, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as regular characters. Valid Code Examples: Input: "<DIV>This is the first line <![CDATA[<div>]]></DIV>" Output: True Explanation: The code is wrapped in a closed tag : <DIV> and </DIV>. The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. Although CDATA_CONTENT has unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as tag. So TAG_CONTENT is valid, and then the code is valid. Thus return true. Input: "<DIV>>> ![cdata[]] <![CDATA[<div>]>]]>]]>>]</DIV>" Output: True Explanation: We first separate the code into : start_tag|tag_content|end_tag. start_tag -> "<DIV>" end_tag -> "</DIV>" tag_content could also be separated into : text1|cdata|text2. text1 -> ">> ![cdata[]] " cdata -> "<![CDATA[<div>]>]]>", where the CDATA_CONTENT is "<div>]>" text2 -> "]]>>]" The reason why start_tag is NOT "<DIV>>>" is because of the rule 6. The reason why cdata is NOT "<![CDATA[<div>]>]]>]]>" is because of the rule 7. Invalid Code Examples: Input: "<A> <B> </A> </B>" Output: False Explanation: Unbalanced. If "<A>" is closed, then "<B>" must be unmatched, and vice versa. Input: "<DIV> div tag is not closed <DIV>" Output: False Input: "<DIV> unmatched < </DIV>" Output: False Input: "<DIV> closed tags with invalid tag name <b>123</b> </DIV>" Output: False Input: "<DIV> unmatched tags with invalid tag name </1234567890> and <CDATA[[]]> </DIV>" Output: False Input: "<DIV> unmatched start tag <B> and unmatched end tag </C> </DIV>" Output: False Note: For simplicity, you could assume the input code (including the any characters mentioned above) only contain letters, digits, '<','>','/','!','[',']' and ' '.
class Solution: def isValid(self, code): """ :type code: str :rtype: bool """ S=code CDATA_BEGIN='![CDATA[' CDATA_END=']]>' def collect_tag(i): for j in range(i,len(S)): if S[j]=='>': break else: return None return S[i+1:j] def valid_tag(tag): if 1<=len(tag)<=9 and all('A' <=c<= 'Z' for c in tag): return True else: return False if not S or S[0]!='<': return False #print('###########1111############') tag=collect_tag(0) #print(tag) if not tag or not S.startswith('<{}>'.format(tag)) or not S.endswith('</{}>'.format(tag)) or not valid_tag(tag): return False S=S[len(tag)+2:-len(tag)-3] i=0 stack=[] while i<len(S): if S[i]=='<': tag=collect_tag(i) #print(tag) if not tag: return False if tag.startswith(CDATA_BEGIN): while i<len(S) and S[i:i+3]!=CDATA_END: i+=1 if S[i:i+3]!=CDATA_END: return False i+=2 elif tag.startswith('/'): tag=tag[1:] if not valid_tag(tag) or not stack or stack.pop()!=tag: return False else: if not valid_tag(tag): return False stack.append(tag) i+=1 return not stack
class Solution: def isValid(self, code): """ :type code: str :rtype: bool """ S=code CDATA_BEGIN='![CDATA[' CDATA_END=']]>' def collect_tag(i): for j in range(i,len(S)): if S[j]=='>': break else: return None return S[i+1:j] def valid_tag(tag): if 1<=len(tag)<=9 and all('A' <=c<= 'Z' for c in tag): return True else: return False if not S or S[0]!='<': return False #print('###########1111############') tag=collect_tag(0) #print(tag) if not tag or not S.startswith('<{}>'.format(tag)) or not S.endswith('</{}>'.format(tag)) or not valid_tag(tag): return False S=S[len(tag)+2:-len(tag)-3] i=0 stack=[] while i<len(S): if S[i]=='<': tag=collect_tag(i) #print(tag) if not tag: return False if tag.startswith(CDATA_BEGIN): while i<len(S) and S[i:i+3]!=CDATA_END: i+=1 if S[i:i+3]!=CDATA_END: return False i+=2 elif tag.startswith('/'): tag=tag[1:] if not valid_tag(tag) or not stack or stack.pop()!=tag: return False else: if not valid_tag(tag): return False stack.append(tag) i+=1 return not stack
train
APPS_structured
Chef has come to a 2 dimensional garden in which there are N points. Each point has coordinates (x, y), where x can either be 1 or 2 or 3. Chef will now choose every triplet of these N points and make a triangle from it. You need to tell the sum of areas of all the triangles the Chef makes. Note that some of the triplets might not form proper triangles, and would end up as a line or a point (ie. degenerate), but that is fine because their area will be zero. -----Input----- - The first line contains a single integer T, the number of test cases. The description of each testcase follows. - The first line of each test case contains an integer N denoting the number of points on the plane. - The next N lines contain 2 space separated integers x and y denoting the coordinates of the points. -----Output----- For each test case, output a single line containing the answer. Your answer will be considered correct if the absolute error is less than or equal to 10-2. -----Constraints----- - 1 ≤ T ≤ 20 - 1 ≤ N ≤ 2000 - 1 ≤ x ≤ 3 - 1 ≤ y ≤106 - All (x, y) pairs are distinct -----Example----- Input: 2 3 1 1 2 1 3 3 4 1 1 2 2 2 1 3 3 Output: 1.0 2.0 -----Explanation:----- Test Case 1: There is only one triangle which has non-zero area, and it's area is 1, hence the output. Test Case 2: Let the points be A(1,1), B(2,2), C(2,1), D(3,3). There are 3 non degenerate triangles possible. - area ABC = 0.5 - area BCD = 0.5 - area ACD = 1 Total area = 2
# Author: Dancing Monkey | Created: 09.DEC.2018 import bisect for _ in range(int(input())): n = int(input()) x1 , x2, x3 = [], [], [] for i in range(n): x, y = list(map(int, input().split())) if x == 1: x1.append(y) if x == 2: x2.append(y) if x == 3: x3.append(y) x1.sort() x2.sort() x3.sort() y1, y2, y3 = len(x1), len(x2), len(x3) area = 0 for i in range(y1): for j in range(i+1, y1): area += abs(x1[i] - x1[j])*(y2 + (2*y3)) for i in range(y3): for j in range(i+1, y3): area += abs(x3[i] - x3[j])*(y2 + (2*y1)) for i in range(y2): for j in range(i+1, y2): area += abs(x2[i] - x2[j])*(y1 + y3) area /= 2 s1 = [0] for i in range(y2): s1.append(s1[-1] + x2[i]) # print(s1) s2 = [0] for i in range(y2):s2.append(s2[-1] + x2[y2 - 1 - i]) # print(s2) for i in x1: for j in x3: p1 = (i + j) / 2 p = bisect.bisect_left(x2, p1) # print('p', p) l = p h = y2 - l # print(l, h) area += p1*(l) - s1[l] # print('dfg', area) area += s2[h] - p1*(h) print(format(area, 'f')) # print()
# Author: Dancing Monkey | Created: 09.DEC.2018 import bisect for _ in range(int(input())): n = int(input()) x1 , x2, x3 = [], [], [] for i in range(n): x, y = list(map(int, input().split())) if x == 1: x1.append(y) if x == 2: x2.append(y) if x == 3: x3.append(y) x1.sort() x2.sort() x3.sort() y1, y2, y3 = len(x1), len(x2), len(x3) area = 0 for i in range(y1): for j in range(i+1, y1): area += abs(x1[i] - x1[j])*(y2 + (2*y3)) for i in range(y3): for j in range(i+1, y3): area += abs(x3[i] - x3[j])*(y2 + (2*y1)) for i in range(y2): for j in range(i+1, y2): area += abs(x2[i] - x2[j])*(y1 + y3) area /= 2 s1 = [0] for i in range(y2): s1.append(s1[-1] + x2[i]) # print(s1) s2 = [0] for i in range(y2):s2.append(s2[-1] + x2[y2 - 1 - i]) # print(s2) for i in x1: for j in x3: p1 = (i + j) / 2 p = bisect.bisect_left(x2, p1) # print('p', p) l = p h = y2 - l # print(l, h) area += p1*(l) - s1[l] # print('dfg', area) area += s2[h] - p1*(h) print(format(area, 'f')) # print()
train
APPS_structured
You have unweighted tree of $n$ vertices. You have to assign a positive weight to each edge so that the following condition would hold: For every two different leaves $v_{1}$ and $v_{2}$ of this tree, bitwise XOR of weights of all edges on the simple path between $v_{1}$ and $v_{2}$ has to be equal to $0$. Note that you can put very large positive integers (like $10^{(10^{10})}$). It's guaranteed that such assignment always exists under given constraints. Now let's define $f$ as the number of distinct weights in assignment. [Image] In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is $0$. $f$ value is $2$ here, because there are $2$ distinct edge weights($4$ and $5$). [Image] In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex $1$ and vertex $6$ ($3, 4, 5, 4$) is not $0$. What are the minimum and the maximum possible values of $f$ for the given tree? Find and print both. -----Input----- The first line contains integer $n$ ($3 \le n \le 10^{5}$) — the number of vertices in given tree. The $i$-th of the next $n-1$ lines contains two integers $a_{i}$ and $b_{i}$ ($1 \le a_{i} \lt b_{i} \le n$) — it means there is an edge between $a_{i}$ and $b_{i}$. It is guaranteed that given graph forms tree of $n$ vertices. -----Output----- Print two integers — the minimum and maximum possible value of $f$ can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints. -----Examples----- Input 6 1 3 2 3 3 4 4 5 5 6 Output 1 4 Input 6 1 3 2 3 3 4 4 5 4 6 Output 3 3 Input 7 1 2 2 7 3 4 4 7 5 6 6 7 Output 1 6 -----Note----- In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum. [Image] In the second example, possible assignments for each minimum and maximum are described in picture below. The $f$ value of valid assignment of this tree is always $3$. [Image] In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum. [Image]
n = int(input()) g = [[] for i in range(n)] for i in range(n-1): u,v = [int(i)-1 for i in input().split()] g[u].append(v) g[v].append(u) leaf = [len(i)==1 for i in g] root = -1 mx = n-1 for i in range(n): if leaf[i]: root = i leafs = 0 for j in g[i]: if leaf[j]: leafs += 1 if leafs > 1: mx -= leafs-1 stack = [(root, -1, 0)] even = True while len(stack)>0: i, j, d = stack.pop() if leaf[i] and d%2 == 1: even = False break for k in g[i]: if k != j: stack.append((k,i,d+1)) mn = 1 if even else 3 print(mn,mx)
n = int(input()) g = [[] for i in range(n)] for i in range(n-1): u,v = [int(i)-1 for i in input().split()] g[u].append(v) g[v].append(u) leaf = [len(i)==1 for i in g] root = -1 mx = n-1 for i in range(n): if leaf[i]: root = i leafs = 0 for j in g[i]: if leaf[j]: leafs += 1 if leafs > 1: mx -= leafs-1 stack = [(root, -1, 0)] even = True while len(stack)>0: i, j, d = stack.pop() if leaf[i] and d%2 == 1: even = False break for k in g[i]: if k != j: stack.append((k,i,d+1)) mn = 1 if even else 3 print(mn,mx)
train
APPS_structured
Positive integers have so many gorgeous features. Some of them could be expressed as a sum of two or more consecutive positive numbers. ___ # Consider an Example : * `10` , could be expressed as a sum of `1 + 2 + 3 + 4 `. ___ # Task **_Given_** *Positive integer*, N , **_Return_** true if it could be expressed as a sum of two or more consecutive positive numbers , OtherWise return false . ___ # Notes ~~~if-not:clojure,csharp,java * Guaranteed constraint : **_2 ≤ N ≤ (2^32) -1_** . ~~~ ~~~if:clojure,csharp,java * Guaranteed constraint : **_2 ≤ N ≤ (2^31) -1_** . ~~~ ___ # Input >> Output Examples: ___ ___ ___ # [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) # [Bizarre Sorting-katas](https://www.codewars.com/collections/bizarre-sorting-katas) # [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored) ___ ## ALL translations are welcomed ## Enjoy Learning !! # Zizou
def consecutive_ducks(n): while n % 2 == 0: n //= 2 return n > 1
def consecutive_ducks(n): while n % 2 == 0: n //= 2 return n > 1
train
APPS_structured
We have a matrix of integers with m rows and n columns. We want to calculate the total sum for the matrix: As you can see, the name "alternating sum" of the title is due to the sign of the terms that changes from one term to its contiguous one and so on. Let's see an example: ``` matrix = [[1, 2, 3], [-3, -2, 1], [3, - 1, 2]] total_sum = (1 - 2 + 3) + [-(-3) + (-2) - 1] + [3 - (-1) + 2] = 2 + 0 + 6 = 8 ``` You may be given matrixes with their dimensions between these values:```10 < m < 300``` and ```10 < n < 300```. More example cases in the Example Test Cases. Enjoy it!!
def score_matrix(matrix): total_sum = 0 for (x,row) in enumerate(matrix): for (y, v) in enumerate(row): total_sum += v * (1 if (x+y)%2 == 0 else -1) return total_sum
def score_matrix(matrix): total_sum = 0 for (x,row) in enumerate(matrix): for (y, v) in enumerate(row): total_sum += v * (1 if (x+y)%2 == 0 else -1) return total_sum
train
APPS_structured
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, one integer $K$. -----Output:----- For each test case, output as the pattern. -----Constraints----- - $1 \leq T \leq 50$ - $1 \leq K \leq 50$ -----Sample Input:----- 5 1 2 3 4 5 -----Sample Output:----- 1 1 23 1 23 456 1 23 4 5 6789 1 23 4 5 6 7 89101112 -----EXPLANATION:----- No need, else pattern can be decode easily.
# cook your dish here # cook your dish here def solve(): n = int(input()) #n,m = input().split() #n = int(n) #m = int(m) #s = input() #a = list(map(int, input().split())) it = 1 k=1 for i in range(n): j=0 while j<it: mark=1 if (i==n-1 or (j==0 or j==it-1) ): print(k,end="") k+=1 else: print(" ",end="") # continue j+=1 print("") it+=1 def __starting_point(): T = int(input()) for i in range(T): #a = solve() #n = len(a) #for i in range(n): # if i==n-1 : print(a[i]) # else: print(a[i],end=" ") (solve()) __starting_point()
# cook your dish here # cook your dish here def solve(): n = int(input()) #n,m = input().split() #n = int(n) #m = int(m) #s = input() #a = list(map(int, input().split())) it = 1 k=1 for i in range(n): j=0 while j<it: mark=1 if (i==n-1 or (j==0 or j==it-1) ): print(k,end="") k+=1 else: print(" ",end="") # continue j+=1 print("") it+=1 def __starting_point(): T = int(input()) for i in range(T): #a = solve() #n = len(a) #for i in range(n): # if i==n-1 : print(a[i]) # else: print(a[i],end=" ") (solve()) __starting_point()
train
APPS_structured
Define a function that takes one integer argument and returns logical value `true` or `false` depending on if the integer is a prime. Per Wikipedia, a prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. ## Requirements * You can assume you will be given an integer input. * You can not assume that the integer will be only positive. You may be given negative numbers as well (or `0`). * **NOTE on performance**: There are no fancy optimizations required, but still *the* most trivial solutions might time out. Numbers go up to 2^31 (or similar, depends on language version). Looping all the way up to `n`, or `n/2`, will be too slow. ## Example ```nasm mov edi, 1 call is_prime ; EAX <- 0 (false) mov edi, 2 call is_prime ; EAX <- 1 (true) mov edi, -1 call is_prime ; EAX <- 0 (false) ```
# This is the Miller-Rabin test for primes, which works for super large n import random def even_odd(n): s, d = 0, n while d % 2 == 0: s += 1 d >>= 1 return s, d def Miller_Rabin(a, p): s, d = even_odd(p-1) a = pow(a, d, p) if a == 1: return True for i in range(s): if a == p-1: return True a = pow(a, 2, p) return False def is_prime(p): if p == 2: return True if p <= 1 or p % 2 == 0: return False return all(Miller_Rabin(random.randint(2,p-1),p) for _ in range(40))
# This is the Miller-Rabin test for primes, which works for super large n import random def even_odd(n): s, d = 0, n while d % 2 == 0: s += 1 d >>= 1 return s, d def Miller_Rabin(a, p): s, d = even_odd(p-1) a = pow(a, d, p) if a == 1: return True for i in range(s): if a == p-1: return True a = pow(a, 2, p) return False def is_prime(p): if p == 2: return True if p <= 1 or p % 2 == 0: return False return all(Miller_Rabin(random.randint(2,p-1),p) for _ in range(40))
train
APPS_structured
Given a valid (IPv4) IP address, return a defanged version of that IP address. A defanged IP address replaces every period "." with "[.]". Example 1: Input: address = "1.1.1.1" Output: "1[.]1[.]1[.]1" Example 2: Input: address = "255.100.50.0" Output: "255[.]100[.]50[.]0" Constraints: The given address is a valid IPv4 address.
class Solution: def defangIPaddr(self, address: str) -> str: return '[.]'.join(address.split('.'))
class Solution: def defangIPaddr(self, address: str) -> str: return '[.]'.join(address.split('.'))
train
APPS_structured
A lot of goods have an International Article Number (formerly known as "European Article Number") abbreviated "EAN". EAN is a 13-digits barcode consisting of 12-digits data followed by a single-digit checksum (EAN-8 is not considered in this kata). The single-digit checksum is calculated as followed (based upon the 12-digit data): The digit at the first, third, fifth, etc. position (i.e. at the odd position) has to be multiplied with "1". The digit at the second, fourth, sixth, etc. position (i.e. at the even position) has to be multiplied with "3". Sum these results. If this sum is dividable by 10, the checksum is 0. Otherwise the checksum has the following formula: checksum = 10 - (sum mod 10) For example, calculate the checksum for "400330101839" (= 12-digits data): 4·1 + 0·3 + 0·1 + 3·3 + 3·1 + 0·3 + 1·1 + 0·3 + 1·1 + 8·3 + 3·1 + 9·3 = 4 + 0 + 0 + 9 + 3 + 0 + 1 + 0 + 1 + 24 + 3 + 27 = 72 10 - (72 mod 10) = 8 ⇒ Checksum: 8 Thus, the EAN-Code is 4003301018398 (= 12-digits data followed by single-digit checksum). Your Task Validate a given EAN-Code. Return true if the given EAN-Code is valid, otherwise false. Assumption You can assume the given code is syntactically valid, i.e. it only consists of numbers and it exactly has a length of 13 characters. Examples ```python validate_ean("4003301018398") # => True validate_ean("4003301018392") # => False ``` Good Luck and have fun.
def validate_ean(code): data, last = code[:12], int(code[12]) checksum = -sum(int(d) * 3**(i % 2) for i, d in enumerate(data)) % 10 return last == checksum
def validate_ean(code): data, last = code[:12], int(code[12]) checksum = -sum(int(d) * 3**(i % 2) for i, d in enumerate(data)) % 10 return last == checksum
train
APPS_structured
Each test case will generate a variable whose value is 777. Find the name of the variable.
find_variable = lambda: next(var for var, val in globals().items() if val == 777)
find_variable = lambda: next(var for var, val in globals().items() if val == 777)
train
APPS_structured