input
stringlengths
50
13.9k
output_program
stringlengths
5
655k
output_answer
stringlengths
5
655k
split
stringclasses
1 value
dataset
stringclasses
1 value
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
def is_uppercase(inp): return not set(inp) & set('abcdefghijklmnopqrstuvwxyz')
def is_uppercase(inp): return not set(inp) & set('abcdefghijklmnopqrstuvwxyz')
train
APPS_structured
You are given an array $a$ of $n$ integers. You want to make all elements of $a$ equal to zero by doing the following operation exactly three times: Select a segment, for each number in this segment we can add a multiple of $len$ to it, where $len$ is the length of this segment (added integers can be different). It can be proven that it is always possible to make all elements of $a$ equal to zero. -----Input----- The first line contains one integer $n$ ($1 \le n \le 100\,000$): the number of elements of the array. The second line contains $n$ elements of an array $a$ separated by spaces: $a_1, a_2, \dots, a_n$ ($-10^9 \le a_i \le 10^9$). -----Output----- The output should contain six lines representing three operations. For each operation, print two lines: The first line contains two integers $l$, $r$ ($1 \le l \le r \le n$): the bounds of the selected segment. The second line contains $r-l+1$ integers $b_l, b_{l+1}, \dots, b_r$ ($-10^{18} \le b_i \le 10^{18}$): the numbers to add to $a_l, a_{l+1}, \ldots, a_r$, respectively; $b_i$ should be divisible by $r - l + 1$. -----Example----- Input 4 1 3 2 4 Output 1 1 -1 3 4 4 2 2 4 -3 -6 -6
n=int(input()) a=list(map(int,input().split())) if n!=1: print(n,n) print(-a[-1]) print(1,n-1) res_2 = [a[i]*(n-1) for i in range(n-1)] print(*res_2) print(1,n) res_3 = [-a[i]*n for i in range(n)] res_3[-1] = 0 print(*res_3) else: print(1,1) print(-a[0]) print(1,1) print(0) print(1,1) print(0)
n=int(input()) a=list(map(int,input().split())) if n!=1: print(n,n) print(-a[-1]) print(1,n-1) res_2 = [a[i]*(n-1) for i in range(n-1)] print(*res_2) print(1,n) res_3 = [-a[i]*n for i in range(n)] res_3[-1] = 0 print(*res_3) else: print(1,1) print(-a[0]) print(1,1) print(0) print(1,1) print(0)
train
APPS_structured
Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present. Examples: spinWords( "Hey fellow warriors" ) => returns "Hey wollef sroirraw" spinWords( "This is a test") => returns "This is a test" spinWords( "This is another test" )=> returns "This is rehtona test"
def spin_words(sentence): # Your code goes here return " ".join([x[::-1] if len(x) >= 5 else x for x in sentence.split(" ")])
def spin_words(sentence): # Your code goes here return " ".join([x[::-1] if len(x) >= 5 else x for x in sentence.split(" ")])
train
APPS_structured
The number 81 has a special property, a certain power of the sum of its digits is equal to 81 (nine squared). Eighty one (81), is the first number in having this property (not considering numbers of one digit). The next one, is 512. Let's see both cases with the details 8 + 1 = 9 and 9^(2) = 81 512 = 5 + 1 + 2 = 8 and 8^(3) = 512 We need to make a function, ```power_sumDigTerm()```, that receives a number ```n``` and may output the ```n-th term``` of this sequence of numbers. The cases we presented above means that power_sumDigTerm(1) == 81 power_sumDigTerm(2) == 512 Happy coding!
def power_sumDigTerm(n): def sum_d(x): L = [int(d) for d in str(x)] res = 0 for l in L: res = res + l return res r_list = [] for j in range(2, 50): for i in range(7, 100): a = i**j if sum_d(a) == i: r_list.append(a) r_list = list(set(r_list)) r_list = sorted((r_list)) return r_list[n-1]
def power_sumDigTerm(n): def sum_d(x): L = [int(d) for d in str(x)] res = 0 for l in L: res = res + l return res r_list = [] for j in range(2, 50): for i in range(7, 100): a = i**j if sum_d(a) == i: r_list.append(a) r_list = list(set(r_list)) r_list = sorted((r_list)) return r_list[n-1]
train
APPS_structured
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string). Examples: ```python solution('abc', 'bc') # returns true solution('abc', 'd') # returns false ```
solution=str.endswith # Easy peasy
solution=str.endswith # Easy peasy
train
APPS_structured
Write a function that when given a URL as a string, parses out just the domain name and returns it as a string. For example: ```python domain_name("http://github.com/carbonfive/raygun") == "github" domain_name("http://www.zombie-bites.com") == "zombie-bites" domain_name("https://www.cnet.com") == "cnet" ```
import re def domain_name(url): pattern = "[\-\.a-z0-9]+|www.[\-a-z0-9]+\." string = re.findall(pattern, url) string = string[1 if len(string) > 1 and 'http' in string[0] else 0] return re.sub("www\.|\/\/|\.[\.a-z]+$|\.", "", string)
import re def domain_name(url): pattern = "[\-\.a-z0-9]+|www.[\-a-z0-9]+\." string = re.findall(pattern, url) string = string[1 if len(string) > 1 and 'http' in string[0] else 0] return re.sub("www\.|\/\/|\.[\.a-z]+$|\.", "", string)
train
APPS_structured
Chef has an old machine if the chef enters any natural number, the machine will display 1, 2, …n, n-1, n-2, n-3,…1 series and in next line prints sum of cubes of each number in the series. Chef wants to create a computer program which can replicate the functionality of the machine. Help the chef to code. -----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. -----Constraints----- - $1 \leq T \leq 50$ - $1 \leq N \leq 50$ -----Sample Input:----- 2 1 3 -----Sample Output:----- 1 45 -----EXPLANATION:----- For 2) series will be 1, 2, 3, 2, 1 and the sum will be = 1 + 8 + 27 + 8+ 1
t=int(input()) while(t!=0): t=t-1 n=int(input()) ans=0 for i in range(1,n+1,1): sum=0; for j in range(1,i+1,1): sum=sum+j s=sum-i sum=sum+s if(i!=n): ans=ans+2*sum*i else: ans=ans+sum*i print(ans)
t=int(input()) while(t!=0): t=t-1 n=int(input()) ans=0 for i in range(1,n+1,1): sum=0; for j in range(1,i+1,1): sum=sum+j s=sum-i sum=sum+s if(i!=n): ans=ans+2*sum*i else: ans=ans+sum*i print(ans)
train
APPS_structured
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. The update(i, val) function modifies nums by updating the element at index i to val. Example: Given nums = [1, 3, 5] sumRange(0, 2) -> 9 update(1, 2) sumRange(0, 2) -> 8 Note: The array is only modifiable by the update function. You may assume the number of calls to update and sumRange function is distributed evenly.
from math import sqrt class NumArray(object): def __init__(self, nums): """ :type nums: List[int] """ if nums: k=int(sqrt(len(nums))) add,i=[],0 while i<=len(nums)-k: add.append(sum(nums[i:i+k])) i+=k if i!=len(nums): add.append(sum(nums[i:])) self.nums,self.add,self.k=nums,add,k def update(self, i, val): """ :type i: int :type val: int :rtype: void """ self.add[i//self.k]+=val-self.nums[i] self.nums[i]=val def sumRange(self, i, j): """ :type i: int :type j: int :rtype: int """ def func(i): return sum(self.add[:i//self.k])+sum(self.nums[(i//self.k)*self.k:i+1]) if i>=0 else 0 return func(j)-func(i-1) # Your NumArray object will be instantiated and called as such: # obj = NumArray(nums) # obj.update(i,val) # param_2 = obj.sumRange(i,j)
from math import sqrt class NumArray(object): def __init__(self, nums): """ :type nums: List[int] """ if nums: k=int(sqrt(len(nums))) add,i=[],0 while i<=len(nums)-k: add.append(sum(nums[i:i+k])) i+=k if i!=len(nums): add.append(sum(nums[i:])) self.nums,self.add,self.k=nums,add,k def update(self, i, val): """ :type i: int :type val: int :rtype: void """ self.add[i//self.k]+=val-self.nums[i] self.nums[i]=val def sumRange(self, i, j): """ :type i: int :type j: int :rtype: int """ def func(i): return sum(self.add[:i//self.k])+sum(self.nums[(i//self.k)*self.k:i+1]) if i>=0 else 0 return func(j)-func(i-1) # Your NumArray object will be instantiated and called as such: # obj = NumArray(nums) # obj.update(i,val) # param_2 = obj.sumRange(i,j)
train
APPS_structured
Given a string s and an integer k. You should construct k non-empty palindrome strings using all the characters in s. Return True if you can use all the characters in s to construct k palindrome strings or False otherwise. Example 1: Input: s = "annabelle", k = 2 Output: true Explanation: You can construct two palindromes using all characters in s. Some possible constructions "anna" + "elble", "anbna" + "elle", "anellena" + "b" Example 2: Input: s = "leetcode", k = 3 Output: false Explanation: It is impossible to construct 3 palindromes using all the characters of s. Example 3: Input: s = "true", k = 4 Output: true Explanation: The only possible solution is to put each character in a separate string. Example 4: Input: s = "yzyzyzyzyzyzyzy", k = 2 Output: true Explanation: Simply you can put all z's in one string and all y's in the other string. Both strings will be palindrome. Example 5: Input: s = "cr", k = 7 Output: false Explanation: We don't have enough characters in s to construct 7 palindromes. Constraints: 1 <= s.length <= 10^5 All characters in s are lower-case English letters. 1 <= k <= 10^5
class Solution: def canConstruct(self, s: str, k: int) -> bool: c = Counter(s) return sum(c.values()) >= k and len([v for v in c.values() if v % 2]) <= k
class Solution: def canConstruct(self, s: str, k: int) -> bool: c = Counter(s) return sum(c.values()) >= k and len([v for v in c.values() if v % 2]) <= k
train
APPS_structured
Chef Shifu wanted to celebrate the success of his new restaurant with all his employees. He was willing to host a party and he had decided the location of the party as well. However, Chef Shifu was a shy person and wanted to communicate with the least possible employees to inform them about the party, and that these employees could inform their friends. Note that an employee could only inform his/her immediate friends about the party, not his/her friends’ friends. Chef Shifu has a list of all the friendships among his employees. Help him find the minimum number of employees he should inform, so that every employee knows about the celebration party. -----Input----- First line contains a single integer T - the total number of testcases. T testcases follow. For each testcase: The first line contains 2 space-separated integers N and M - the total number of employees working under Chef Shifu and the number of friendship relations. M lines follow - each line contains 2 space-separated integers u and v, indicating that employee u is a friend of employee v and vice-versa. The employees are numbered from 1 to N, and each employee is assigned a distinct integer. -----Output----- For each testcase, print the minimum number of employees to be informed on a new line. -----Constraints----- Subtask 1: 5 points 1 ≤ T ≤ 5 1 ≤ N ≤ 4 0 ≤ M ≤ N*(N-1)/2 Subtask 2: 35 points 1 ≤ T ≤ 5 1 ≤ N ≤ 15 0 ≤ M ≤ N*(N-1)/2 Subtask 3: 60 points 1 ≤ T ≤ 5 1 ≤ N ≤ 20 0 ≤ M ≤ N*(N-1)/2 -----Example----- Input 2 3 3 1 2 2 3 1 3 4 3 1 2 2 3 3 4 Output 1 2 Explanation In testcase 1, since every employee is a friend of every other employee, we just need to select 1 employee. In testcase 2, selecting employees 2 and 4 would ensure that all 4 employees are represented. Similarly, selecting employees 1 and 3 would also ensure that all 4 employees are selected. In both cases, we must select 2 employees in the best case.
t=int(input()) for _ in range(t): n,m=map(int,input().split()) mat=[[0 for i in range(n+1)] for j in range(n+1)] for i in range(m): u,v=map(int,input().split()) mat[u][v]=1 mat[v][u]=1 ord=[] for i in range(n+1): ord.append([sum(mat[i]),i]) ord.sort(reverse=True) moves=[] tld=0 ord=ord[:-1] for k in range(n): mv=0 for i in range(n): loc=ord[(i+k)%n][1] if(mat[loc][0]!=1): mv+=1 for j in range(1,n+1): if(mat[loc][j]==1 and mat[j][0]!=1): mat[j][0]=1 moves.append(mv) print(min(moves))
t=int(input()) for _ in range(t): n,m=map(int,input().split()) mat=[[0 for i in range(n+1)] for j in range(n+1)] for i in range(m): u,v=map(int,input().split()) mat[u][v]=1 mat[v][u]=1 ord=[] for i in range(n+1): ord.append([sum(mat[i]),i]) ord.sort(reverse=True) moves=[] tld=0 ord=ord[:-1] for k in range(n): mv=0 for i in range(n): loc=ord[(i+k)%n][1] if(mat[loc][0]!=1): mv+=1 for j in range(1,n+1): if(mat[loc][j]==1 and mat[j][0]!=1): mat[j][0]=1 moves.append(mv) print(min(moves))
train
APPS_structured
Chef has $N$ small boxes arranged on a line from $1$ to $N$. For each valid $i$, the weight of the $i$-th box is $W_i$. Chef wants to bring them to his home, which is at the position $0$. He can hold any number of boxes at the same time; however, the total weight of the boxes he's holding must not exceed K at any time, and he can only pick the ith box if all the boxes between Chef's home and the ith box have been either moved or picked up in this trip. Therefore, Chef will pick up boxes and carry them home in one or more round trips. Find the smallest number of round trips he needs or determine that he cannot bring all boxes home. -----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$. - The second line contains $N$ space-separated integers $W_1, W_2, \ldots, W_N$. -----Output----- For each test case, print a single line containing one integer ― the smallest number of round trips or $-1$ if it is impossible for Chef to bring all boxes home. -----Constraints----- - $1 \le T \le 100$ - $1 \le N, K \le 10^3$ - $1 \le W_i \le 10^3$ for each valid $i$ -----Example Input----- 4 1 1 2 2 4 1 1 3 6 3 4 2 3 6 3 4 3 -----Example Output----- -1 1 2 3 -----Explanation----- Example case 1: Since the weight of the box higher than $K$, Chef can not carry that box home in any number of the round trip. Example case 2: Since the sum of weights of both boxes is less than $K$, Chef can carry them home in one round trip. Example case 3: In the first round trip, Chef can only pick up the box at position $1$. In the second round trip, he can pick up both remaining boxes at positions $2$ and $3$. Example case 4: Chef can only carry one box at a time, so three round trips are required.
def fun(lst, k): weight = 0 ans = 1 for el in lst: if el > k: return -1 elif weight + el <= k: weight += el else: ans += 1 weight = el return ans for _ in range(int(input())): n, k = list(map(int, input().split())) lst = [int(i) for i in input().split()] print(fun(lst, k))
def fun(lst, k): weight = 0 ans = 1 for el in lst: if el > k: return -1 elif weight + el <= k: weight += el else: ans += 1 weight = el return ans for _ in range(int(input())): n, k = list(map(int, input().split())) lst = [int(i) for i in input().split()] print(fun(lst, k))
train
APPS_structured
Task ====== Make a custom esolang interpreter for the language [InfiniTick](https://esolangs.org/wiki/InfiniTick). InfiniTick is a descendant of [Tick](https://esolangs.org/wiki/tick) but also very different. Unlike Tick, InfiniTick has 8 commands instead of 4. It also runs infinitely, stopping the program only when an error occurs. You may choose to do the [Tick](https://www.codewars.com/kata/esolang-tick) kata first. Syntax/Info ====== InfiniTick runs in an infinite loop. This makes it both harder and easier to program in. It has an infinite memory of bytes and an infinite output amount. The program only stops when an error is reached. The program is also supposed to ignore non-commands. Commands ====== `>`: Move data selector right. `<`: Move data selector left. `+`: Increment amount of memory cell. Truncate overflow: 255+1=0. `-`: Decrement amount of memory cell. Truncate overflow: 0-1=255. `*`: Add ascii value of memory cell to the output tape. `&`: Raise an error, ie stop the program. `/`: Skip next command if cell value is zero. `\`: Skip next command if cell value is nonzero. Examples ====== **Hello world!** The following is a valid hello world program in InfiniTick. ``` '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++**>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*>++++++++++++++++++++++++++++++++*>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*<<*>>>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*<<<<*>>>>>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*>+++++++++++++++++++++++++++++++++*&' ``` Notes ====== * Please be wordy and post your likes/dislikes in the discourse area. * If this kata is a duplicate or uses incorrect style, this is not an issue, this is a suggestion. * Please don't edit this kata just to change the estimated rank. Thank you!
def interpreter(tape): data, pos, res = [0 for i in range(tape.count('*'))], 0, "" while 1: try: for i in iter([i for i in tape]): if i == "+": data[pos] = (data[pos] + 1) %256 elif i == "-": data[pos] = (data[pos] - 1) %256 elif i == ">": pos += 1 elif i == "<": pos -= 1 elif i == "*": res += chr(data[pos]) elif i == "/" and data[pos] == 0: next(tape) elif i == "\\" and data[pos] != 0: next(tape) elif i == "&": return res except: pass
def interpreter(tape): data, pos, res = [0 for i in range(tape.count('*'))], 0, "" while 1: try: for i in iter([i for i in tape]): if i == "+": data[pos] = (data[pos] + 1) %256 elif i == "-": data[pos] = (data[pos] - 1) %256 elif i == ">": pos += 1 elif i == "<": pos -= 1 elif i == "*": res += chr(data[pos]) elif i == "/" and data[pos] == 0: next(tape) elif i == "\\" and data[pos] != 0: next(tape) elif i == "&": return res except: pass
train
APPS_structured
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day. Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created. All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule. Helen knows that each minute of delay of the i-th flight costs airport c_{i} burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport. -----Input----- The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ 10^7), here c_{i} is the cost of delaying the i-th flight for one minute. -----Output----- The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t_1, t_2, ..., t_{n} (k + 1 ≤ t_{i} ≤ k + n), here t_{i} is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them. -----Example----- Input 5 2 4 2 1 10 2 Output 20 3 6 7 4 5 -----Note----- Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
from heapq import heappush, heappop, heapify n, k = list(map(int, input().split())) a = list(map(int, input().split())) q = [(-a[i], i) for i in range(k)] heapify(q) res, s = [0] * n, 0 for i in range(k, n): heappush(q, (-a[i], i)) x, j = heappop(q) s -= x * (i-j) res[j] = i+1 for i in range(n, n+k): x, j = heappop(q) s -= x * (i-j) res[j] = i+1 print(s) print(*res)
from heapq import heappush, heappop, heapify n, k = list(map(int, input().split())) a = list(map(int, input().split())) q = [(-a[i], i) for i in range(k)] heapify(q) res, s = [0] * n, 0 for i in range(k, n): heappush(q, (-a[i], i)) x, j = heappop(q) s -= x * (i-j) res[j] = i+1 for i in range(n, n+k): x, j = heappop(q) s -= x * (i-j) res[j] = i+1 print(s) print(*res)
train
APPS_structured
You are given a string S consisting of a,b and c. Find the number of strings that can be possibly obtained by repeatedly performing the following operation zero or more times, modulo 998244353: - Choose an integer i such that 1\leq i\leq |S|-1 and the i-th and (i+1)-th characters in S are different. Replace each of the i-th and (i+1)-th characters in S with the character that differs from both of them (among a, b and c). -----Constraints----- - 2 \leq |S| \leq 2 × 10^5 - S consists of a, b and c. -----Input----- Input is given from Standard Input in the following format: S -----Output----- Print the number of strings that can be possibly obtained by repeatedly performing the operation, modulo 998244353. -----Sample Input----- abc -----Sample Output----- 3 abc, aaa and ccc can be obtained.
#!/usr/bin/env python3 M = 998244353 def powmod(a, x, m = M): y = 1 while 0 < x: if x % 2 == 1: y *= a y %= m x //= 2 a = a ** 2 a %= m return y def solve(s): n = len(s) nb = nc = 0 ch = s[0] if ch == 'b': nb += 1 elif ch == 'c': nc += 1 sf = True tf = True left = ch for ch in s[1:]: if ch == 'b': nb += 1 elif ch == 'c': nc += 1 if ch == left: sf = False else: tf = False left = ch if tf: return 1 if n == 3: if (nb + nc * 2) % 3: return 7 if sf else 6 else: return 3 if n % 3: return (powmod(3, n - 1) + M - powmod(2, n - 1) + (1 if sf else 0)) % M else: if (nb + nc * 2) % 3: return (powmod(3, n - 1) + M - (powmod(2, n - 1) - powmod(2, n // 3 - 1)) + (1 if sf else 0)) % M else: return (powmod(3, n - 1) + M - (powmod(2, n // 3) + 4 * powmod(8, n // 3 - 1)) + (1 if sf else 0)) % M def main(): s = input() print((solve(s))) def __starting_point(): main() __starting_point()
#!/usr/bin/env python3 M = 998244353 def powmod(a, x, m = M): y = 1 while 0 < x: if x % 2 == 1: y *= a y %= m x //= 2 a = a ** 2 a %= m return y def solve(s): n = len(s) nb = nc = 0 ch = s[0] if ch == 'b': nb += 1 elif ch == 'c': nc += 1 sf = True tf = True left = ch for ch in s[1:]: if ch == 'b': nb += 1 elif ch == 'c': nc += 1 if ch == left: sf = False else: tf = False left = ch if tf: return 1 if n == 3: if (nb + nc * 2) % 3: return 7 if sf else 6 else: return 3 if n % 3: return (powmod(3, n - 1) + M - powmod(2, n - 1) + (1 if sf else 0)) % M else: if (nb + nc * 2) % 3: return (powmod(3, n - 1) + M - (powmod(2, n - 1) - powmod(2, n // 3 - 1)) + (1 if sf else 0)) % M else: return (powmod(3, n - 1) + M - (powmod(2, n // 3) + 4 * powmod(8, n // 3 - 1)) + (1 if sf else 0)) % M def main(): s = input() print((solve(s))) def __starting_point(): main() __starting_point()
train
APPS_structured
You're fed up about changing the version of your software manually. Instead, you will create a little script that will make it for you. # Exercice Create a function `nextVersion`, that will take a string in parameter, and will return a string containing the next version number. For example: # Rules All numbers, except the first one, must be lower than 10: if there are, you have to set them to 0 and increment the next number in sequence. You can assume all tests inputs to be valid.
import re from itertools import zip_longest def next_version(version): s, n = re.subn(r'\.', '', version) return ''.join([b + a for a, b in zip_longest('{:0{}}'.format(int(s) + 1, len(s))[::-1], '.' * n, fillvalue = '')][::-1])
import re from itertools import zip_longest def next_version(version): s, n = re.subn(r'\.', '', version) return ''.join([b + a for a, b in zip_longest('{:0{}}'.format(int(s) + 1, len(s))[::-1], '.' * n, fillvalue = '')][::-1])
train
APPS_structured
Vasya's older brother, Petya, attends an algorithm course in his school. Today he learned about matchings in graphs. Formally, a set of edges in a graph is called a matching if no pair of distinct edges in the set shares a common endpoint. Petya instantly came up with an inverse concept, an antimatching. In an antimatching, any pair of distinct edges should have a common endpoint. Petya knows that finding a largest matching in a graph is a somewhat formidable task. He wonders if finding the largest antimatching is any easier. Help him find the number of edges in a largest antimatching in a given graph. -----Input:----- The first line contains T$T$, number of test cases per file. The first line of each test case contains two integers n$n$ and m−$m-$ the number of vertices and edges of the graph respectively (1≤n≤104$1 \leq n \leq 10^4$, 0≤m≤104$0 \leq m \leq 10^4$). The next m$m$ lines describe the edges. The i$i$-th of these lines contains two integers ui$u_i$ and vi−$v_i-$ the indices of endpoints of the i$i$-th edge (1≤ui,vi≤n$1 \leq u_i, v_i \leq n$, ui≠vi$u_i \neq v_i$). It is guaranteed that the graph does not contain self-loops nor multiple edges. It is not guaranteed that the graph is connected. -----Output:----- Print a single number per test case −$-$ the maximum size of an antichain in the graph. -----Constraints----- - 1≤T≤10$1 \leq T \leq 10$ - 1≤n≤104$1 \leq n \leq 10^4$ - 0≤m≤104$0 \leq m \leq 10^4$ - 1≤ui,vi≤n$1 \leq u_i, v_i \leq n$ - ui≠vi$u_i \neq v_i$ -----Sample Input:----- 3 3 3 1 2 1 3 2 3 4 2 1 2 3 4 5 0 -----Sample Output:----- 3 1 0 -----EXPLANATION:----- In the first sample all three edges form an antimatching. In the second sample at most one of the two edges can be included in an antimatching since they do not share common endpoints. In the third sample there are no edges, hence the answer is 0$0$.
# cook your dish here def detect_triangle(adj): for x in range(len(adj)): for y in adj[x]: if not set(adj[x]).isdisjoint(adj[y]): return True for _ in range(int(input())): n,m=map(int,input().split()) graph=[[] for i in range(n)] for i in range(m): u,v=map(int,input().split()) graph[u-1].append(v-1) graph[v-1].append(u-1) h=[] for i in range(len(graph)): h.append(len(graph[i])) h1=max(h) if h1>=3: print(h1) continue if detect_triangle(graph): print(3) continue print(h1)
# cook your dish here def detect_triangle(adj): for x in range(len(adj)): for y in adj[x]: if not set(adj[x]).isdisjoint(adj[y]): return True for _ in range(int(input())): n,m=map(int,input().split()) graph=[[] for i in range(n)] for i in range(m): u,v=map(int,input().split()) graph[u-1].append(v-1) graph[v-1].append(u-1) h=[] for i in range(len(graph)): h.append(len(graph[i])) h1=max(h) if h1>=3: print(h1) continue if detect_triangle(graph): print(3) continue print(h1)
train
APPS_structured
=====Problem Statement===== A newly opened multinational brand has decided to base their company logo on the three most common characters in the company name. They are now trying out various combinations of company names and logos based on this condition. Given a string s, which is the company name in lowercase letters, your task is to find the top three most common characters in the string. Print the three most common characters along with their occurrence count. Sort in descending order of occurrence count. If the occurrence count is the same, sort the characters in alphabetical order. For example, according to the conditions described above, GOOGLE would have it's logo with the letters G, O, E. =====Input Format===== A single line of input containing the string S. =====Constraints===== 3≤len(S)≤10^4
#!/bin/python3 import sys from collections import Counter def __starting_point(): s = input().strip() best = Counter(s) sortit = sorted(list(best.items()), key = lambda x: (-x[1], x[0]))[:3] print(("\n".join(x[0]+" "+str(x[1]) for x in sortit))) __starting_point()
#!/bin/python3 import sys from collections import Counter def __starting_point(): s = input().strip() best = Counter(s) sortit = sorted(list(best.items()), key = lambda x: (-x[1], x[0]))[:3] print(("\n".join(x[0]+" "+str(x[1]) for x in sortit))) __starting_point()
train
APPS_structured
Given an array A, partition it into two (contiguous) subarrays left and right so that: Every element in left is less than or equal to every element in right. left and right are non-empty. left has the smallest possible size. Return the length of left after such a partitioning.  It is guaranteed that such a partitioning exists. Example 1: Input: [5,0,3,8,6] Output: 3 Explanation: left = [5,0,3], right = [8,6] Example 2: Input: [1,1,1,0,6,12] Output: 4 Explanation: left = [1,1,1,0], right = [6,12] Note: 2 <= A.length <= 30000 0 <= A[i] <= 10^6 It is guaranteed there is at least one way to partition A as described.
class Solution: def partitionDisjoint(self, A: List[int]) -> int: run_max = [float('-inf')] run_min = [float('inf')] # get run_max p = 1 while p < len(A): run_max.append(max(run_max[-1], A[p-1])) p += 1 # get run_min p = len(A) - 2 while p > -1: run_min.append(min(run_min[-1], A[p+1])) p -= 1 run_min = run_min[::-1] # find the pos that satisfies the condition. res = -1 p = 0 done = False while p < len(A) - 1 and not done: if A[p] <= run_min[p] and run_max[p] <= run_min[p]: res = p + 1 done = True p += 1 return res
class Solution: def partitionDisjoint(self, A: List[int]) -> int: run_max = [float('-inf')] run_min = [float('inf')] # get run_max p = 1 while p < len(A): run_max.append(max(run_max[-1], A[p-1])) p += 1 # get run_min p = len(A) - 2 while p > -1: run_min.append(min(run_min[-1], A[p+1])) p -= 1 run_min = run_min[::-1] # find the pos that satisfies the condition. res = -1 p = 0 done = False while p < len(A) - 1 and not done: if A[p] <= run_min[p] and run_max[p] <= run_min[p]: res = p + 1 done = True p += 1 return res
train
APPS_structured
$Jaggu$ monkey a friend of $Choota$ $Bheem$ a great warrior of $Dholakpur$. He gets everything he wants. Being a friend of $Choota$ $Bheem$ he never has to struggle for anything, because of this he is in a great debt of $Choota$ $Bheem$, he really wants to pay his debt off. Finally the time has come to pay his debt off, $Jaggu$ is on a magical tree. He wants to collect apples from different branches but he is in a hurry. $Botakpur$ has attacked on $Dholakpur$ and $Bheem$ is severely injured, as been instructed by the village witch, $Bheem$ can only be saved by the apples of the magical tree. Each apple is placed in Tree Node structure and each apple has some sweetness. Now there's a problem as $Jaggu$ is also injured so he can only slide downwards and alse is collecting apples in his hand so he can't climb. You would be given $Q$ queries. Queries are of 2 type :- - Ending Node Node of $Jaggu$ is given. $format$ - type of query node -(1 2) - Sweetness of Apple on a given node is changed. $format$ - type of query node new sweetness(2 3 10) $Note$: $Jaggu$ is always on the top of tree initially in each query.The sweetness is always positive. Help $Jaggu$ in saving $Bheem$ -----Input:----- - First line contains $N$ - (number of nodes). - Next line contains $N$ integers with space giving sweetness of apple on Nodes $(1 to N)$ - Next $N-1$ lines contain $N1$ $N2$ connected nodes. - Next line contains single integer $Q$ Number of queries -----Output:----- - For each query of type 1, print total sweetness of apples. -----Constraints----- - $1 \leq N \leq 10^4$ - $2 \leq Q \leq 10^4$ -----Sample Input:----- 10 10 12 6 8 1 19 0 5 13 17 1 2 1 3 1 4 3 10 4 8 8 9 4 5 5 7 5 6 3 1 1 2 3 20 1 8 -----Sample Output:----- 10 23 -----EXPLANATION:----- This sweetness array is : $[10,2,6,8,1,19,0,5,13,17]$ The tree is: 1 / | \ 2 3 4 / / \ 10 8 5 / / \ 9 7 6
counter = -1 def flattree(node): nonlocal counter if visited[node]==1: return else: visited[node]=1 counter += 1 i_c[node] = counter flat_tree[counter] = swt[node] for i in graph[node]: if visited[i]==0: flattree(i) counter += 1 o_c[node] = counter flat_tree[counter] = -swt[node] return def getsum(BITTree, i): s = 0 # initialize result i = i + 1 while i > 0: s += BITTree[i] i -= i & (-i) return s def upd(BITTree, n, i, v): i += 1 while i <= n: BITTree[i] += v i += i & (-i) def construct(arr, n): BITTree = [0] * (n + 1) for i in range(n): upd(BITTree, n, i, arr[i]) return BITTree from collections import defaultdict n = int(input()) swt = list(map(int, input().split())) graph = defaultdict(list) for i in range(n-1): n1, n2 = list(map(int, input().split())) graph[n1-1].append(n2-1) graph[n2-1].append(n1-1) flat_tree = [0]*(2*n+1) i_c = [0]*n o_c = [0]*n visited = [0]*n flattree(0) tre = construct(flat_tree, 2*n) q = int(input()) for i in range(q): query = list(map(int, input().split())) if query[0] == 1: node = query[1] - 1 answer = getsum(tre, i_c[node]) print(answer) else: node = query[1]-1 upd(flat_tree, (2*n), i_c[node], query[2]) upd(flat_tree, (2*n), o_c[node], -query[2])
counter = -1 def flattree(node): nonlocal counter if visited[node]==1: return else: visited[node]=1 counter += 1 i_c[node] = counter flat_tree[counter] = swt[node] for i in graph[node]: if visited[i]==0: flattree(i) counter += 1 o_c[node] = counter flat_tree[counter] = -swt[node] return def getsum(BITTree, i): s = 0 # initialize result i = i + 1 while i > 0: s += BITTree[i] i -= i & (-i) return s def upd(BITTree, n, i, v): i += 1 while i <= n: BITTree[i] += v i += i & (-i) def construct(arr, n): BITTree = [0] * (n + 1) for i in range(n): upd(BITTree, n, i, arr[i]) return BITTree from collections import defaultdict n = int(input()) swt = list(map(int, input().split())) graph = defaultdict(list) for i in range(n-1): n1, n2 = list(map(int, input().split())) graph[n1-1].append(n2-1) graph[n2-1].append(n1-1) flat_tree = [0]*(2*n+1) i_c = [0]*n o_c = [0]*n visited = [0]*n flattree(0) tre = construct(flat_tree, 2*n) q = int(input()) for i in range(q): query = list(map(int, input().split())) if query[0] == 1: node = query[1] - 1 answer = getsum(tre, i_c[node]) print(answer) else: node = query[1]-1 upd(flat_tree, (2*n), i_c[node], query[2]) upd(flat_tree, (2*n), o_c[node], -query[2])
train
APPS_structured
There are n people and 40 types of hats labeled from 1 to 40. Given a list of list of integers hats, where hats[i] is a list of all hats preferred by the i-th person. Return the number of ways that the n people wear different hats to each other. Since the answer may be too large, return it modulo 10^9 + 7. Example 1: Input: hats = [[3,4],[4,5],[5]] Output: 1 Explanation: There is only one way to choose hats given the conditions. First person choose hat 3, Second person choose hat 4 and last one hat 5. Example 2: Input: hats = [[3,5,1],[3,5]] Output: 4 Explanation: There are 4 ways to choose hats (3,5), (5,3), (1,3) and (1,5) Example 3: Input: hats = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]] Output: 24 Explanation: Each person can choose hats labeled from 1 to 4. Number of Permutations of (1,2,3,4) = 24. Example 4: Input: hats = [[1,2,3],[2,3,5,6],[1,3,7,9],[1,8,9],[2,5,7]] Output: 111 Constraints: n == hats.length 1 <= n <= 10 1 <= hats[i].length <= 40 1 <= hats[i][j] <= 40 hats[i] contains a list of unique integers.
class Solution: def numberWays(self, hats: List[List[int]]) -> int: N = len(hats) for i, h in enumerate(hats): hats[i] = set(h) mod = (10 ** 9) + 7 @lru_cache(None) def rec(cur, mask): if cur > 41: return 0 if mask == 0: return 1 ans = 0 for i in range(N): if (mask & (1<<i)) == 0: continue if cur not in hats[i]: continue ans += rec(cur+1, mask ^ (1<<i)) ans += rec(cur+1, mask) while ans >= mod: ans -= mod return ans return rec(0, (2**N)-1)
class Solution: def numberWays(self, hats: List[List[int]]) -> int: N = len(hats) for i, h in enumerate(hats): hats[i] = set(h) mod = (10 ** 9) + 7 @lru_cache(None) def rec(cur, mask): if cur > 41: return 0 if mask == 0: return 1 ans = 0 for i in range(N): if (mask & (1<<i)) == 0: continue if cur not in hats[i]: continue ans += rec(cur+1, mask ^ (1<<i)) ans += rec(cur+1, mask) while ans >= mod: ans -= mod return ans return rec(0, (2**N)-1)
train
APPS_structured
Given an integer n, return a string with n characters such that each character in such string occurs an odd number of times. The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them.   Example 1: Input: n = 4 Output: "pppz" Explanation: "pppz" is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as "ohhh" and "love". Example 2: Input: n = 2 Output: "xy" Explanation: "xy" is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as "ag" and "ur". Example 3: Input: n = 7 Output: "holasss" Constraints: 1 <= n <= 500
import random import string class Solution: def generateTheString(self, n: int) -> str: if n%2!=0: return 'a'*n else: return 'a'*(n-1) + 'b'
import random import string class Solution: def generateTheString(self, n: int) -> str: if n%2!=0: return 'a'*n else: return 'a'*(n-1) + 'b'
train
APPS_structured
Count how often sign changes in array. ### result number from `0` to ... . Empty array returns `0` ### example
def catch_sign_change(lst): result = 0 for i in range(len(lst)-1): a = lst[i] if lst[i] !=0 else 1 b = lst[i+1] if lst[i+1] !=0 else 1 if a*b < 0: result += 1 return result
def catch_sign_change(lst): result = 0 for i in range(len(lst)-1): a = lst[i] if lst[i] !=0 else 1 b = lst[i+1] if lst[i+1] !=0 else 1 if a*b < 0: result += 1 return result
train
APPS_structured
You are given an N × N grid initially filled by zeros. Let the rows and columns of the grid be numbered from 1 to N, inclusive. There are two types of operations can be applied to the grid: - RowAdd R X: all numbers in the row R should be increased by X. - ColAdd C X: all numbers in the column C should be increased by X. Now after performing the sequence of such operations you need to find the maximum element in the grid. -----Input----- The first line of the input contains two space separated integers N and Q denoting the size of the grid and the number of performed operations respectively. Each of the following Q lines describe an operation in the format described above. -----Output----- Output a single line containing the maximum number at the grid after performing all the operations. -----Constraints----- - 1 ≤ N ≤ 314159 - 1 ≤ Q ≤ 314159 - 1 ≤ X ≤ 3141 - 1 ≤ R, C ≤ N -----Example----- Input: 2 4 RowAdd 1 3 ColAdd 2 1 ColAdd 1 4 RowAdd 2 1 Output: 7 -----Explanation----- The grid changes as follows: 00 33 34 74 74 00 00 01 41 52 The maximum number in the final grid is 7.
N,Q = [int(i) for i in input().split()] row = [0 for i in range(N)] col = [0 for i in range(N)] for i in range(Q): x = input().split() if(x[0]=='RowAdd'): row[int(x[1])-1] += int(x[2]) else: col[int(x[1])-1] += int(x[2]) print(max(row)+max(col))
N,Q = [int(i) for i in input().split()] row = [0 for i in range(N)] col = [0 for i in range(N)] for i in range(Q): x = input().split() if(x[0]=='RowAdd'): row[int(x[1])-1] += int(x[2]) else: col[int(x[1])-1] += int(x[2]) print(max(row)+max(col))
train
APPS_structured
Share price =========== You spent all your saved money to buy some shares. You bought it for `invested`, and want to know how much it's worth, but all the info you can quickly get are just the change the shares price made in percentages. Your task: ---------- Write the function `sharePrice()` that calculates, and returns the current price of your share, given the following two arguments: - `invested`(number), the amount of money you initially invested in the given share - `changes`(array of numbers), contains your shares daily movement percentages The returned number, should be in string format, and it's precision should be fixed at 2 decimal numbers. Have fun! >**Hint:** Try to write the function in a functional manner!
def share_price(invested, changes): for change in changes: invested = invested + ( invested * (change/100.00) ) return "%.2f" % invested
def share_price(invested, changes): for change in changes: invested = invested + ( invested * (change/100.00) ) return "%.2f" % invested
train
APPS_structured
You are given an unweighted tree with N$N$ nodes (numbered 1$1$ through N$N$). Let's denote the distance between any two nodes p$p$ and q$q$ by d(p,q)$d(p, q)$. You should answer Q$Q$ queries. In each query, you are given parameters a$a$, da$d_a$, b$b$, db$d_b$, and you should find a node x$x$ such that d(x,a)=da$d(x, a) = d_a$ and d(x,b)=db$d(x, b) = d_b$, or determine that there is no such node. -----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 Q$Q$. - Each of the next N−1$N-1$ lines contains two space-separated integers u$u$ and v$v$ denoting that nodes u$u$ and v$v$ are connected by an edge. - Each of the next Q$Q$ lines contains four space-separated integers a$a$, da$d_a$, b$b$ and db$d_b$ describing a query. -----Output----- For each query, print a single line containing one integer ― the number of a node satisfying the given requirements, or −1$-1$ if no such node exists. If there are multiple solutions, you may output any one. -----Constraints----- - 1≤T≤1,000$1 \le T \le 1,000$ - 1≤N,Q≤106$1 \le N, Q \le 10^6$ - 1≤u,v≤N$1 \le u, v \le N$ - the graph on the input is a tree - 1≤a,b≤N$1 \le a, b \le N$ - 1≤da,db<N$1 \le d_a, d_b < N$ - the sum of N$N$ over all test cases does not exceed 106$10^6$ - the sum of Q$Q$ over all test cases does not exceed 106$10^6$ -----Subtasks----- Subtask #1 (50 points): - 1≤N,Q≤1,000$1 \le N, Q \le 1,000$ - the sum of N$N$ over all test cases does not exceed 1,000$1,000$ - the sum of Q$Q$ over all test cases does not exceed 1,000$1,000$ Subtask #2 (50 points): original constraints -----Example Input----- 1 5 3 1 2 2 3 3 4 3 5 2 1 4 1 2 2 4 2 1 1 2 1 -----Example Output----- 3 5 -1
# cook your dish here import numpy as np def add(adj,a,b,n): adj[a,b] = adj[b,a] = 1 for i in range(n): if adj[a,i]!=-10 and a!=i and b!=i and adj[b,i]==-10: adj[b,i] = adj[a,i] + 1 adj[i,b] = adj[b,i] for i in range(n): if adj[b,i]!=-10 and b!=i and a!=i and adj[a,i]==-10: adj[a,i] = adj[b,i] + 1 adj[i,a] = adj[a,i] return adj t = int(input()) while t>0 : n,q = map(int,input().split()) adj = np.zeros((n,n),dtype = 'int') adj += np.array([-10]) for i in range(n): adj[i,i] = 0 for i in range(1,n): a,b = map(int,input().split()) adj = add(adj,a-1,b-1,n) for _ in range(q): a,da,b,db = map(int,input().split()) x = -1 for i in range(n): if adj[a-1,i] == da and adj[b-1,i] == db: x = i + 1 break print(x) t -= 1
# cook your dish here import numpy as np def add(adj,a,b,n): adj[a,b] = adj[b,a] = 1 for i in range(n): if adj[a,i]!=-10 and a!=i and b!=i and adj[b,i]==-10: adj[b,i] = adj[a,i] + 1 adj[i,b] = adj[b,i] for i in range(n): if adj[b,i]!=-10 and b!=i and a!=i and adj[a,i]==-10: adj[a,i] = adj[b,i] + 1 adj[i,a] = adj[a,i] return adj t = int(input()) while t>0 : n,q = map(int,input().split()) adj = np.zeros((n,n),dtype = 'int') adj += np.array([-10]) for i in range(n): adj[i,i] = 0 for i in range(1,n): a,b = map(int,input().split()) adj = add(adj,a-1,b-1,n) for _ in range(q): a,da,b,db = map(int,input().split()) x = -1 for i in range(n): if adj[a-1,i] == da and adj[b-1,i] == db: x = i + 1 break print(x) t -= 1
train
APPS_structured
How many bees are in the beehive? * bees can be facing UP, DOWN, LEFT, or RIGHT * bees can share parts of other bees Examples Ex1 ``` bee.bee .e..e.. .b..eeb ``` *Answer: 5* Ex2 ``` bee.bee e.e.e.e eeb.eeb ``` *Answer: 8* # Notes * The hive may be empty or null/None/nil/... * Python: the hive is passed as a list of lists (not a list of strings)
def how_many_bees(hive): bees = ('bee', 'eeb') num_of_bees = 0 if hive == None: return 0 for line in hive: for pos in range(len(line)-2): possible_bee = line[pos] + line[pos+1] + line[pos+2] if possible_bee in bees: num_of_bees +=1 for line_idx in range(len(hive)-2): for pos_idx in range(len(hive[line_idx])): possible_bee = hive[line_idx][pos_idx] + hive[line_idx+1][pos_idx] + hive[line_idx+2][pos_idx] if possible_bee in bees: num_of_bees +=1 return num_of_bees
def how_many_bees(hive): bees = ('bee', 'eeb') num_of_bees = 0 if hive == None: return 0 for line in hive: for pos in range(len(line)-2): possible_bee = line[pos] + line[pos+1] + line[pos+2] if possible_bee in bees: num_of_bees +=1 for line_idx in range(len(hive)-2): for pos_idx in range(len(hive[line_idx])): possible_bee = hive[line_idx][pos_idx] + hive[line_idx+1][pos_idx] + hive[line_idx+2][pos_idx] if possible_bee in bees: num_of_bees +=1 return num_of_bees
train
APPS_structured
Given a positive integer K, you need find the smallest positive integer N such that N is divisible by K, and N only contains the digit 1. Return the length of N.  If there is no such N, return -1. Example 1: Input: 1 Output: 1 Explanation: The smallest answer is N = 1, which has length 1. Example 2: Input: 2 Output: -1 Explanation: There is no such positive integer N divisible by 2. Example 3: Input: 3 Output: 3 Explanation: The smallest answer is N = 111, which has length 3. Note: 1 <= K <= 10^5
class Solution: # https://leetcode.com/problems/smallest-integer-divisible-by-k/discuss/801679/Simple-elegant-code-with-explanation-and-example def smallestRepunitDivByK(self, K: int) -> int: if K == 2 or K == 5: return -1 remainder = 0 for i in range(1, K + 1): remainder = (remainder * 10 + 1) % K if not remainder: return i return -1
class Solution: # https://leetcode.com/problems/smallest-integer-divisible-by-k/discuss/801679/Simple-elegant-code-with-explanation-and-example def smallestRepunitDivByK(self, K: int) -> int: if K == 2 or K == 5: return -1 remainder = 0 for i in range(1, K + 1): remainder = (remainder * 10 + 1) % K if not remainder: return i return -1
train
APPS_structured
A Train started its journey at x=-infinity is travelling on the x-Coordinate Axis. Given n passengers and the coordinates $b_i$ and $d_i$ for each of the $ith$ passenger at which they board and leave from the train respectively. Due to current COVID-19 crisis, the train is monitored at each mile/coordinate. The infection degree of the train at each mile is equal to the total passengers present in the train at that mile/coordinate. The train stops its journey if no more passengers are there to board the train. The term infection severity of the journey is defined as the sum of infection degrees noted at each mile. Find the Infection severity of the journey. Note: A passenger is considered for calculation of infection degree at both boarding and leaving stations. Since the answer can be very large, print it modulo $(10^9)+7$. -----Input:----- - First line will contain $N$, number of passengers. Then the $N$ lines follow. - $i$th line contains two integers $b_i, d_i$ , the boarding and departure mile of $i$th passenger. -----Output:----- Print a single value, the Infection Severity of the journey modulo $(10^9)+7$. -----Constraints----- - $0 \leq N \leq 100000$ - $-500000 \leq b_i \leq 500000$ - $-500000 \leq d_i \leq 500000$ -----Sample Input:----- 3 0 2 1 3 -1 4 -----Sample Output:----- 12 -----EXPLANATION:----- Infection degree at : -1 is 1 0 is 2 1 is 3 2 is 3 3 is 2 4 is 1 Calculation started at mile -1 and ended at mile 4. Infection Severity = 1+2+3+3+2+1 =12
M=1000000007 n = int(input()) L=[] R=[] for i in range(n): l,r = list(map(int,input().split())) L.append(l) R.append(r) LS=set(L) RS=set(R) LD=dict(list(zip(LS,[0]*len(LS)))) for e in L: LD[e]+=1 RD=dict(list(zip(RS,[0]*len(RS)))) for e in R: RD[e]+=1 L=dict(list(zip(L,[0]*n))) R=dict(list(zip(R,[0]*n))) inf=0 total=0 for i in range( min(LS), max(RS)+1 ): if i in L: inf+=LD[i] total+=inf if i in R: inf-=RD[i] print(total%M)
M=1000000007 n = int(input()) L=[] R=[] for i in range(n): l,r = list(map(int,input().split())) L.append(l) R.append(r) LS=set(L) RS=set(R) LD=dict(list(zip(LS,[0]*len(LS)))) for e in L: LD[e]+=1 RD=dict(list(zip(RS,[0]*len(RS)))) for e in R: RD[e]+=1 L=dict(list(zip(L,[0]*n))) R=dict(list(zip(R,[0]*n))) inf=0 total=0 for i in range( min(LS), max(RS)+1 ): if i in L: inf+=LD[i] total+=inf if i in R: inf-=RD[i] print(total%M)
train
APPS_structured
# Task John was in math class and got bored, so he decided to fold some origami from a rectangular `a × b` sheet of paper (`a > b`). His first step is to make a square piece of paper from the initial rectangular piece of paper by folding the sheet along the bisector of the right angle and cutting off the excess part. After moving the square piece of paper aside, John wanted to make even more squares! He took the remaining (`a-b`) × `b` strip of paper and went on with the process until he was left with a square piece of paper. Your task is to determine how many square pieces of paper John can make. # Example: For: `a = 2, b = 1`, the output should be `2`. Given `a = 2` and `b = 1`, John can fold a `1 × 1` then another `1 × 1`. So the answer is `2`. For: `a = 10, b = 7`, the output should be `6`. We are given `a = 10` and `b = 7`. The following is the order of squares John folds: `7 × 7, 3 × 3, 3 × 3, 1 × 1, 1 × 1, and 1 × 1`. Here are pictures for the example cases. # Input/Output - `[input]` integer `a` `2 ≤ a ≤ 1000` - `[input]` integer `b` `1 ≤ b < a ≤ 1000` - `[output]` an integer The maximum number of squares.
from itertools import count def folding(a, b): for c in count(0): if a == 1: return c + b if b == 1: return c + a if a == b: return c + 1 a, b = abs(a-b), min(a, b)
from itertools import count def folding(a, b): for c in count(0): if a == 1: return c + b if b == 1: return c + a if a == b: return c + 1 a, b = abs(a-b), min(a, b)
train
APPS_structured
The most basic encryption method is to map a char to another char by a certain math rule. Because every char has an ASCII value, we can manipulate this value with a simple math expression. For example 'a' + 1 would give us 'b', because 'a' value is 97 and 'b' value is 98. You will need to write a method which does exactly that - get a string as text and an int as the rule of manipulation, and should return encrypted text. for example: encrypt("a",1) = "b" *Full ascii table is used on our question (256 chars) - so 0-255 are the valid values.* Good luck.
def encrypt(text, key): return "".join(chr((ord(ch) + key) & 255) for ch in text)
def encrypt(text, key): return "".join(chr((ord(ch) + key) & 255) for ch in text)
train
APPS_structured
This kata generalizes [Twice Linear](https://www.codewars.com/kata/5672682212c8ecf83e000050). You may want to attempt that kata first. ## Sequence Consider an integer sequence `U(m)` defined as: 1. `m` is a given non-empty set of positive integers. 2. `U(m)[0] = 1`, the first number is always 1. 3. For each `x` in `U(m)`, and each `y` in `m`, `x * y + 1` must also be in `U(m)`. 4. No other numbers are in `U(m)`. 5. `U(m)` is sorted, with no duplicates. ### Sequence Examples #### `U(2, 3) = [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ...]` 1 produces 3 and 4, since `1 * 2 + 1 = 3`, and `1 * 3 + 1 = 4`. 3 produces 7 and 10, since `3 * 2 + 1 = 7`, and `3 * 3 + 1 = 10`. #### `U(5, 7, 8) = [1, 6, 8, 9, 31, 41, 43, 46, 49, 57, 64, 65, 73, 156, 206, ...]` 1 produces 6, 8, and 9. 6 produces 31, 43, and 49. ## Task: Implement `n_linear` or `nLinear`: given a set of postive integers `m`, and an index `n`, find `U(m)[n]`, the `n`th value in the `U(m)` sequence. ### Tips * Tests use large n values. Slow algorithms may time-out. * Tests use large values in the m set. Algorithms which multiply further than neccessary may overflow. * Linear run time and memory usage is possible. * How can you build the sequence iteratively, without growing extra data structures?
from heapq import heappush, heappop def n_linear(m, n): h = [1] x = 0 for _ in range(n+1): x = heappop(h) while h and h[0] == x: heappop(h) for y in m: a = y * x + 1 heappush(h, a) return x
from heapq import heappush, heappop def n_linear(m, n): h = [1] x = 0 for _ in range(n+1): x = heappop(h) while h and h[0] == x: heappop(h) for y in m: a = y * x + 1 heappush(h, a) return x
train
APPS_structured
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are: `2332, 110011, 54322345` For a given number ```num```, write a function which returns an array of all the numerical palindromes contained within each number. The array should be sorted in ascending order and any duplicates should be removed. In this kata, single digit numbers and numbers which start or end with zeros (such as `010` and `00`) are **NOT** considered valid numerical palindromes. If `num` contains no valid palindromes, return `"No palindromes found"`. Otherwise, return `"Not valid"` if the input is not an integer or is less than `0`. ## Examples ``` palindrome(1221) => [22, 1221] palindrome(34322122) => [22, 212, 343, 22122] palindrome(1001331) => [33, 1001, 1331] palindrome(1294) => "No palindromes found" palindrome("1221") => "Not valid" ``` --- ### Other Kata in this Series: Numerical Palindrome #1 Numerical Palindrome #1.5 Numerical Palindrome #2 Numerical Palindrome #3 Numerical Palindrome #3.5 Numerical Palindrome #4 Numerical Palindrome #5
def palindrome(num): if not (isinstance(num, int) and num > 0): return 'Not valid' s = str(num) result = set() for i in range(0, len(s)-1): for j in range(i+2, len(s)+1): if s[i] == '0': continue x = s[i:j] if x == x[::-1]: result.add(int(x)) if result: return sorted(result) return 'No palindromes found'
def palindrome(num): if not (isinstance(num, int) and num > 0): return 'Not valid' s = str(num) result = set() for i in range(0, len(s)-1): for j in range(i+2, len(s)+1): if s[i] == '0': continue x = s[i:j] if x == x[::-1]: result.add(int(x)) if result: return sorted(result) return 'No palindromes found'
train
APPS_structured
# Task You are given a binary string (a string consisting of only '1' and '0'). The only operation that can be performed on it is a Flip operation. It flips any binary character ( '0' to '1' and vice versa) and all characters to the `right` of it. For example, applying the Flip operation to the 4th character of string "1001010" produces the "1000101" string, since all characters from the 4th to the 7th are flipped. Your task is to find the minimum number of flips required to convert the binary string to string consisting of all '0'. # Example For `s = "0101"`, the output should be `3`. It's possible to convert the string in three steps: ``` "0101" -> "0010" ^^^ "0010" -> "0001" ^^ "0001" -> "0000" ^ ``` # Input/Output - `[input]` string `s` A binary string. - `[output]` an integer The minimum number of flips required.
def bin_str(s): return s.count("10") * 2 + (s[-1] == "1")
def bin_str(s): return s.count("10") * 2 + (s[-1] == "1")
train
APPS_structured
There is an array of strings. All strings contains similar _letters_ except one. Try to find it! ```python find_uniq([ 'Aa', 'aaa', 'aaaaa', 'BbBb', 'Aaaa', 'AaAaAa', 'a' ]) # => 'BbBb' find_uniq([ 'abc', 'acb', 'bac', 'foo', 'bca', 'cab', 'cba' ]) # => 'foo' ``` Strings may contain spaces. Spaces is not significant, only non-spaces symbols matters. E.g. string that contains only spaces is like empty string. It’s guaranteed that array contains more than 3 strings. This is the second kata in series: 1. [Find the unique number](https://www.codewars.com/kata/585d7d5adb20cf33cb000235) 2. Find the unique string (this kata) 3. [Find The Unique](https://www.codewars.com/kata/5862e0db4f7ab47bed0000e5)
def find_uniq(arr): counts = {} result = {} for s in arr: hash = frozenset(s.strip().lower()) counts[hash] = counts.get(hash, 0) + 1 result[hash] = s if len(counts) > 1 and counts[max(counts, key=counts.get)] > 1: return result[min(counts, key=counts.get)]
def find_uniq(arr): counts = {} result = {} for s in arr: hash = frozenset(s.strip().lower()) counts[hash] = counts.get(hash, 0) + 1 result[hash] = s if len(counts) > 1 and counts[max(counts, key=counts.get)] > 1: return result[min(counts, key=counts.get)]
train
APPS_structured
There is a simple undirected graph with N vertices and M edges. The vertices are numbered 1 through N, and the edges are numbered 1 through M. Edge i connects Vertex U_i and V_i. Also, Vertex i has two predetermined integers A_i and B_i. You will play the following game on this graph. First, choose one vertex and stand on it, with W yen (the currency of Japan) in your pocket. Here, A_s \leq W must hold, where s is the vertex you choose. Then, perform the following two kinds of operations any number of times in any order: - Choose one vertex v that is directly connected by an edge to the vertex you are standing on, and move to vertex v. Here, you need to have at least A_v yen in your pocket when you perform this move. - Donate B_v yen to the vertex v you are standing on. Here, the amount of money in your pocket must not become less than 0 yen. You win the game when you donate once to every vertex. Find the smallest initial amount of money W that enables you to win the game. -----Constraints----- - 1 \leq N \leq 10^5 - N-1 \leq M \leq 10^5 - 1 \leq A_i,B_i \leq 10^9 - 1 \leq U_i < V_i \leq N - The given graph is connected and simple (there is at most one edge between any pair of vertices). -----Input----- Input is given from Standard Input in the following format: N M A_1 B_1 A_2 B_2 : A_N B_N U_1 V_1 U_2 V_2 : U_M V_M -----Output----- Print the smallest initial amount of money W that enables you to win the game. -----Sample Input----- 4 5 3 1 1 2 4 1 6 2 1 2 2 3 2 4 1 4 3 4 -----Sample Output----- 6 If you have 6 yen initially, you can win the game as follows: - Stand on Vertex 4. This is possible since you have not less than 6 yen. - Donate 2 yen to Vertex 4. Now you have 4 yen. - Move to Vertex 3. This is possible since you have not less than 4 yen. - Donate 1 yen to Vertex 3. Now you have 3 yen. - Move to Vertex 2. This is possible since you have not less than 1 yen. - Move to Vertex 1. This is possible since you have not less than 3 yen. - Donate 1 yen to Vertex 1. Now you have 2 yen. - Move to Vertex 2. This is possible since you have not less than 1 yen. - Donate 2 yen to Vertex 2. Now you have 0 yen. If you have less than 6 yen initially, you cannot win the game. Thus, the answer is 6.
class dsu: def __init__(self, n=0): self._n = n self.parent_or_size = [-1] * n def merge(self, a: int, b: int) -> int: x = self.leader(a) y = self.leader(b) if x == y: return x if self.parent_or_size[x] > self.parent_or_size[y]: x, y = y, x self.parent_or_size[x] += self.parent_or_size[y] self.parent_or_size[y] = x return x def same(self, a: int, b: int) -> bool: return self.leader(a) == self.leader(b) def leader(self, a: int) -> int: x = a while self.parent_or_size[x] >= 0: x = self.parent_or_size[x] while a != x: self.parent_or_size[a], a = x, self.parent_or_size[a] return x def size(self, a: int) -> int: return -self.parent_or_size[self.leader(a)] def groups(self): g = [[] for _ in range(self._n)] for i in range(self._n): g[self.leader(i)].append(i) return list(c for c in g if c) n, m = list(map(int, input().split())) vdata = [] # (required, gain) for _ in range(n): a, b = list(map(int, input().split())) vdata.append((max(a - b, 0), b)) to = [[] for _ in range(n)] for _ in range(m): u, v = list(map(int, input().split())) u -= 1; v -= 1 to[u].append(v) to[v].append(u) s = dsu(n) dp = vdata.copy() # (extra, tot_gain) visited = [False] * n for u in sorted(list(range(n)), key=lambda i: vdata[i][0]): req, gain = vdata[u] frm = {u} for v in to[u]: if visited[v]: frm.add(s.leader(v)) mnextra = 10 ** 18 for v in frm: e, g = dp[v] e += max(req - (e + g), 0) if e < mnextra: mnextra, mni = e, v extra, tot_gain = mnextra, sum(dp[v][1] for v in frm) for v in frm: s.merge(u, v) dp[s.leader(u)] = extra, tot_gain visited[u] = True ans = sum(dp[s.leader(0)]) print(ans)
class dsu: def __init__(self, n=0): self._n = n self.parent_or_size = [-1] * n def merge(self, a: int, b: int) -> int: x = self.leader(a) y = self.leader(b) if x == y: return x if self.parent_or_size[x] > self.parent_or_size[y]: x, y = y, x self.parent_or_size[x] += self.parent_or_size[y] self.parent_or_size[y] = x return x def same(self, a: int, b: int) -> bool: return self.leader(a) == self.leader(b) def leader(self, a: int) -> int: x = a while self.parent_or_size[x] >= 0: x = self.parent_or_size[x] while a != x: self.parent_or_size[a], a = x, self.parent_or_size[a] return x def size(self, a: int) -> int: return -self.parent_or_size[self.leader(a)] def groups(self): g = [[] for _ in range(self._n)] for i in range(self._n): g[self.leader(i)].append(i) return list(c for c in g if c) n, m = list(map(int, input().split())) vdata = [] # (required, gain) for _ in range(n): a, b = list(map(int, input().split())) vdata.append((max(a - b, 0), b)) to = [[] for _ in range(n)] for _ in range(m): u, v = list(map(int, input().split())) u -= 1; v -= 1 to[u].append(v) to[v].append(u) s = dsu(n) dp = vdata.copy() # (extra, tot_gain) visited = [False] * n for u in sorted(list(range(n)), key=lambda i: vdata[i][0]): req, gain = vdata[u] frm = {u} for v in to[u]: if visited[v]: frm.add(s.leader(v)) mnextra = 10 ** 18 for v in frm: e, g = dp[v] e += max(req - (e + g), 0) if e < mnextra: mnextra, mni = e, v extra, tot_gain = mnextra, sum(dp[v][1] for v in frm) for v in frm: s.merge(u, v) dp[s.leader(u)] = extra, tot_gain visited[u] = True ans = sum(dp[s.leader(0)]) print(ans)
train
APPS_structured
Every day we can send from the server a certain limit of e-mails. Task: Write a function that will return the integer number of e-mails sent in the percentage of the limit. Example: ``` limit - 1000; emails sent - 101; return - 10%; // becouse integer from 10,1 = 10 ``` Arguments: Integer, limit; Integer, number of e-mails sent today; When: the argument ```$sent = 0```, then return the message: "No e-mails sent"; the argument ```$sent >= $limit```, then return the message: "Daily limit is reached"; the argument ```$limit is empty```, then default ```$limit = 1000``` emails; Good luck!
def get_percentage(a, b=1000): return "No e-mails sent" if not a else "Daily limit is reached" if a >= b else f"{int(a / b * 100)}%"
def get_percentage(a, b=1000): return "No e-mails sent" if not a else "Daily limit is reached" if a >= b else f"{int(a / b * 100)}%"
train
APPS_structured
Chef changed the password of his laptop a few days ago, but he can't remember it today. Luckily, he wrote the encrypted password on a piece of paper, along with the rules for decryption. The encrypted password is a string S consists of ASCII printable characters except space (ASCII 33 - 126, in decimal notation, the same below). Read here for more details: ASCII printable characters. Each rule contains a pair of characters ci, pi, denoting that every character ci appears in the encrypted password should be replaced with pi. Notice that it is not allowed to do multiple replacements on a single position, see example case 1 for clarification. After all the character replacements, the string is guaranteed to be a positive decimal number. The shortest notation of this number is the real password. To get the shortest notation, we should delete all the unnecessary leading and trailing zeros. If the number contains only non-zero fractional part, the integral part should be omitted (the shortest notation of "0.5" is ".5"). If the number contains zero fractional part, the decimal point should be omitted as well (the shortest notation of "5.00" is "5"). Please help Chef to find the real password. -----Input----- The first line of the input contains an interger T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single interger N, denoting the number of rules. Each of the next N lines contains two space-separated characters ci and pi, denoting a rule. The next line contains a string S, denoting the encrypted password. -----Output----- For each test case, output a single line containing the real password. -----Constraints----- - 1 ≤ T ≤ 1000 - 0 ≤ N ≤ 94 - All characters in S and ci may be any ASCII printable character except space. (ASCII 33 - 126) - All ci in a single test case are distinct. - pi is a digit ("0" - "9") or a decimal point "." (ASCII 46). - The total length of S in a single input file will not exceed 106. -----Example----- Input: 4 2 5 3 3 1 5 0 01800.00 0 0.00100 3 x 0 d 3 # . 0xd21#dd098x Output: 3 1800 .001 321.33098
for _ in range(int(input())): n=int(input()) rule=[] ci="" pi="" for _ in range(n): c,p=input().split() ci+=c pi+=p trans=str.maketrans(ci,pi) s=input() s=s.translate(trans) s="".join(s) dot = s.find(".") if dot!=-1: s=s.strip("0").rstrip(".") else: s=s.lstrip("0") if s=="": print(0) else: print(s)
for _ in range(int(input())): n=int(input()) rule=[] ci="" pi="" for _ in range(n): c,p=input().split() ci+=c pi+=p trans=str.maketrans(ci,pi) s=input() s=s.translate(trans) s="".join(s) dot = s.find(".") if dot!=-1: s=s.strip("0").rstrip(".") else: s=s.lstrip("0") if s=="": print(0) else: print(s)
train
APPS_structured
Chef has $N$ doggo (dogs) , Lets number them $1$ to $N$. Chef decided to build houses for each, but he soon realizes that keeping so many dogs at one place may be messy. So he decided to divide them into several groups called doggo communities. Let the total no. of groups be $K$ . In a community, paths between pairs of houses can be made so that doggo can play with each other. But there cannot be a path between two houses of different communities for sure. Chef wanted to make maximum no. of paths such that the total path is not greater then $K$. Let’s visualize this problem in an engineer's way :) The problem is to design a graph with max edge possible such that the total no. of edges should not be greater than the total no. of connected components. -----INPUT FORMAT----- - First line of each test case file contain $T$ , denoting total number of test cases. - $ith$ test case contain only one line with a single integer $N$ , denoting the number of dogs(vertex) -----OUTPUT FORMAT----- - For each test case print a line with a integer , denoting the maximum possible path possible. -----Constraints----- - $1 \leq T \leq 10000$ - $1 \leq N \leq 10^9$ -----Sub-Tasks----- - $20 Points$ - $1 \leq N \leq 10^6$ -----Sample Input----- 1 4 -----Sample Output----- 2 -----Explanation----- 4 houses can be made with like this: community #1 : [1 - 2 ] community #2 : [3 - 4 ] or [1 - 2 - 3] , [ 4 ] In both cases the maximum possible path is 2.
# cook your dish here import sys def get_array(): return list(map(int , sys.stdin.readline().strip().split())) def get_ints(): return list(map(int, sys.stdin.readline().strip().split())) def input(): return sys.stdin.readline().strip() import math from collections import defaultdict from itertools import combinations_with_replacement,permutations import bisect import math as mt from functools import reduce import time def __starting_point(): for _ in range(int(input())): n = int(input()) a=1 b=1 c=(-2*n) dis = b * b - 4 * a * c sqrt_val = math.sqrt(abs(dis)) r1=(-b + sqrt_val)/(2 * a) # r2=(-b - sqrt_val)/(2 * a) # print(r1) r1 = math.floor(r1)+1 print(n-r1+1) __starting_point()
# cook your dish here import sys def get_array(): return list(map(int , sys.stdin.readline().strip().split())) def get_ints(): return list(map(int, sys.stdin.readline().strip().split())) def input(): return sys.stdin.readline().strip() import math from collections import defaultdict from itertools import combinations_with_replacement,permutations import bisect import math as mt from functools import reduce import time def __starting_point(): for _ in range(int(input())): n = int(input()) a=1 b=1 c=(-2*n) dis = b * b - 4 * a * c sqrt_val = math.sqrt(abs(dis)) r1=(-b + sqrt_val)/(2 * a) # r2=(-b - sqrt_val)/(2 * a) # print(r1) r1 = math.floor(r1)+1 print(n-r1+1) __starting_point()
train
APPS_structured
We are given a list schedule of employees, which represents the working time for each employee. Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order. Return the list of finite intervals representing common, positive-length free time for all employees, also in sorted order. Example 1: Input: schedule = [[[1,2],[5,6]],[[1,3]],[[4,10]]] Output: [[3,4]] Explanation: There are a total of three employees, and all common free time intervals would be [-inf, 1], [3, 4], [10, inf]. We discard any intervals that contain inf as they aren't finite. Example 2: Input: schedule = [[[1,3],[6,7]],[[2,4]],[[2,5],[9,12]]] Output: [[5,6],[7,9]] (Even though we are representing Intervals in the form [x, y], the objects inside are Intervals, not lists or arrays. For example, schedule[0][0].start = 1, schedule[0][0].end = 2, and schedule[0][0][0] is not defined.) Also, we wouldn't include intervals like [5, 5] in our answer, as they have zero length. Note: schedule and schedule[i] are lists with lengths in range [1, 50]. 0 .
class Solution: def intersectionSizeTwo(self, intervals): """ :type intervals: List[List[int]] :rtype: int """ intervals.sort(key=lambda inter: (inter[1], -inter[0])) res=0 left,right=-1,-1 # current second largest, and largest for inter in intervals: # assume each inter[0]<inter[1] if inter[0]<=left: # two overlap, skip this inter, cc for intervals with the same inter[1] continue # current inter[0] is not greater than previou inter[0], so at least (left,right) are overlap elements if inter[0]>right: # greater than current largest, no overlap, need add new [left, right] res+=2 right=inter[1] # greedy, use the two largest num in this inter left=right-1 elif inter[0]<=right: # one overlap with current largest res+=1 left=right right=inter[1] return res
class Solution: def intersectionSizeTwo(self, intervals): """ :type intervals: List[List[int]] :rtype: int """ intervals.sort(key=lambda inter: (inter[1], -inter[0])) res=0 left,right=-1,-1 # current second largest, and largest for inter in intervals: # assume each inter[0]<inter[1] if inter[0]<=left: # two overlap, skip this inter, cc for intervals with the same inter[1] continue # current inter[0] is not greater than previou inter[0], so at least (left,right) are overlap elements if inter[0]>right: # greater than current largest, no overlap, need add new [left, right] res+=2 right=inter[1] # greedy, use the two largest num in this inter left=right-1 elif inter[0]<=right: # one overlap with current largest res+=1 left=right right=inter[1] return res
train
APPS_structured
=====Problem Statement===== Neo has a complex matrix script. The matrix script is a NXM grid of strings. It consists of alphanumeric characters, spaces and symbols (!,@,#,$,%,&). To decode the script, Neo needs to read each column and select only the alphanumeric characters and connect them. Neo reads the column from top to bottom and starts reading from the leftmost column. If there are symbols or spaces between two alphanumeric characters of the decoded script, then Neo replaces them with a single space '' for better readability. Neo feels that there is no need to use 'if' conditions for decoding. Alphanumeric characters consist of: [A-Z, a-z, and 0-9]. =====Input Format===== The first line contains space-separated integers N (rows) and M (columns) respectively. The next N lines contain the row elements of the matrix script. =====Constraints===== 0<N,M<100 Note: A 0 score will be awarded for using 'if' conditions in your code. =====Output Format===== Print the decoded matrix script.
import re n, m = list(map(int,input().split())) character_ar = [''] * (n*m) for i in range(n): line = input() for j in range(m): character_ar[i+(j*n)]=line[j] decoded_str = ''.join(character_ar) final_decoded_str = re.sub(r'(?<=[A-Za-z0-9])([ !@#$%&]+)(?=[A-Za-z0-9])',' ',decoded_str) print(final_decoded_str)
import re n, m = list(map(int,input().split())) character_ar = [''] * (n*m) for i in range(n): line = input() for j in range(m): character_ar[i+(j*n)]=line[j] decoded_str = ''.join(character_ar) final_decoded_str = re.sub(r'(?<=[A-Za-z0-9])([ !@#$%&]+)(?=[A-Za-z0-9])',' ',decoded_str) print(final_decoded_str)
train
APPS_structured
The function sigma 1, σ1 in mathematics, is known as the one that gives the sum of the divisors of an integer number. For example for the number 10, ```python σ1(10) = 18 # because the divisors of 10 are: 1, 2, 5, 10 σ1(10) = 1 + 2 + 5 + 10 = 18 ``` You can see the graph of this important function up to 250: The number 528 and its reversed, 825 have equal value for the function σ1. ```python σ1(528) = σ1(825) divisors of 528 are: 1, 2, 3, 4, 6, 8, 11, 12, 16, 22, 24, 33, 44, 48, 66, 88, 132, 176, 264 and 528 the sum of the divisors of 528 is 1488 divisors of 825 are: 1, 3, 5, 11, 15, 25, 33, 55, 75, 165, 275 and 825 the sum of the divisors of 825 is 1488 ``` In fact 528 is the smallest non palindromic integer that has this property. We need a function, ```equal_sigma1()```, that may collect all the positive integers that fulfill the property described above. The function receives an upper limit, ```nMax```, will output the total sum of these numbers and its reversed while are less or equal nMax. Let's see some cases: ```python equal_sigma1(100) = 0 # There are no numbers. equal_sigma1(1000) = 1353 # 528 and its revesed 825 were found, 528 + 825 = 1353 equal_sigma1(2000) = 4565 # There are four numbers_: 528 + 825 + 1561 + 1651 = 4565 equal_sigma1(1600) = 2914 # Now we have three numbers: 528 + 825 + 1561 = 2914 equal_sigma1(1561) = 2914 ``` The palindromic numbers (like 88, 808, 929), numbers that are equal to its reversed should be discarded. Happy coding!! (For more information about the general sigma function see at: https://en.wikipedia.org/wiki/Divisor_function)
def sigma1(n): ans = 0 for i in xrange(1,int(n**0.5) + 1): if n % i == 0: ans += i + n / i return ans if n ** 0.5 % 1 != 0 else ans - int(n ** 0.5) def equal_sigma1(n_max): ans = 0 for i in xrange(528,n_max+1): j = int(str(i)[::-1]) if i != j and sigma1(i) == sigma1(j):ans += i return ans
def sigma1(n): ans = 0 for i in xrange(1,int(n**0.5) + 1): if n % i == 0: ans += i + n / i return ans if n ** 0.5 % 1 != 0 else ans - int(n ** 0.5) def equal_sigma1(n_max): ans = 0 for i in xrange(528,n_max+1): j = int(str(i)[::-1]) if i != j and sigma1(i) == sigma1(j):ans += i return ans
train
APPS_structured
The aim of this Kata is to write a function which will reverse the case of all consecutive duplicate letters in a string. That is, any letters that occur one after the other and are identical. If the duplicate letters are lowercase then they must be set to uppercase, and if they are uppercase then they need to be changed to lowercase. **Examples:** ```python reverse_case("puzzles") Expected Result: "puZZles" reverse_case("massive") Expected Result: "maSSive" reverse_case("LITTLE") Expected Result: "LIttLE" reverse_case("shhh") Expected Result: "sHHH" ``` Arguments passed will include only alphabetical letters A–Z or a–z.
from itertools import groupby def reverse(str): reversal="" for k,g in groupby(str): l=list(g) if len(l)>1:reversal+=''.join(l).swapcase() else:reversal+=k return reversal
from itertools import groupby def reverse(str): reversal="" for k,g in groupby(str): l=list(g) if len(l)>1:reversal+=''.join(l).swapcase() else:reversal+=k return reversal
train
APPS_structured
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said # Description: Given a string `str` that contains some "(" or ")". Your task is to find the longest substring in `str`(all brackets in the substring are closed). The result is the length of the longest substring. For example: ``` str = "()()(" findLongest(str) === 4 "()()" is the longest substring ``` # Note: - All inputs are valid. - If no such substring found, return 0. - Please pay attention to the performance of code. ;-) - In the performance test(100000 brackets str x 100 testcases), the time consuming of each test case should be within 35ms. This means, your code should run as fast as a rocket ;-) # Some Examples ``` findLongest("()") === 2 findLongest("()(") === 2 findLongest("()()") === 4 findLongest("()()(") === 4 findLongest("(()())") === 6 findLongest("(()(())") === 6 findLongest("())(()))") === 4 findLongest("))((") === 0 findLongest("") === 0 ```
def find_longest(string): n = len(string) # Create a stack and push -1 as initial index to it. stk = [] stk.append(-1) # Initialize result result = 0 # Traverse all characters of given string for i in range(n): # If opening bracket, push index of it if string[i] == '(': stk.append(i) else: # If closing bracket, i.e., str[i] = ')' # Pop the previous opening bracket's index stk.pop() # Check if this length formed with base of # current valid substring is more than max # so far if len(stk) != 0: result = max(result, i - stk[len(stk)-1]) # If stack is empty. push current index as # base for next valid substring (if any) else: stk.append(i) return result
def find_longest(string): n = len(string) # Create a stack and push -1 as initial index to it. stk = [] stk.append(-1) # Initialize result result = 0 # Traverse all characters of given string for i in range(n): # If opening bracket, push index of it if string[i] == '(': stk.append(i) else: # If closing bracket, i.e., str[i] = ')' # Pop the previous opening bracket's index stk.pop() # Check if this length formed with base of # current valid substring is more than max # so far if len(stk) != 0: result = max(result, i - stk[len(stk)-1]) # If stack is empty. push current index as # base for next valid substring (if any) else: stk.append(i) return result
train
APPS_structured
# Task The function `fold_cube(number_list)` should return a boolean based on a net (given as a number list), if the net can fold into a cube. Your code must be effecient and complete the tests within 500ms. ## Input Imagine a net such as the one below. ``` @ @ @ @ @ @ ``` Then, put it on the table with each `@` being one cell. ``` -------------------------- | 1 | 2 | 3 | 4 | 5 | -------------------------- | 6 | 7 | 8 | 9 | 10 | -------------------------- | 11 | 12 | 13 | 14 | 15 | -------------------------- | 16 | 17 | 18 | 19 | 20 | -------------------------- | 21 | 22 | 23 | 24 | 25 | -------------------------- ``` The number list for a net will be the numbers the net falls on when placed on the table. Note that the numbers in the list won't always be in order. The position of the net can be anywhere on the table, it can also be rotated. For the example above, a possible number list will be `[1, 7, 8, 6, 9, 13]`. ## Output `fold_cube` should return `True` if the net can be folded into a cube. `False` if not. --- # Examples ### Example 1: `number_list` = `[24, 20, 14, 19, 18, 9]` Shape and rotation of net: ``` @ @ @ @ @ @ ``` Displayed on the table: ``` -------------------------- | 1 | 2 | 3 | 4 | 5 | -------------------------- | 6 | 7 | 8 | @ | 10 | -------------------------- | 11 | 12 | 13 | @ | 15 | -------------------------- | 16 | 17 | @ | @ | @ | -------------------------- | 21 | 22 | 23 | @ | 25 | -------------------------- ``` So, `fold_cube([24, 20, 14, 19, 18, 9])` should return `True`. ### Example 2: `number_list` = `[1, 7, 6, 17, 12, 16]` Shape and rotation of net: ``` @ @ @ @ @ @ ``` Displayed on the table: ``` -------------------------- | @ | 2 | 3 | 4 | 5 | -------------------------- | @ | @ | 8 | 9 | 10 | -------------------------- | 11 | @ | 13 | 14 | 15 | -------------------------- | @ | @ | 18 | 19 | 20 | -------------------------- | 21 | 22 | 23 | 24 | 25 | -------------------------- ``` `fold_cube([1, 7, 6, 17, 12, 16])` should return `False`. #### *Translations appreciated!!* --- ### If you liked this kata.... check out these! - [Folding a 4D Cube (Tesseract)](https://www.codewars.com/kata/5f3b561bc4a71f000f191ef7) - [Wraping a net around a cube](https://www.codewars.com/kata/5f4af9c169f1cd0001ae764d)
BASE = {' x\nxxx\n x \n x ', ' x\n x\nxx\nx \nx ', ' x \n xx\nxx \n x ', 'xx \n xx\n x \n x ', ' x \n xx\nxx \nx ', 'xxx\n x \n x \n x ', 'xx \n x \n xx\n x ', 'xx \n x \n xx\n x', 'xx \n x \n x \n xx', ' xx\n xx \nxx ', ' x \nxxx\n x \n x '} def reflect(s): return '\n'.join(r[::-1] for r in s.split('\n')) def rotate(s): return '\n'.join(''.join(c[::-1]) for c in zip(*s.split('\n'))) def fold_cube(arr): table = [[' '] * 5 for _ in range(5)] x0, y0, x1, y1 = 4, 4, 0, 0 for p in arr: x, y = divmod(p - 1, 5) table[x][y] = 'x' x0, y0 = min(x, x0), min(y, y0) x1, y1 = max(x, x1), max(y, y1) net = '\n'.join(''.join(r[y0:y1 + 1]) for r in table[x0:x1 + 1]) net2 = reflect(net) for i in range(4): if net in BASE or net2 in BASE: return True net, net2 = rotate(net), rotate(net2) return False
BASE = {' x\nxxx\n x \n x ', ' x\n x\nxx\nx \nx ', ' x \n xx\nxx \n x ', 'xx \n xx\n x \n x ', ' x \n xx\nxx \nx ', 'xxx\n x \n x \n x ', 'xx \n x \n xx\n x ', 'xx \n x \n xx\n x', 'xx \n x \n x \n xx', ' xx\n xx \nxx ', ' x \nxxx\n x \n x '} def reflect(s): return '\n'.join(r[::-1] for r in s.split('\n')) def rotate(s): return '\n'.join(''.join(c[::-1]) for c in zip(*s.split('\n'))) def fold_cube(arr): table = [[' '] * 5 for _ in range(5)] x0, y0, x1, y1 = 4, 4, 0, 0 for p in arr: x, y = divmod(p - 1, 5) table[x][y] = 'x' x0, y0 = min(x, x0), min(y, y0) x1, y1 = max(x, x1), max(y, y1) net = '\n'.join(''.join(r[y0:y1 + 1]) for r in table[x0:x1 + 1]) net2 = reflect(net) for i in range(4): if net in BASE or net2 in BASE: return True net, net2 = rotate(net), rotate(net2) return False
train
APPS_structured
Mr. X stays in a mansion whose door opens in the North. He travels every morning to meet his friend Ms. Y walking a predefined path. To cut the distance short, one day he decides to construct a skywalk from his place to his friend’s place. Help him to find the shortest distance between the two residences. -----Input----- The first line contains a single positive integer T <= 100, the number of test cases. T test cases follow. The only line of each test case contains a string which is the path from X to Y. The integer value represents the distance. The character R or L represents a Right or a Left respectively. -----Output----- For each test case, output a single line containing the minimum distance and the direction(N,S,W,E,NE,NW,SE,SW) of Y’s residence with respect to X’s residence. The output distance should have only 1 decimal place with no approximation. Print “0.0” if X’s and Y’s residence coincide. -----Example----- Input: 1 2 L 2 R 2 L 1 Output: 5.0NW Explanation Mr. X travels 2units and then takes a Left, and then he travels 2units and takes a Right, then after travelling 2units he takes a Left and finally travels 1unit to reach Y’s residence. (Unlike Input, Output does not have spaces between the distance and direction)
#input must be invalid because no runtime error after handling invalid input def parse(movestr): moves = [] acc = "" for char in movestr: char = char.upper() if char == "R" or char == "L": if acc != "": moves.append(int(acc)) acc = "" moves.append(char) elif char.isdigit(): acc += char elif len(acc) > 0: moves.append(int(acc)) acc = "" if len(acc) > 0: moves.append(int(acc)) return moves def make_move(x,y,direc,dist): if direc == 0: #north y += dist elif direc == 1: #west x -= dist elif direc == 2: #south y -= dist elif direc == 3: #east x += dist return x,y def calc(moves): x,y = 0,0 direc = 0 for move in moves: if move == "L": direc = (direc+1)%4 elif move == "R": direc = (direc-1)%4 else: x,y = make_move(x,y,direc,move) return x,y def string(dist): d = str(dist) k = d.find(".") return d[:k+2] cases = int(input()) for case in range(cases): movestr = input().replace(" ","") moves = parse(movestr) x,y = calc(moves) dist = (x**2 + y**2)**0.5 if x == 0: if y == 0: direc = "" elif y < 0: direc = "S" else: direc = "N" elif x < 0: if y == 0: direc = "W" elif y < 0: direc = "SW" else: direc = "NW" else: if y == 0: direc = "E" elif y < 0: direc = "SE" else: direc = "NE" print("%s%s" %(string(dist),direc))
#input must be invalid because no runtime error after handling invalid input def parse(movestr): moves = [] acc = "" for char in movestr: char = char.upper() if char == "R" or char == "L": if acc != "": moves.append(int(acc)) acc = "" moves.append(char) elif char.isdigit(): acc += char elif len(acc) > 0: moves.append(int(acc)) acc = "" if len(acc) > 0: moves.append(int(acc)) return moves def make_move(x,y,direc,dist): if direc == 0: #north y += dist elif direc == 1: #west x -= dist elif direc == 2: #south y -= dist elif direc == 3: #east x += dist return x,y def calc(moves): x,y = 0,0 direc = 0 for move in moves: if move == "L": direc = (direc+1)%4 elif move == "R": direc = (direc-1)%4 else: x,y = make_move(x,y,direc,move) return x,y def string(dist): d = str(dist) k = d.find(".") return d[:k+2] cases = int(input()) for case in range(cases): movestr = input().replace(" ","") moves = parse(movestr) x,y = calc(moves) dist = (x**2 + y**2)**0.5 if x == 0: if y == 0: direc = "" elif y < 0: direc = "S" else: direc = "N" elif x < 0: if y == 0: direc = "W" elif y < 0: direc = "SW" else: direc = "NW" else: if y == 0: direc = "E" elif y < 0: direc = "SE" else: direc = "NE" print("%s%s" %(string(dist),direc))
train
APPS_structured
Given a number return the closest number to it that is divisible by 10. Example input: ``` 22 25 37 ``` Expected output: ``` 20 30 40 ```
def closest_multiple_10(i): r = i % 10 return i - r if r < 5 else i - r + 10
def closest_multiple_10(i): r = i % 10 return i - r if r < 5 else i - r + 10
train
APPS_structured
# Story John found a path to a treasure, and while searching for its precise location he wrote a list of directions using symbols `"^"`, `"v"`, `"<"`, `">"` which mean `north`, `east`, `west`, and `east` accordingly. On his way John had to try many different paths, sometimes walking in circles, and even missing the treasure completely before finally noticing it. ___ ## Task Simplify the list of directions written by John by eliminating any loops. **Note**: a loop is any sublist of directions which leads John to the coordinate he had already visited. ___ ## Examples ``` simplify("<>>") == ">" simplify("<^^>v<^^^") == "<^^^^" simplify("") == "" simplify("^< > v ^ v > > C > D > > ^ ^ v ^ < B < < ^ A ``` John visits points `A -> B -> C -> D -> B -> C -> D`, realizes that `-> C -> D -> B` steps are meaningless and removes them, getting this path: `A -> B -> (*removed*) -> C -> D`. ``` ∙ ∙ ∙ ∙ ∙ > > C > D > > ^ ∙ ∙ ^ < B ∙ ∙ ^ A ``` Following the final, simplified route John visits points `C` and `D`, but for the first time, not the second (because we ignore the steps made on a hypothetical path), and he doesn't need to alter the directions list anymore.
def simplify(path): location = (0,0) new_path = path new_path_locations = [location] for d in path: if d == '<': location = (location[0]-1, location[1]) elif d == '>': location = (location[0]+1, location[1]) elif d == 'v': location = (location[0], location[1]+1) else: location = (location[0], location[1]-1) if location in new_path_locations: i = new_path_locations.index(location) remove_length = len(new_path_locations) - i new_path_locations = new_path_locations[:i+1] # leave the current location new_path = new_path[:i] + new_path[i+remove_length:] else: new_path_locations.append(location) return new_path
def simplify(path): location = (0,0) new_path = path new_path_locations = [location] for d in path: if d == '<': location = (location[0]-1, location[1]) elif d == '>': location = (location[0]+1, location[1]) elif d == 'v': location = (location[0], location[1]+1) else: location = (location[0], location[1]-1) if location in new_path_locations: i = new_path_locations.index(location) remove_length = len(new_path_locations) - i new_path_locations = new_path_locations[:i+1] # leave the current location new_path = new_path[:i] + new_path[i+remove_length:] else: new_path_locations.append(location) return new_path
train
APPS_structured
Write a function that returns the number of '2's in the factorization of a number. For example, ```python two_count(24) ``` should return 3, since the factorization of 24 is 2^3 x 3 ```python two_count(17280) ``` should return 7, since the factorization of 17280 is 2^7 x 5 x 3^3 The number passed to two_count (twoCount) will always be a positive integer greater than or equal to 1.
def two_count(n): if n%2 != 0: return 0 else: return 1 + two_count(n//2)
def two_count(n): if n%2 != 0: return 0 else: return 1 + two_count(n//2)
train
APPS_structured
Consider a sequence, which is formed by the following rule: next term is taken as the smallest possible non-negative integer, which is not yet in the sequence, so that `no 3` terms of sequence form an arithmetic progression. ## Example `f(0) = 0` -- smallest non-negative `f(1) = 1` -- smallest non-negative, which is not yet in the sequence `f(2) = 3` -- since `0, 1, 2` form an arithmetic progression `f(3) = 4` -- neither of `0, 1, 4`, `0, 3, 4`, `1, 3, 4` form an arithmetic progression, so we can take smallest non-negative, which is larger than `3` `f(4) = 9` -- `5, 6, 7, 8` are not good, since `1, 3, 5`, `0, 3, 6`, `1, 4, 7`, `0, 4, 8` are all valid arithmetic progressions. etc... ## The task Write a function `f(n)`, which returns the `n-th` member of sequence. ## Limitations There are `1000` random tests with `0 <= n <= 10^9`, so you should consider algorithmic complexity of your solution.
def sequence(n): return int(format(n, 'b'), 3)
def sequence(n): return int(format(n, 'b'), 3)
train
APPS_structured
Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order. Examples 1 Input: 5 / \ 2 -3 return [2, -3, 4], since all the values happen only once, return all of them in any order. Examples 2 Input: 5 / \ 2 -5 return [2], since 2 happens twice, however -5 only occur once. Note: You may assume the sum of values in any subtree is in the range of 32-bit signed integer.
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def findFrequentTreeSum(self, root): """ :type root: TreeNode :rtype: List[int] """ res = dict() def helper(root): if not root: return 0 val = root.val + helper(root.left) + helper(root.right) if val in res: res[val] += 1 else: res[val] = 1 return val helper(root) if not res: return [] max_val = max(res.values()) return [k for k, v in res.items() if v == max_val]
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def findFrequentTreeSum(self, root): """ :type root: TreeNode :rtype: List[int] """ res = dict() def helper(root): if not root: return 0 val = root.val + helper(root.left) + helper(root.right) if val in res: res[val] += 1 else: res[val] = 1 return val helper(root) if not res: return [] max_val = max(res.values()) return [k for k, v in res.items() if v == max_val]
train
APPS_structured
----- ARRAY AND DISTINCT ELEMENTS ----- Chef is multitalented but he mistakenly took part in 2 contest which will take place at the same time. So while chef is busy at one cooking contest, he wants you to take part in coding contest. Chef wants u to solve this program for him. You have been given an array of size n. You have to calculate a subarray of size k with maximum sum having distinct elements same as original array. -----Input Format----- First line contains no. of test cases. Second line contains n and k. Third line contains array of n integers. -----Output----- Print maximum possible sum as stated in question -----Example Text Case----- Input: 1 10 6 8 8 3 5 3 8 5 7 7 7 Output: 37
# cook your dish here for u in range(int(input())): n,k=list(map(int,input().split())) l=list(map(int,input().split())) m=0 s=set(l) r=len(s) for i in range(n-k+1): c=0 d=set() for j in range(i,i+k): c+=l[j] d.add(l[j]) if(len(d)==r): m=max(m,c) print(m)
# cook your dish here for u in range(int(input())): n,k=list(map(int,input().split())) l=list(map(int,input().split())) m=0 s=set(l) r=len(s) for i in range(n-k+1): c=0 d=set() for j in range(i,i+k): c+=l[j] d.add(l[j]) if(len(d)==r): m=max(m,c) print(m)
train
APPS_structured
Given the root of a binary tree, then value v and depth d, you need to add a row of nodes with value v at the given depth d. The root node is at depth 1. The adding rule is: given a positive integer depth d, for each NOT null tree nodes N in depth d-1, create two tree nodes with value v as N's left subtree root and right subtree root. And N's original left subtree should be the left subtree of the new left subtree root, its original right subtree should be the right subtree of the new right subtree root. If depth d is 1 that means there is no depth d-1 at all, then create a tree node with value v as the new root of the whole original tree, and the original tree is the new root's left subtree. Example 1: Input: A binary tree as following: 4 / \ 2 6 / \ / 3 1 5 v = 1 d = 2 Output: 4 / \ 1 1 / \ 2 6 / \ / 3 1 5 Example 2: Input: A binary tree as following: 4 / 2 / \ 3 1 v = 1 d = 3 Output: 4 / 2 / \ 1 1 / \ 3 1 Note: The given d is in range [1, maximum depth of the given tree + 1]. The given binary tree has at least one tree node.
class Solution: def addOneRow(self, root, v, d): """ :type root: TreeNode :type v: int :type d: int :rtype: TreeNode """ # if d == 1: # 广度搜索 64ms # newroot = TreeNode(v) # newroot.left = root # return newroot # lastlevel = [] # cur = 1 # curlevel = [root] # nextlevel = [] # while cur < d: # for node in curlevel: # if node: # nextlevel.append(node.left) # nextlevel.append(node.right) # lastlevel = curlevel # curlevel = nextlevel # nextlevel = [] # cur += 1 # count = 0 # for node in lastlevel: # if node: # templeft, tempright = TreeNode(v), TreeNode(v) # templeft.left = curlevel[count] # tempright.right = curlevel[count+1] # count += 2 # node.left = templeft # node.right = tempright # return root if d == 1: newroot = TreeNode(v) newroot.left = root return newroot queue = [(root, 1)] for node, level in queue: if node.left: queue.append((node.left, level+1)) if node.right: queue.append((node.right, level+1)) if level == d-1: newleft = TreeNode(v) newleft.left = node.left newright = TreeNode(v) newright.right = node.right node.left = newleft node.right = newright return root
class Solution: def addOneRow(self, root, v, d): """ :type root: TreeNode :type v: int :type d: int :rtype: TreeNode """ # if d == 1: # 广度搜索 64ms # newroot = TreeNode(v) # newroot.left = root # return newroot # lastlevel = [] # cur = 1 # curlevel = [root] # nextlevel = [] # while cur < d: # for node in curlevel: # if node: # nextlevel.append(node.left) # nextlevel.append(node.right) # lastlevel = curlevel # curlevel = nextlevel # nextlevel = [] # cur += 1 # count = 0 # for node in lastlevel: # if node: # templeft, tempright = TreeNode(v), TreeNode(v) # templeft.left = curlevel[count] # tempright.right = curlevel[count+1] # count += 2 # node.left = templeft # node.right = tempright # return root if d == 1: newroot = TreeNode(v) newroot.left = root return newroot queue = [(root, 1)] for node, level in queue: if node.left: queue.append((node.left, level+1)) if node.right: queue.append((node.right, level+1)) if level == d-1: newleft = TreeNode(v) newleft.left = node.left newright = TreeNode(v) newright.right = node.right node.left = newleft node.right = newright return root
train
APPS_structured
Given 3 positives numbers a, b and c. Return the minimum flips required in some bits of a and b to make ( a OR b == c ). (bitwise OR operation). Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation. Example 1: Input: a = 2, b = 6, c = 5 Output: 3 Explanation: After flips a = 1 , b = 4 , c = 5 such that (a OR b == c) Example 2: Input: a = 4, b = 2, c = 7 Output: 1 Example 3: Input: a = 1, b = 2, c = 3 Output: 0 Constraints: 1 <= a <= 10^9 1 <= b <= 10^9 1 <= c <= 10^9
class Solution: def minFlips(self, a: int, b: int, c: int) -> int: flips = 0 print(bin(a)) print(bin(b)) print(bin(c)) while a or b or c: # print(a, b, c) if c % 2: if not (a % 2 or b % 2): flips += 1 else: flips += a % 2 + b % 2 a //= 2 b //= 2 c //= 2 return flips
class Solution: def minFlips(self, a: int, b: int, c: int) -> int: flips = 0 print(bin(a)) print(bin(b)) print(bin(c)) while a or b or c: # print(a, b, c) if c % 2: if not (a % 2 or b % 2): flips += 1 else: flips += a % 2 + b % 2 a //= 2 b //= 2 c //= 2 return flips
train
APPS_structured
=====Problem Statement===== You are given a function f(X) = X^2. You are also given K lists. The ith list consists of N_i elements. You have to pick one element from each list so that the value from the equation below is maximized: S = (f(X_1) + f(X_2) + ... + f(X_k))%M X_i denotes the element picked from the ith list. Find the maximized value S_max obtained. % denotes the modulo operator. Note that you need to take exactly one element from each list, not necessarily the largest element. You add the squares of the chosen elements and perform the modulo operation. The maximum value that you can obtain, will be the answer to the problem. =====Input Format===== The first line contains 2 space separated integers K and M. The next K lines each contains an integer N_i, denoting the number of elements in the ith list, followed by space separated integers denoting the elements in the list. =====Constraints===== 1≤K≤7 1≤M≤1000 1≤N_i≤7 1≤Magnitude of elements in list≤10^9 =====Output Format===== Output a single integer denoting the value S_max.
#!/usr/bin/env python3 from itertools import product K,M = list(map(int,input().split())) N = (list(map(int, input().split()))[1:] for _ in range(K)) results = [sum(i**2 for i in x)%M for x in product(*N)] print((max(results)))
#!/usr/bin/env python3 from itertools import product K,M = list(map(int,input().split())) N = (list(map(int, input().split()))[1:] for _ in range(K)) results = [sum(i**2 for i in x)%M for x in product(*N)] print((max(results)))
train
APPS_structured
We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself. Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not. Example: Input: 28 Output: True Explanation: 28 = 1 + 2 + 4 + 7 + 14 Note: The input number n will not exceed 100,000,000. (1e8)
class Solution: def checkPerfectNumber(self, num): """ :type num: int :rtype: bool """ if num <= 1: return False factors = [] for i in range(1, int(num ** 0.5) + 1): if num % i == 0: factors.append(i) for factor in factors: if num / factor not in factors and factor > 1: factors.append(num / factor) if num == sum(i for i in factors): return True else: return False
class Solution: def checkPerfectNumber(self, num): """ :type num: int :rtype: bool """ if num <= 1: return False factors = [] for i in range(1, int(num ** 0.5) + 1): if num % i == 0: factors.append(i) for factor in factors: if num / factor not in factors and factor > 1: factors.append(num / factor) if num == sum(i for i in factors): return True else: return False
train
APPS_structured
Wet Shark once had 2 sequences: {a_n}= {a_1, a_2, a_3, ... , a_(109)} {b_n} = {b_1, b_2, b_3, ... , b_(109)} However, he only kept one element from each sequence. Luckily, both the elements that Wet Shark kept have the same index in Wet Shark's sequences: that is, he took a_i and b_i for some 1 ≤ i ≤ 109. Right after Wet Shark loses his sequences, he finds that he actually needs them to break the code of Cthulhu to escape a labyrinth. Cthulhu's code is a single floating point number Q. However, the code verifier is faulty. If Wet Shark enters any code c such that |c - Q| ≤ 0.01 , Cthulhu's code checker will allow him to escape. Wet Shark now starts to panic, and consults Dry Dolphin for help via ultrasonic waves. After the Dry Dolphin Sequence Processing Factory processes data of Wet Shark's sequences, the machines give Wet Shark the following 2 relations his sequences follow for all 1 ≤ n < 109, where x = sqrt(2) and y = sqrt(3). Wet Shark is now clueless on how to compute anything, and asks you for help. Wet Shark has discovered that Cthulhu's code is actually defined as Q = (a_k + b_k) / (2^s), where s is a predetermined number, k is the index of another element in Wet Shark's sequence, and a_k, b_k are precisely the kth elements of Wet Shark's sequences {a_n} and {b_n}, respectively. Given k, i, and the 2 elements of the arrays Wet Shark has lost, find any value of the code c that will allow Wet Shark to exit Cthulhu's labyrinth. -----Input----- The first line of input contains 3 space separated integers i, k, s — the common index of the two elements Wet Shark kept, the index of Wet Shark's array needed to break Cthulhu's code, and the number s described in the problem statement, respectively. It is guaranteed that Cthulhu's code, Q, is between -109 and 109 (both inclusive). The second line of the input contains 2 space separated integers a_i and b_i, representing the ith element of sequence {a_n} and the ith element of sequence {b_n}, respectively. -----Output----- Output any number c that will crack Cthulhu's code. Recall that if Wet Shark enters any code c such that |c - Q| ≤ 0.01 , Cthulhu's code checker will allow him to exit the labyrinth. ----- Constraints ----- - SUBTASK 1: 20 POINTS - 1 ≤ i ≤ 103 - 1 ≤ k ≤ 103 - -103 ≤ s ≤ 103 - 1 ≤ a_i, b_i ≤ 103 - SUBTASK 2: 80 POINTS - 1 ≤ i ≤ 1010 - 1 ≤ k ≤ 1010 - -1010 ≤ s ≤ 1010 - 1 ≤ a_i, b_i ≤ 1010 It is guaranteed that -1010 ≤ Q ≤  1010. -----Example----- Input: 1 1 5 4 5 Output: 0.28125 -----Explanation----- Example case 1. In this case, a_1 = 4, b_1 = 5, and s = 5. Cthulhu's code in this case is (a_1 + b_1) / (2s) = 9/32 = 0.28125.
import math def main(): #print("enter i, k, s") IN = '11 6 5' z = IN.split() z = input().split() i = int(z[0]) k = int(z[1]) s = int(z[2]) #print("enter a_i and b_i") IN = '4 5' z = IN.split() z = input().split() a_i = int(z[0]) b_i = int(z[1]) #print( "i = %d k = %d s = %d " % (i, k, s) ) #print( "a_i = %d b_i = %d" % (a_i, b_i) ) x = math.sqrt(2) y = math.sqrt(3) #print(x,y) # Obtaining the k-th element when k >= i if(i<=k): diff = k-i #if both k and i are odd or even if(k-i)%2==0: #print("#1") ans = (a_i + b_i) * math.pow(2,2*(k-i)-s) #diff = int(diff/2) #ans = (a_i + b_i) * math.pow(2,4*diff-s) #if i and k are of different parities then obtaining first # a_(i+1) and b_(i+1) else: #print("#2") ans = (2*x*a_i + 2*x*y*b_i) * math.pow(2,2*(k-(i+1))-s ) diff = int(diff/2) ans = (2*x*a_i + 2*x*y*b_i) * math.pow(2,4*diff - s) #print("1: ", (2*x*a_i + 2*x*y*b_i)) #print("2: ", math.pow(2,4*diff - 2- s)) #print("2 sol: ", math.pow(2,4*int(diff)-s)) #print("diff: ",diff) # Obtaining the k_th element when k < i else: diff = i-k #if both k and i are odd or even if(i-k)%2==0: #print("#3") ans = (a_i + b_i) / math.pow(2,2*(i-k)+s) #diff = int(diff/2) #ans = (a_i + b_i) / math.pow(2,4*diff+s) #if i and k are of different parities then obtaining first # a_(i+1) and b_(i+1) else: #print("#4") ans = (2*x*a_i + 2*x*y*b_i) / math.pow(2,2*(i+1-k)+s) diff = int(diff/2) ans = (2*x*a_i + 2*x*y*b_i) / math.pow(2,4*diff + 4 + s) print(ans) main()
import math def main(): #print("enter i, k, s") IN = '11 6 5' z = IN.split() z = input().split() i = int(z[0]) k = int(z[1]) s = int(z[2]) #print("enter a_i and b_i") IN = '4 5' z = IN.split() z = input().split() a_i = int(z[0]) b_i = int(z[1]) #print( "i = %d k = %d s = %d " % (i, k, s) ) #print( "a_i = %d b_i = %d" % (a_i, b_i) ) x = math.sqrt(2) y = math.sqrt(3) #print(x,y) # Obtaining the k-th element when k >= i if(i<=k): diff = k-i #if both k and i are odd or even if(k-i)%2==0: #print("#1") ans = (a_i + b_i) * math.pow(2,2*(k-i)-s) #diff = int(diff/2) #ans = (a_i + b_i) * math.pow(2,4*diff-s) #if i and k are of different parities then obtaining first # a_(i+1) and b_(i+1) else: #print("#2") ans = (2*x*a_i + 2*x*y*b_i) * math.pow(2,2*(k-(i+1))-s ) diff = int(diff/2) ans = (2*x*a_i + 2*x*y*b_i) * math.pow(2,4*diff - s) #print("1: ", (2*x*a_i + 2*x*y*b_i)) #print("2: ", math.pow(2,4*diff - 2- s)) #print("2 sol: ", math.pow(2,4*int(diff)-s)) #print("diff: ",diff) # Obtaining the k_th element when k < i else: diff = i-k #if both k and i are odd or even if(i-k)%2==0: #print("#3") ans = (a_i + b_i) / math.pow(2,2*(i-k)+s) #diff = int(diff/2) #ans = (a_i + b_i) / math.pow(2,4*diff+s) #if i and k are of different parities then obtaining first # a_(i+1) and b_(i+1) else: #print("#4") ans = (2*x*a_i + 2*x*y*b_i) / math.pow(2,2*(i+1-k)+s) diff = int(diff/2) ans = (2*x*a_i + 2*x*y*b_i) / math.pow(2,4*diff + 4 + s) print(ans) main()
train
APPS_structured
A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) consecutive times.  Given an array of integers rollMax and an integer n, return the number of distinct sequences that can be obtained with exact n rolls. Two sequences are considered different if at least one element differs from each other. Since the answer may be too large, return it modulo 10^9 + 7. Example 1: Input: n = 2, rollMax = [1,1,2,2,2,3] Output: 34 Explanation: There will be 2 rolls of die, if there are no constraints on the die, there are 6 * 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34. Example 2: Input: n = 2, rollMax = [1,1,1,1,1,1] Output: 30 Example 3: Input: n = 3, rollMax = [1,1,1,2,2,3] Output: 181 Constraints: 1 <= n <= 5000 rollMax.length == 6 1 <= rollMax[i] <= 15
class Solution: def dieSimulator(self, n: int, rollMax: List[int]) -> int: M = pow(10, 9) + 7 rollMax = [0] + rollMax dp = [[[0] * (15 + 1) for _ in range(6 + 1)] for _ in range(n + 1)] # 抛第一次骰子,出现数字 i 的次数 for i in range(1, 6 + 1): dp[1][i][1] = 1 for i in range(2, n + 1): # 第 i 次抛 for j in range(1, 6 + 1): # 得到骰子的num数 for k in range(1, rollMax[j] + 1): # 这个数字第 k次出现 if k > 1: dp[i][j][k] = dp[i-1][j][k-1] else: for jj in range(1, 6 + 1): for kk in range(1, rollMax[jj] + 1): if jj != j: dp[i][j][k] += dp[i-1][jj][kk] res = 0 for i in range(1, 7): for j in range(1, rollMax[i] + 1): res += dp[n][i][j] return res % M
class Solution: def dieSimulator(self, n: int, rollMax: List[int]) -> int: M = pow(10, 9) + 7 rollMax = [0] + rollMax dp = [[[0] * (15 + 1) for _ in range(6 + 1)] for _ in range(n + 1)] # 抛第一次骰子,出现数字 i 的次数 for i in range(1, 6 + 1): dp[1][i][1] = 1 for i in range(2, n + 1): # 第 i 次抛 for j in range(1, 6 + 1): # 得到骰子的num数 for k in range(1, rollMax[j] + 1): # 这个数字第 k次出现 if k > 1: dp[i][j][k] = dp[i-1][j][k-1] else: for jj in range(1, 6 + 1): for kk in range(1, rollMax[jj] + 1): if jj != j: dp[i][j][k] += dp[i-1][jj][kk] res = 0 for i in range(1, 7): for j in range(1, rollMax[i] + 1): res += dp[n][i][j] return res % M
train
APPS_structured
One Big Software Company has n employees numbered from 1 to n. The director is assigned number 1. Every employee of the company except the director has exactly one immediate superior. The director, of course, doesn't have a superior. We will call person a a subordinates of another person b, if either b is an immediate supervisor of a, or the immediate supervisor of a is a subordinate to person b. In particular, subordinates of the head are all other employees of the company. To solve achieve an Important Goal we need to form a workgroup. Every person has some efficiency, expressed by a positive integer a_{i}, where i is the person's number. The efficiency of the workgroup is defined as the total efficiency of all the people included in it. The employees of the big software company are obsessed with modern ways of work process organization. Today pair programming is at the peak of popularity, so the workgroup should be formed with the following condition. Each person entering the workgroup should be able to sort all of his subordinates who are also in the workgroup into pairs. In other words, for each of the members of the workgroup the number of his subordinates within the workgroup should be even. Your task is to determine the maximum possible efficiency of the workgroup formed at observing the given condition. Any person including the director of company can enter the workgroup. -----Input----- The first line contains integer n (1 ≤ n ≤ 2·10^5) — the number of workers of the Big Software Company. Then n lines follow, describing the company employees. The i-th line contains two integers p_{i}, a_{i} (1 ≤ a_{i} ≤ 10^5) — the number of the person who is the i-th employee's immediate superior and i-th employee's efficiency. For the director p_1 = - 1, for all other people the condition 1 ≤ p_{i} < i is fulfilled. -----Output----- Print a single integer — the maximum possible efficiency of the workgroup. -----Examples----- Input 7 -1 3 1 2 1 1 1 4 4 5 4 3 5 2 Output 17 -----Note----- In the sample test the most effective way is to make a workgroup from employees number 1, 2, 4, 5, 6.
n = int(input()) t = [list(map(int, input().split())) for q in range(n)] n += 1 u = [-1e7] * n v = [0] * n for i, (j, a) in list(enumerate(t, 1))[::-1]: u[i] = max(u[i], v[i] + a) v[j], u[j] = max(v[j] + v[i], u[j] + u[i]), max(v[j] + u[i], u[j] + v[i]) print(u[1])
n = int(input()) t = [list(map(int, input().split())) for q in range(n)] n += 1 u = [-1e7] * n v = [0] * n for i, (j, a) in list(enumerate(t, 1))[::-1]: u[i] = max(u[i], v[i] + a) v[j], u[j] = max(v[j] + v[i], u[j] + u[i]), max(v[j] + u[i], u[j] + v[i]) print(u[1])
train
APPS_structured
## The galactic games have begun! It's the galactic games! Beings of all worlds come together to compete in several interesting sports, like nroogring, fredling and buzzing (the beefolks love the last one). However, there's also the traditional marathon run. Unfortunately, there have been cheaters in the last years, and the committee decided to place sensors on the track. Committees being committees, they've come up with the following rule: > A sensor should be placed every 3 and 5 meters from the start, e.g. > at 3m, 5m, 6m, 9m, 10m, 12m, 15m, 18m…. Since you're responsible for the track, you need to buy those sensors. Even worse, you don't know how long the track will be! And since there might be more than a single track, and you can't be bothered to do all of this by hand, you decide to write a program instead. ## Task Return the sum of the multiples of 3 and 5 __below__ a number. Being the _galactic_ games, the tracks can get rather large, so your solution should work for _really_ large numbers (greater than 1,000,000). ### Examples ```python solution (10) # => 23 = 3 + 5 + 6 + 9 solution (20) # => 78 = 3 + 5 + 6 + 9 + 10 + 12 + 15 + 18 ```
def summ(number, d): n = (number - 1) // d return n * (n + 1) * d // 2 def solution(number): return summ(number, 3) + summ(number, 5) - summ(number, 15)
def summ(number, d): n = (number - 1) // d return n * (n + 1) * d // 2 def solution(number): return summ(number, 3) + summ(number, 5) - summ(number, 15)
train
APPS_structured
![](http://www.grindtv.com/wp-content/uploads/2015/08/drone.jpg) The other day I saw an amazing video where a guy hacked some wifi controlled lightbulbs by flying a drone past them. Brilliant. In this kata we will recreate that stunt... sort of. You will be given two strings: `lamps` and `drone`. `lamps` represents a row of lamps, currently off, each represented by `x`. When these lamps are on, they should be represented by `o`. The `drone` string represents the position of the drone `T` (any better suggestion for character??) and its flight path up until this point `=`. The drone always flies left to right, and always begins at the start of the row of lamps. Anywhere the drone has flown, including its current position, will result in the lamp at that position switching on. Return the resulting `lamps` string. See example tests for more clarity.
def fly_by(lamps, drone): on = drone.find("T") + 1 return lamps.replace("x", "o", on)
def fly_by(lamps, drone): on = drone.find("T") + 1 return lamps.replace("x", "o", on)
train
APPS_structured
Every Friday Chef and his N - 1 friends go for a party. At these parties, they play board games. This Friday, they are playing a game named "Boats! Boats! Boats!". In this game players have to transport cookies between Venice and Constantinople. Each player has a personal storage. The players are numbered from 1 to N, Chef is numbered 1. Rules for determining a winner are very difficult, therefore Chef asks you to write a program, which will determine who is a winner. There are 6 types of cookies. For each cookie in the storage player gets 1 point. Also player gets additional points if he packs his cookies in some boxes as follows: - A box containing 4 different types of cookies fetches 1 additional point. - A box containing 5 different types of cookies fetches 2 additional points. - A box containing 6 different types of cookies fetches 4 additional points. Obviously a cookie can be put into a single box. For each player, you know the number of cookies in his storage (denoted by c[i]), also the types of cookies in the storage given denoted by type[i][j]. Your task is to determine the winner of this game. Output "tie" if there are two or more players with same maximum score, "chef" if only Chef has a maximum score, winner's index in all other cases. -----Input----- The first line of input contains a single integer T denoting the number of test cases. This will be followed by T test cases. The first line of each test case contains an integer N denoting the number of players. The second line of each test case contains an integer c[i] denoting the number of cookies in the i-th storage, followed by c[i] space-separated integers type[i][j] which denote the type if j-th cookie in the storage i-th. -----Output----- For each test case, output a single line containing the answer as specified in the statement. -----Constraints and Subtasks-----Subtask #1 : (20 points) - 1 ≤ T ≤ 10 - 1 ≤ N ≤ 100 - 1 ≤ c[i] ≤ 100 - 1 ≤ type[i][j] ≤ 3 Subtask #2 : (80 points) - 1 ≤ T ≤ 10 - 1 ≤ N ≤ 100 - 1 ≤ c[i] ≤ 100 - 1 ≤ type[i][j] ≤ 6 -----Example----- Input: 3 2 6 1 2 3 4 5 6 9 3 3 3 4 4 4 5 5 5 2 5 2 3 4 5 6 7 1 1 2 2 3 3 4 3 4 1 1 2 3 4 1 2 2 3 4 1 2 3 3 Output: chef 2 tie -----Explanation----- Example case 1. Chef has total 6 cookie, so he gets 6 points for that. Also, he can put all his cookies (as they are all distinct) in a bag of size 6. It will fetch him additional 4 points. So, Chef's total points will be 10. The second player has 9 cookies, he gets 9 points for that. Other than this, he can't create a bag with either 4, 5 or 6 distinct cookies. So, his final score is 9. 10 > 9 - Chef wins. Example case 2. Chef has 5 + 2 (a bag with 5 different cookies) = 7. The second player has 7 + 1(a bag with 4 different cookies) = 8. 7 < 8 - the second player wins. Example case 3. Every player has 4 cookies and can't create any bag of sweets. So, it's a tie.
t = int(input()) for _ in range(t): n = int(input()) c = [] for _ in range(0,n): c.append(list(map(int,input().split()))) m = [] def newset(c): for i in set(c[1:]): c.remove(i) return c def check(c): s = len(set(c[1:])) if s < len(c[1:]): check(newset(c)) if s == 4: c[0] += 1 elif s == 5: c[0] += 2 elif s == 6: c[0] += 4 return c[0] for i in c: m.append(check(i)) if m.count(max(m))>1: print('tie') elif max(m) == m[0]: print('chef') else: print(m.index(max(m))+1)
t = int(input()) for _ in range(t): n = int(input()) c = [] for _ in range(0,n): c.append(list(map(int,input().split()))) m = [] def newset(c): for i in set(c[1:]): c.remove(i) return c def check(c): s = len(set(c[1:])) if s < len(c[1:]): check(newset(c)) if s == 4: c[0] += 1 elif s == 5: c[0] += 2 elif s == 6: c[0] += 4 return c[0] for i in c: m.append(check(i)) if m.count(max(m))>1: print('tie') elif max(m) == m[0]: print('chef') else: print(m.index(max(m))+1)
train
APPS_structured
In a network of nodes, each node i is directly connected to another node j if and only if graph[i][j] = 1. Some nodes initial are initially infected by malware.  Whenever two nodes are directly connected and at least one of those two nodes is infected by malware, both nodes will be infected by malware.  This spread of malware will continue until no more nodes can be infected in this manner. Suppose M(initial) is the final number of nodes infected with malware in the entire network, after the spread of malware stops. We will remove one node from the initial list.  Return the node that if removed, would minimize M(initial).  If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index. Note that if a node was removed from the initial list of infected nodes, it may still be infected later as a result of the malware spread. Example 1: Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1] Output: 0 Example 2: Input: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2] Output: 0 Example 3: Input: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2] Output: 1 Note: 1 < graph.length = graph[0].length <= 300 0 <= graph[i][j] == graph[j][i] <= 1 graph[i][i] == 1 1 <= initial.length <= graph.length 0 <= initial[i] < graph.length
from collections import deque class Solution: def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int: if graph is None or len(graph) ==0 or len(graph[0]) ==0 or len(initial) ==0: return None n = len(graph) m = len(graph[0]) k = len(initial) initial.sort() result = sys.maxsize idx = None for i in range(k): temp_q = initial[:] temp_q.pop(i) temp_q = deque(temp_q) temp_visited = set(temp_q) self.helper(graph, temp_q, temp_visited) if result > len(temp_visited): result = len(temp_visited) idx = initial[i] return idx def helper(self, graph, temp_q, temp_visited): n, m = len(graph), len(graph[0]) while temp_q: curr = temp_q.popleft() for col in range(m): if col in temp_visited or graph[curr][col] ==0: continue temp_visited.add(col) temp_q.append(col)
from collections import deque class Solution: def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int: if graph is None or len(graph) ==0 or len(graph[0]) ==0 or len(initial) ==0: return None n = len(graph) m = len(graph[0]) k = len(initial) initial.sort() result = sys.maxsize idx = None for i in range(k): temp_q = initial[:] temp_q.pop(i) temp_q = deque(temp_q) temp_visited = set(temp_q) self.helper(graph, temp_q, temp_visited) if result > len(temp_visited): result = len(temp_visited) idx = initial[i] return idx def helper(self, graph, temp_q, temp_visited): n, m = len(graph), len(graph[0]) while temp_q: curr = temp_q.popleft() for col in range(m): if col in temp_visited or graph[curr][col] ==0: continue temp_visited.add(col) temp_q.append(col)
train
APPS_structured
Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful. Therefore, Sasha decided to upsolve the following problem: You have an array $a$ with $n$ integers. You need to count the number of funny pairs $(l, r)$ $(l \leq r)$. To check if a pair $(l, r)$ is a funny pair, take $mid = \frac{l + r - 1}{2}$, then if $r - l + 1$ is an even number and $a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$, then the pair is funny. In other words, $\oplus$ of elements of the left half of the subarray from $l$ to $r$ should be equal to $\oplus$ of elements of the right half. Note that $\oplus$ denotes the bitwise XOR operation. It is time to continue solving the contest, so Sasha asked you to solve this task. -----Input----- The first line contains one integer $n$ ($2 \le n \le 3 \cdot 10^5$) — the size of the array. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i < 2^{20}$) — array itself. -----Output----- Print one integer — the number of funny pairs. You should consider only pairs where $r - l + 1$ is even number. -----Examples----- Input 5 1 2 3 4 5 Output 1 Input 6 3 2 2 3 7 6 Output 3 Input 3 42 4 2 Output 0 -----Note----- Be as cool as Sasha, upsolve problems! In the first example, the only funny pair is $(2, 5)$, as $2 \oplus 3 = 4 \oplus 5 = 1$. In the second example, funny pairs are $(2, 3)$, $(1, 4)$, and $(3, 6)$. In the third example, there are no funny pairs.
def count(arr): even = 0 odd = 0 for i in arr: if i % 2 == 1: even += 1 else: odd += 1 return (even-1) * even //2 + (odd - 1) * odd //2 def solve(a): sums = [] x = 0 for i in a: x = x ^ i sums.append(x) # print(sums) d = {} d[0] = [-1] for i in range(len(sums)): if sums[i] in d: d[sums[i]].append(i) else: d[sums[i]] = [i] # print(d) res = 0 for sums in d: res += count(d[sums]) return res n = int(input()) x = input().split() a = [] for i in x: a.append(int(i)) print(solve(a))
def count(arr): even = 0 odd = 0 for i in arr: if i % 2 == 1: even += 1 else: odd += 1 return (even-1) * even //2 + (odd - 1) * odd //2 def solve(a): sums = [] x = 0 for i in a: x = x ^ i sums.append(x) # print(sums) d = {} d[0] = [-1] for i in range(len(sums)): if sums[i] in d: d[sums[i]].append(i) else: d[sums[i]] = [i] # print(d) res = 0 for sums in d: res += count(d[sums]) return res n = int(input()) x = input().split() a = [] for i in x: a.append(int(i)) print(solve(a))
train
APPS_structured
What's in a name? ..Or rather, what's a name in? For us, a particular string is where we are looking for a name. Task Test whether or not the string contains all of the letters which spell a given name, in order. The format A function passing two strings, searching for one (the name) within the other. ``function nameInStr(str, name){ return true || false }`` Examples nameInStr("Across the rivers", "chris") --> true ^ ^ ^^ ^ c h ri s Contains all of the letters in "chris", in order. ---------------------------------------------------------- nameInStr("Next to a lake", "chris") --> false Contains none of the letters in "chris". -------------------------------------------------------------------- nameInStr("Under a sea", "chris") --> false ^ ^ r s Contains only some of the letters in "chris". -------------------------------------------------------------------- nameInStr("A crew that boards the ship", "chris") --> false cr h s i cr h s i c h r s i ... Contains all of the letters in "chris", but not in order. -------------------------------------------------------------------- nameInStr("A live son", "Allison") --> false ^ ^^ ^^^ A li son Contains all of the correct letters in "Allison", in order, but not enough of all of them (missing an 'l'). Note: testing will _not_ be case-sensitive.
def name_in_str(text, name): for c in text.lower(): if c == name[0].lower(): name = name[1:] if not name: return True return False
def name_in_str(text, name): for c in text.lower(): if c == name[0].lower(): name = name[1:] if not name: return True return False
train
APPS_structured
Ivan has an array consisting of n different integers. He decided to reorder all elements in increasing order. Ivan loves merge sort so he decided to represent his array with one or several increasing sequences which he then plans to merge into one sorted array. Ivan represent his array with increasing sequences with help of the following algorithm. While there is at least one unused number in array Ivan repeats the following procedure: iterate through array from the left to the right; Ivan only looks at unused numbers on current iteration; if current number is the first unused number on this iteration or this number is greater than previous unused number on current iteration, then Ivan marks the number as used and writes it down. For example, if Ivan's array looks like [1, 3, 2, 5, 4] then he will perform two iterations. On first iteration Ivan will use and write numbers [1, 3, 5], and on second one — [2, 4]. Write a program which helps Ivan and finds representation of the given array with one or several increasing sequences in accordance with algorithm described above. -----Input----- The first line contains a single integer n (1 ≤ n ≤ 2·10^5) — the number of elements in Ivan's array. The second line contains a sequence consisting of distinct integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — Ivan's array. -----Output----- Print representation of the given array in the form of one or more increasing sequences in accordance with the algorithm described above. Each sequence must be printed on a new line. -----Examples----- Input 5 1 3 2 5 4 Output 1 3 5 2 4 Input 4 4 3 2 1 Output 4 3 2 1 Input 4 10 30 50 101 Output 10 30 50 101
n = int(input()) from bisect import bisect_left a = list(map(int, input().split())) ss = [] ms = [] for i in range(n): k = a[i] ind = bisect_left(ms, -k) if ind == len(ms): ss.append([]) ms.append(0) ss[ind].append(k) ms[ind] = -k for s in ss: print(' '.join([str(i) for i in s]))
n = int(input()) from bisect import bisect_left a = list(map(int, input().split())) ss = [] ms = [] for i in range(n): k = a[i] ind = bisect_left(ms, -k) if ind == len(ms): ss.append([]) ms.append(0) ss[ind].append(k) ms[ind] = -k for s in ss: print(' '.join([str(i) for i in s]))
train
APPS_structured
# Task John is an orchard worker. There are `n` piles of fruits waiting to be transported. Each pile of fruit has a corresponding weight. John's job is to combine the fruits into a pile and wait for the truck to take them away. Every time, John can combine any two piles(`may be adjacent piles, or not`), and the energy he costs is equal to the weight of the two piles of fruit. For example, if there are two piles, pile1's weight is `1` and pile2's weight is `2`. After merging, the new pile's weight is `3`, and he consumed 3 units of energy. John wants to combine all the fruits into 1 pile with the least energy. Your task is to help John, calculate the minimum energy he costs. # Input - `fruits`: An array of positive integers. Each element represents the weight of a pile of fruit. Javascript: - 1 <= fruits.length <= 10000 - 1 <= fruits[i] <= 10000 Python: - 1 <= len(fruits) <= 5000 - 1 <= fruits[i] <= 10000 # Output An integer. the minimum energy John costs. # Examples For `fruits = [1,2,9]`, the output should be `15`. ``` 3 piles: 1 2 9 combine 1 and 2 to 3, cost 3 units of energy. 2 piles: 3 9 combine 3 and 9 to 12, cost 12 units of energy. 1 pile: 12 The total units of energy is 3 + 12 = 15 units ``` For `fruits = [100]`, the output should be `0`. There's only 1 pile. So no need combine it.
import bisect from collections import deque def comb(fruits): energy = 0 fruits = deque(sorted(fruits)) while len(fruits) > 1: e = fruits.popleft() + fruits.popleft() energy += e bisect.insort_left(fruits, e) return energy
import bisect from collections import deque def comb(fruits): energy = 0 fruits = deque(sorted(fruits)) while len(fruits) > 1: e = fruits.popleft() + fruits.popleft() energy += e bisect.insort_left(fruits, e) return energy
train
APPS_structured
# Task: Given a list of numbers, determine whether the sum of its elements is odd or even. Give your answer as a string matching `"odd"` or `"even"`. If the input array is empty consider it as: `[0]` (array with a zero). ## Example: ``` odd_or_even([0]) == "even" odd_or_even([0, 1, 4]) == "odd" odd_or_even([0, -1, -5]) == "even" ``` Have fun!
def odd_or_even(arr): if arr: return 'odd' if sum(arr) % 2 else 'even' else: return 'even'
def odd_or_even(arr): if arr: return 'odd' if sum(arr) % 2 else 'even' else: return 'even'
train
APPS_structured
In this kata we want to convert a string into an integer. The strings simply represent the numbers in words. Examples: * "one" => 1 * "twenty" => 20 * "two hundred forty-six" => 246 * "seven hundred eighty-three thousand nine hundred and nineteen" => 783919 Additional Notes: * The minimum number is "zero" (inclusively) * The maximum number, which must be supported is 1 million (inclusively) * The "and" in e.g. "one hundred and twenty-four" is optional, in some cases it's present and in others it's not * All tested numbers are valid, you don't need to validate them
from functools import reduce def parse_int(string): unit_ts={'zero':0,'one':1,'two':2,'three':3,'four':4,'five':5,'six':6,'seven':7,'eight':8,'nine':9,'ten':10,'eleven':11,'twelve':12,'thirteen':13,'fourteen':14,'fifteen':15,'sixteen':16,'seventeen':17,'eighteen':18,'nineteen':19,'twenty':20,'thirty':30,'forty':40,'fifty':50,'sixty':60,'seventy':70,'eighty':80,'ninety':90,'hundred':100,'thousand':1000,'million':1000000,'billion':1000000000} text=string.split(' ') lst=[] for element in text: if '-' in element:lst.append(unit_ts[element.split('-')[0]]+unit_ts[element.split('-')[1]]) elif element in unit_ts:lst.append(unit_ts[element]) myid=lst.index(max(lst)) result=0 result+=reduce(lambda x,y:x*y if y%100==0 else x+y,lst[:myid+1])if lst[:myid+1]!=[] else 0 result+=reduce(lambda x,y:x*y if y%100==0 else x+y,lst[myid+1:])if lst[myid+1:]!=[] else 0 return result
from functools import reduce def parse_int(string): unit_ts={'zero':0,'one':1,'two':2,'three':3,'four':4,'five':5,'six':6,'seven':7,'eight':8,'nine':9,'ten':10,'eleven':11,'twelve':12,'thirteen':13,'fourteen':14,'fifteen':15,'sixteen':16,'seventeen':17,'eighteen':18,'nineteen':19,'twenty':20,'thirty':30,'forty':40,'fifty':50,'sixty':60,'seventy':70,'eighty':80,'ninety':90,'hundred':100,'thousand':1000,'million':1000000,'billion':1000000000} text=string.split(' ') lst=[] for element in text: if '-' in element:lst.append(unit_ts[element.split('-')[0]]+unit_ts[element.split('-')[1]]) elif element in unit_ts:lst.append(unit_ts[element]) myid=lst.index(max(lst)) result=0 result+=reduce(lambda x,y:x*y if y%100==0 else x+y,lst[:myid+1])if lst[:myid+1]!=[] else 0 result+=reduce(lambda x,y:x*y if y%100==0 else x+y,lst[myid+1:])if lst[myid+1:]!=[] else 0 return result
train
APPS_structured
A rectangle can be split up into a grid of 1x1 squares, the amount of which being equal to the product of the two dimensions of the rectangle. Depending on the size of the rectangle, that grid of 1x1 squares can also be split up into larger squares, for example a 3x2 rectangle has a total of 8 squares, as there are 6 distinct 1x1 squares, and two possible 2x2 squares. A 4x3 rectangle contains 20 squares. Your task is to write a function `findSquares` that returns the total number of squares for any given rectangle, the dimensions of which being given as two integers with the first always being equal to or greater than the second.
findSquares=lambda m,n:sum((m-i)*(n-i) for i in range(min(m,n)))
findSquares=lambda m,n:sum((m-i)*(n-i) for i in range(min(m,n)))
train
APPS_structured
Little Praneet loves experimenting with algorithms and has devised a new algorithm. The algorithm is performed on an integer as follows: - if the rearmost digit is $0$, he will erase it. - else, he will replace the rearmost digit $d$ with $d-1$. If a point comes when the integer becomes $0$, the algorithm stops. You are given an integer $n$. Praneet will perform the algorithm on it $a$ times. You have to print the result after $a$ operations. -----Input:----- - The first and only line of input contains two integers $n$ — initial number, and $a$ —the number of operations. -----Output:----- - Print one integer — the result of performing the algorithm on $n$ $a$ times. -----Constraints----- - $2 \leq n \leq 10^9$ - $1 \leq a \leq 50$ -----Sample Input 1----- 1001 2 -----Sample Input 2----- 5 2 -----Sample Output 1----- 100 -----Sample Output 2----- 3 -----Explanation----- - In the first example, the transformation is as follows: $1001->1000->100$. - In the second example, the transformation is as follows: $5->4->3$.
# cook your dish here n,a=map(int,input().split()) for i in range(a): if n!= 0: r=n%10 n=n//10 if r!=0: r-=1 n=n*10+r print(int(n))
# cook your dish here n,a=map(int,input().split()) for i in range(a): if n!= 0: r=n%10 n=n//10 if r!=0: r-=1 n=n*10+r print(int(n))
train
APPS_structured
Write a function that accepts two square (`NxN`) matrices (two dimensional arrays), and returns the product of the two. Only square matrices will be given. How to multiply two square matrices: We are given two matrices, A and B, of size 2x2 (note: tests are not limited to 2x2). Matrix C, the solution, will be equal to the product of A and B. To fill in cell `[0][0]` of matrix C, you need to compute: `A[0][0] * B[0][0] + A[0][1] * B[1][0]`. More general: To fill in cell `[n][m]` of matrix C, you need to first multiply the elements in the nth row of matrix A by the elements in the mth column of matrix B, then take the sum of all those products. This will give you the value for cell `[m][n]` in matrix C. ## Example ``` A B C |1 2| x |3 2| = | 5 4| |3 2| |1 1| |11 8| ``` Detailed calculation: ``` C[0][0] = A[0][0] * B[0][0] + A[0][1] * B[1][0] = 1*3 + 2*1 = 5 C[0][1] = A[0][0] * B[0][1] + A[0][1] * B[1][1] = 1*2 + 2*1 = 4 C[1][0] = A[1][0] * B[0][0] + A[1][1] * B[1][0] = 3*3 + 2*1 = 11 C[1][1] = A[1][0] * B[0][1] + A[1][1] * B[1][1] = 3*2 + 2*1 = 8 ``` Link to Wikipedia explaining matrix multiplication (look at the square matrix example): http://en.wikipedia.org/wiki/Matrix_multiplication A more visual explanation of matrix multiplication: http://matrixmultiplication.xyz ~~~if:c **Note:** In **C**, the dimensions of both square matrices `n` will be passed into your function. However, since the dimensions of your returned "matrix" is expected to be the same as that of the inputs, you will not need to keep track of the dimensions of your matrix in another variable. ~~~
def matrix_mult(A, B): # Multiply two lists index by index item_multiply = lambda x, y: sum(x[i]*y[i] for i in range(len(x))) # Reverse the matrix to allow index by index multiplication B = [[j[i] for j in B] for i in range(len(B[0]))] result = [] # Go line by line on matrix a cycles = list(range(len(A))) for k in cycles: items = [] # Add all lists multiplications to a list for l in cycles: items.append(item_multiply(A[k], B[l])) # Then add these multiplications list to the result result.append(items) return result
def matrix_mult(A, B): # Multiply two lists index by index item_multiply = lambda x, y: sum(x[i]*y[i] for i in range(len(x))) # Reverse the matrix to allow index by index multiplication B = [[j[i] for j in B] for i in range(len(B[0]))] result = [] # Go line by line on matrix a cycles = list(range(len(A))) for k in cycles: items = [] # Add all lists multiplications to a list for l in cycles: items.append(item_multiply(A[k], B[l])) # Then add these multiplications list to the result result.append(items) return result
train
APPS_structured
Basic regex tasks. Write a function that takes in a numeric code of any length. The function should check if the code begins with 1, 2, or 3 and return `true` if so. Return `false` otherwise. You can assume the input will always be a number.
validate_code=lambda n:str(n).startswith(tuple('123'))
validate_code=lambda n:str(n).startswith(tuple('123'))
train
APPS_structured
A string with length $L$ is called rich if $L \ge 3$ and there is a character which occurs in this string strictly more than $L/2$ times. You are given a string $S$ and you should answer $Q$ queries on this string. In each query, you are given a substring $S_L, S_{L+1}, \ldots, S_R$. Consider all substrings of this substring. You have to determine whether at least one of them is rich. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains two space-separated integers $N$ and $Q$. - The second line contains a single string $S$ with length $N$. - Each of the next $Q$ lines contains two space-separated integers $L$ and $R$ describing a query. -----Output----- For each query, print a single line containing the string "YES" if the given substring contains a rich substring or "NO" if it does not contain any rich substring. -----Constraints----- - $1 \le T \le 10$ - $1 \le N, Q \le 10^5$ - $1 \le L \le R \le N$ - $S$ contains only lowercase English letters -----Example Input----- 1 10 2 helloworld 1 3 1 10 -----Example Output----- NO YES
def compute_rich_substr(s): rich = [0 for _ in range(len(s)+1)] for i in range(len(s) - 2): if (s[i] == s[i+1]) or (s[i] == s[i+2]) or (s[i+1] == s[i+2]): rich[i+1] = rich[i] + 1 else: rich[i+1] = rich[i] rich[len(s) - 1] = rich[len(s)] = rich[len(s) - 2] return rich t = int(input()) for _ in range(t): n, q = list(map(int, input().strip().split())) s = input() rich = compute_rich_substr(s) for _ in range(q): l, r = list(map(int, input().strip().split())) if r - l + 1 < 3: print("NO") elif rich[r - 2] - rich[l - 1] > 0: print("YES") else: print("NO")
def compute_rich_substr(s): rich = [0 for _ in range(len(s)+1)] for i in range(len(s) - 2): if (s[i] == s[i+1]) or (s[i] == s[i+2]) or (s[i+1] == s[i+2]): rich[i+1] = rich[i] + 1 else: rich[i+1] = rich[i] rich[len(s) - 1] = rich[len(s)] = rich[len(s) - 2] return rich t = int(input()) for _ in range(t): n, q = list(map(int, input().strip().split())) s = input() rich = compute_rich_substr(s) for _ in range(q): l, r = list(map(int, input().strip().split())) if r - l + 1 < 3: print("NO") elif rich[r - 2] - rich[l - 1] > 0: print("YES") else: print("NO")
train
APPS_structured
There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows: In each step, you will choose any 3 piles of coins (not necessarily consecutive). Of your choice, Alice will pick the pile with the maximum number of coins. You will pick the next pile with maximum number of coins. Your friend Bob will pick the last pile. Repeat until there are no more piles of coins. Given an array of integers piles where piles[i] is the number of coins in the ith pile. Return the maximum number of coins which you can have. Example 1: Input: piles = [2,4,1,2,7,8] Output: 9 Explanation: Choose the triplet (2, 7, 8), Alice Pick the pile with 8 coins, you the pile with 7 coins and Bob the last one. Choose the triplet (1, 2, 4), Alice Pick the pile with 4 coins, you the pile with 2 coins and Bob the last one. The maximum number of coins which you can have are: 7 + 2 = 9. On the other hand if we choose this arrangement (1, 2, 8), (2, 4, 7) you only get 2 + 4 = 6 coins which is not optimal. Example 2: Input: piles = [2,4,5] Output: 4 Example 3: Input: piles = [9,8,7,6,5,1,2,3,4] Output: 18 Constraints: 3 <= piles.length <= 10^5 piles.length % 3 == 0 1 <= piles[i] <= 10^4
class Solution: def maxCoins(self, piles: List[int]) -> int: n = len(piles) piles.sort(reverse=True) ans = 0 i = 1 while i < n: ans += piles[i] i += 2 n -= 1 return ans
class Solution: def maxCoins(self, piles: List[int]) -> int: n = len(piles) piles.sort(reverse=True) ans = 0 i = 1 while i < n: ans += piles[i] i += 2 n -= 1 return ans
train
APPS_structured
Given a list of white pawns on a chessboard (any number of them, meaning from 0 to 64 and with the possibility to be positioned everywhere), determine how many of them have their backs covered by another. Pawns attacking upwards since we have only white ones. Please remember that a pawn attack(and defend as well) only the 2 square on the sides in front of him. https://en.wikipedia.org/wiki/Pawn_(chess)#/media/File:Pawn_(chess)_movements.gif This is how the chess board coordinates are defined: ABCDEFGH8♜♞♝♛♚♝♞♜7♟♟♟♟♟♟♟♟65432♙♙♙♙♙♙♙♙1♖♘♗♕♔♗♘♖
def covered_pawns(pawns): count = 0 for i in range(len(pawns)): x, y = list(pawns[i]) if "".join([chr(ord(x) - 1), str(int(y) - 1)]) in pawns or \ "".join([chr(ord(x) + 1), str(int(y) - 1)]) in pawns: count += 1 return count
def covered_pawns(pawns): count = 0 for i in range(len(pawns)): x, y = list(pawns[i]) if "".join([chr(ord(x) - 1), str(int(y) - 1)]) in pawns or \ "".join([chr(ord(x) + 1), str(int(y) - 1)]) in pawns: count += 1 return count
train
APPS_structured
Iahub got bored, so he invented a game to be played on paper.  He writes n integers a1, a2, ..., an. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≤ i ≤ j ≤ n) and flips all values ak for which their positions are in range [i, j] (that is i ≤ k ≤ j). Flip the value of x means to apply operation x = 1 - x.  The goal of the game is that after exactly one move to obtain the maximum number of ones. Write a program to solve the little game of Iahub. ``` @param {Array} line of the input there are n integers: a1, a2, ..., an. 1 ≤ n ≤ 100. It is guaranteed that each of those n values is either 0 or 1 @return {Integer} the maximal number of 1s that can be obtained after exactly one move ``` Examples : ``` [1, 0, 0, 1, 0, 0] => 5 [1, 0, 0, 1] => 4 ``` Note:  In the first case, flip the segment from 2 to 6 (i = 2, j = 6). That flip changes the sequence, it becomes: [1 1 1 0 1 1]. So, it contains four ones. There is no way to make the whole sequence equal to [1 1 1 1 1 1].  In the second case, flipping only the second and the third element (i = 2, j = 3) will turn all numbers into 1. (c)ll931110 & fchirica
flipping_game=lambda a:sum(a)+max(j-i-2*sum(a[i:j])for j in range(1,len(a)+1)for i in range(j))
flipping_game=lambda a:sum(a)+max(j-i-2*sum(a[i:j])for j in range(1,len(a)+1)for i in range(j))
train
APPS_structured
In this Kata, you will be given a multi-dimensional array containing `2 or more` sub-arrays of integers. Your task is to find the maximum product that can be formed by taking any one element from each sub-array. ``` Examples: solve( [[1, 2],[3, 4]] ) = 8. The max product is given by 2 * 4 solve( [[10,-15],[-1,-3]] ) = 45, given by (-15) * (-3) solve( [[1,-1],[2,3],[10,-100]] ) = 300, given by (-1) * 3 * (-100) ``` More examples in test cases. Good luck!
from itertools import product from functools import reduce def solve(arr): return max( reduce(int.__mul__, p,1) for p in product(*arr) )
from itertools import product from functools import reduce def solve(arr): return max( reduce(int.__mul__, p,1) for p in product(*arr) )
train
APPS_structured
Given an integer $x$, find two non-negative integers $a$ and $b$ such that $(a \wedge b) + (a \vee b) = x$, where $\wedge$ is the bitwise AND operation and $\vee$ is the bitwise OR operation. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first and only line of each test case contains a single integer $x$. -----Output----- If there is no valid pair $(a, b)$, print a single line containing the integer $-1$. Otherwise, print a single line containing two space-separated integers $a$ and $b$. If there are multiple solutions, you may print any one of them. -----Constraints----- - $1 \le T \le 10^5$ - $1 \le x \le 10^{18}$ -----Subtasks----- Subtask #1 (30 points): - $1 \le T \le 200$ - $1 \le x \le 200$ Subtask #2 (70 points): original constraints -----Example Input----- 2 1 8 -----Example Output----- 0 1 5 3
# cook your dish here n=int(input()) for _ in range(n): a=int(input()) if(a%2==0): f=(a//2)-1 s=a-f else: f=(a//2) s=a-f print(f,s)
# cook your dish here n=int(input()) for _ in range(n): a=int(input()) if(a%2==0): f=(a//2)-1 s=a-f else: f=(a//2) s=a-f print(f,s)
train
APPS_structured
Sonya was unable to think of a story for this problem, so here comes the formal description. You are given the array containing n positive integers. At one turn you can pick any element and increase or decrease it by 1. The goal is the make the array strictly increasing by making the minimum possible number of operations. You are allowed to change elements in any way, they can become negative or equal to 0. -----Input----- The first line of the input contains a single integer n (1 ≤ n ≤ 3000) — the length of the array. Next line contains n integer a_{i} (1 ≤ a_{i} ≤ 10^9). -----Output----- Print the minimum number of operation required to make the array strictly increasing. -----Examples----- Input 7 2 1 5 11 5 9 11 Output 9 Input 5 5 4 3 2 1 Output 12 -----Note----- In the first sample, the array is going to look as follows: 2 3 5 6 7 9 11 |2 - 2| + |1 - 3| + |5 - 5| + |11 - 6| + |5 - 7| + |9 - 9| + |11 - 11| = 9 And for the second sample: 1 2 3 4 5 |5 - 1| + |4 - 2| + |3 - 3| + |2 - 4| + |1 - 5| = 12
from bisect import bisect_left as BL n = int(input()) graph = [(-99**9, 0)] # x, slope ans = 0 for i,a in enumerate(map(int,input().split())): a-= i new = [] turnj = BL(graph, (a,99**9)) - 1 if turnj != len(graph)-1: ans+= graph[-1][0] - a # add |x-a| for j in range(turnj): x, sl = graph[j] new.append((x, sl-1)) for j in range(turnj, len(graph)): x, sl = graph[j] if j == turnj: new.append((x, sl-1)) new.append((a, sl+1)) else: new.append((x, sl+1)) # remove positive slopes graph = new while graph[-1][1] > 0: x, sl = graph.pop() if graph[-1][1] != 0: graph.append((x, 0)) print(ans)
from bisect import bisect_left as BL n = int(input()) graph = [(-99**9, 0)] # x, slope ans = 0 for i,a in enumerate(map(int,input().split())): a-= i new = [] turnj = BL(graph, (a,99**9)) - 1 if turnj != len(graph)-1: ans+= graph[-1][0] - a # add |x-a| for j in range(turnj): x, sl = graph[j] new.append((x, sl-1)) for j in range(turnj, len(graph)): x, sl = graph[j] if j == turnj: new.append((x, sl-1)) new.append((a, sl+1)) else: new.append((x, sl+1)) # remove positive slopes graph = new while graph[-1][1] > 0: x, sl = graph.pop() if graph[-1][1] != 0: graph.append((x, 0)) print(ans)
train
APPS_structured
# Task You have two sorted arrays `a` and `b`, merge them to form new array of unique items. If an item is present in both arrays, it should be part of the resulting array if and only if it appears in both arrays the same number of times. # Example For `a = [1, 3, 40, 40, 50, 60, 60, 60]` and `b = [2, 40, 40, 50, 50, 65]`, the result should be `[1, 2, 3, 40, 60, 65]`. ``` Number 40 appears 2 times in both arrays, thus it is in the resulting array. Number 50 appears once in array a and twice in array b, therefore it is not part of the resulting array.``` # Input/Output - `[input]` integer array `a` A sorted array. 1 ≤ a.length ≤ 500000 - `[input]` integer array `b` A sorted array. `1 ≤ b.length ≤ 500000` - `[output]` an integer array The resulting sorted array.
def merge_arrays(a, b): return sorted(n for n in set(a+b) if (n in a) != (n in b) or a.count(n) == b.count(n))
def merge_arrays(a, b): return sorted(n for n in set(a+b) if (n in a) != (n in b) or a.count(n) == b.count(n))
train
APPS_structured
Cyael is a teacher at a very famous school in Byteland and she is known by her students for being very polite to them and also to encourage them to get good marks on their tests. Then, if they get good marks she will reward them with candies :) However, she knows they are all very good at Mathematics, so she decided to split the candies evenly to all the students she considers worth of receiving them, so they don't fight with each other. She has a bag which initially contains N candies and she intends to split the candies evenly to K students. To do this she will proceed as follows: while she has more than K candies she will give exactly 1 candy to each student until she has less than K candies. On this situation, as she can't split candies equally among all students she will keep the remaining candies to herself. Your job is to tell how many candies will each student and the teacher receive after the splitting is performed. -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. Each test case will consist of 2 space separated integers, N and K denoting the number of candies and the number of students as described above. -----Output----- For each test case, output a single line containing two space separated integers, the first one being the number of candies each student will get, followed by the number of candies the teacher will get. -----Constraints----- - T<=100 in each test file - 0 <= N,K <= 233 - 1 -----Example-----Input: 2 10 2 100 3 Output: 5 0 33 1 -----Explanation----- For the first test case, all students can get an equal number of candies and teacher receives no candies at all For the second test case, teacher can give 33 candies to each student and keep 1 candy to herselfUpdate: There may be multiple whitespaces before, after or between the numbers in input.
# cook your dish here t=int(input()) for i in range(t): candies,student=map(int,input().split()) if student==0: print(0,candies) else: each_student=candies//student teachers=candies%student print(each_student,teachers)
# cook your dish here t=int(input()) for i in range(t): candies,student=map(int,input().split()) if student==0: print(0,candies) else: each_student=candies//student teachers=candies%student print(each_student,teachers)
train
APPS_structured
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied. A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order. Example 1: Input: nums = [10,2,-10,5,20], k = 2 Output: 37 Explanation: The subsequence is [10, 2, 5, 20]. Example 2: Input: nums = [-1,-2,-3], k = 1 Output: -1 Explanation: The subsequence must be non-empty, so we choose the largest number. Example 3: Input: nums = [10,-2,-10,-5,20], k = 2 Output: 23 Explanation: The subsequence is [10, -2, -5, 20]. Constraints: 1 <= k <= nums.length <= 10^5 -10^4 <= nums[i] <= 10^4
from typing import List import numpy class Solution: def constrainedSubsetSum(self, nums: List[int], k: int) -> int: _len = len(nums) dp = numpy.zeros(_len, dtype=int) dp[0] = nums[0] _deque = [] result = -sys.maxsize for i in range(_len): while _deque and i - _deque[0] > k: _deque.pop(0) tmp = 0 if _deque: tmp = dp[_deque[0]] dp[i] = max(nums[i], nums[i] + tmp) result = max(result, dp[i]) while _deque and dp[i] >= dp[_deque[-1]]: _deque.pop() _deque.append(i) pass return result
from typing import List import numpy class Solution: def constrainedSubsetSum(self, nums: List[int], k: int) -> int: _len = len(nums) dp = numpy.zeros(_len, dtype=int) dp[0] = nums[0] _deque = [] result = -sys.maxsize for i in range(_len): while _deque and i - _deque[0] > k: _deque.pop(0) tmp = 0 if _deque: tmp = dp[_deque[0]] dp[i] = max(nums[i], nums[i] + tmp) result = max(result, dp[i]) while _deque and dp[i] >= dp[_deque[-1]]: _deque.pop() _deque.append(i) pass return result
train
APPS_structured
Write function describeList which returns "empty" if the list is empty or "singleton" if it contains only one element or "longer"" if more.
def describeList(list): if len(list)==1: return 'singleton' elif len(list)>1: return 'longer' else: return 'empty'
def describeList(list): if len(list)==1: return 'singleton' elif len(list)>1: return 'longer' else: return 'empty'
train
APPS_structured
Implement the class TweetCounts that supports two methods: 1. recordTweet(string tweetName, int time) Stores the tweetName at the recorded time (in seconds). 2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime) Returns the total number of occurrences for the given tweetName per minute, hour, or day (depending on freq) starting from the startTime (in seconds) and ending at the endTime (in seconds). freq is always minute, hour or day, representing the time interval to get the total number of occurrences for the given tweetName. The first time interval always starts from the startTime, so the time intervals are [startTime, startTime + delta*1>,  [startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)> for some non-negative number i and delta (which depends on freq).   Example: Input ["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"] [[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]] Output [null,null,null,null,[2],[2,1],null,[4]] Explanation TweetCounts tweetCounts = new TweetCounts(); tweetCounts.recordTweet("tweet3", 0); tweetCounts.recordTweet("tweet3", 60); tweetCounts.recordTweet("tweet3", 10); // All tweets correspond to "tweet3" with recorded times at 0, 10 and 60. tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]. The frequency is per minute (60 seconds), so there is one interval of time: 1) [0, 60> - > 2 tweets. tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2, 1]. The frequency is per minute (60 seconds), so there are two intervals of time: 1) [0, 60> - > 2 tweets, and 2) [60,61> - > 1 tweet. tweetCounts.recordTweet("tweet3", 120); // All tweets correspond to "tweet3" with recorded times at 0, 10, 60 and 120. tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]. The frequency is per hour (3600 seconds), so there is one interval of time: 1) [0, 211> - > 4 tweets. Constraints: There will be at most 10000 operations considering both recordTweet and getTweetCountsPerFrequency. 0 <= time, startTime, endTime <= 10^9 0 <= endTime - startTime <= 10^4
class TweetCounts: MAP = { 'minute': 60, 'hour': 60 * 60, 'day': 24 * 60 * 60 } def __init__(self): self.data = defaultdict(list) def recordTweet(self, tweetName: str, time: int) -> None: self.data[tweetName].append(time) self.data[tweetName].sort() def getTweetCountsPerFrequency(self, freq: str, tweetName: str, startTime: int, endTime: int) -> List[int]: data = self.data[tweetName] index = 0 while index < len(data) and data[index] < startTime: index += 1 ans = [] tmp = 0 k = 0 delta = self.MAP[freq] while startTime + k * delta <= endTime: end = min(startTime + delta * (k + 1), endTime + 1) if index >= len(data) or data[index] >= end: ans.append(tmp) tmp = 0 k += 1 else: tmp += 1 index += 1 return ans
class TweetCounts: MAP = { 'minute': 60, 'hour': 60 * 60, 'day': 24 * 60 * 60 } def __init__(self): self.data = defaultdict(list) def recordTweet(self, tweetName: str, time: int) -> None: self.data[tweetName].append(time) self.data[tweetName].sort() def getTweetCountsPerFrequency(self, freq: str, tweetName: str, startTime: int, endTime: int) -> List[int]: data = self.data[tweetName] index = 0 while index < len(data) and data[index] < startTime: index += 1 ans = [] tmp = 0 k = 0 delta = self.MAP[freq] while startTime + k * delta <= endTime: end = min(startTime + delta * (k + 1), endTime + 1) if index >= len(data) or data[index] >= end: ans.append(tmp) tmp = 0 k += 1 else: tmp += 1 index += 1 return ans
train
APPS_structured
The Chef once decided to prepare some nice dishes on his birthday. There are N items kept on his shelf linearly from position 1 to N. Taste of the i-th item is denoted by a integer Ai. He wants to make Q dishes. A dish will be made using some ingredients in the continuous range AL, AL + 1, , , AR (1-base indexing). Quality of the dish will be determined by the ingredient with minimum taste. Chef wants help of his assistant Rupsa to find out sum and product of qualities of the dishes. As product of the qualities of the dishes could be very large, print it modulo 109 + 7. Also, you are given an integer K and you are assured that for each dish, the size of continuous range of the ingredients (i.e. R - L + 1) will always lie between K and 2 * K, both inclusive. Method of generation of Array A You are given non-negative integer parameters a, b, c, d, e, f, r, s, t, m, A[1] for x = 2 to N: if(t^x mod s <= r) // Here t^x signifies "t to the power of x" A[x] = (a*A[x-1]^2 + b*A[x-1] + c) mod m else A[x] = (d*A[x-1]^2 + e*A[x-1] + f) mod m Method of generation of range of ingredients for Q dishes You are given non-negative integer parameters L1, La, Lc, Lm, D1, Da, Dc, Dm for i = 1 to Q: L1 = (La * L1 + Lc) mod Lm; D1 = (Da * D1 + Dc) mod Dm; L = L1 + 1; R = min(L + K - 1 + D1, N); -----Input----- - The first line contains three integers N, K and Q. - The second line contains the integers a, b, c, d, e, f, r, s, t, m, and A[1]. - Then third line contains the integers L1, La, Lc, Lm, D1, Da, Dc, and Dm -----Output----- Output two space separated integers: - The sum of qualities of the dishes. - The product of qualities of the dishes modulo 109+7. -----Constraints----- - 1 ≤ N, Q ≤ 107 - 1 ≤ K ≤ N - 0 ≤ a, b, c, d, e, f, r, s, t, m, A[1] ≤ 109+7 - 1 ≤ Lm ≤ N - K + 1 - 1 ≤ Dm ≤ K + 1 - 1 ≤ La, Lc ≤ Lm - 1 ≤ Da, Dc ≤ Dm - 1 ≤ L1 ≤ N - 1 ≤ D1 ≤ K -----Sub tasks----- - Subtask #1: 1 ≤ N, Q ≤ 1000 (10 points) - Subtask #2: 1 ≤ Q ≤ 104 (20 points) - Subtask #3: original constraints (70 points) -----Example----- Input: 4 2 1 1 1 1 1 1 1 1 1 1 100 1 1 1 1 3 1 1 1 2 Output: 13 13 -----Explanation----- - The array A comes out to be {1, 3, 13, 83} and the first dish has L = 3 and R = 4. The minimum in this range is 13, thus the sum and product both are 13 and hence the answer. -----Note----- Multiplier for C# and Java have been reduced to 1.5 instead of 2.
mod=10**9+7 N,K,Q=list(map(int,input().split())) A=[0,0] #min_t=[-1]*((N*N-1)/2) #print min_t a,b,c,d,e,f,r,s,t,m,A[1]=list(map(int,input().split())) L1,La,Lc,Lm,D1,Da,Dc,Dm=list(map(int,input().split())) tmpt=t min_arr=[0] for x in range(2,N+1): tmpt=(tmpt*t)%s if tmpt <= r: A.append(( A[x-1]*(a*A[x-1] + b) + c) % m) else: A.append(( A[x-1]*(d*A[x-1] + e) + f) % m) for x in range(1,N-K+2): min_arr.append(min(A[x:x+K])) res_sum=0 res_pro=1 for x in range(1,Q+1): L1 = (La * L1 + Lc) % Lm D1 = (Da * D1 + Dc) % Dm L = L1 + 1 R = min(L + K - 1 + D1, N) R=R-K+1 #print min_arr,L,R,min_arr[L:R+1] if L==R: tmp=min_arr[L] else: tmp=min(min_arr[L:R+1]) res_sum+=tmp res_pro=(res_pro*tmp)% mod print(res_sum,res_pro)
mod=10**9+7 N,K,Q=list(map(int,input().split())) A=[0,0] #min_t=[-1]*((N*N-1)/2) #print min_t a,b,c,d,e,f,r,s,t,m,A[1]=list(map(int,input().split())) L1,La,Lc,Lm,D1,Da,Dc,Dm=list(map(int,input().split())) tmpt=t min_arr=[0] for x in range(2,N+1): tmpt=(tmpt*t)%s if tmpt <= r: A.append(( A[x-1]*(a*A[x-1] + b) + c) % m) else: A.append(( A[x-1]*(d*A[x-1] + e) + f) % m) for x in range(1,N-K+2): min_arr.append(min(A[x:x+K])) res_sum=0 res_pro=1 for x in range(1,Q+1): L1 = (La * L1 + Lc) % Lm D1 = (Da * D1 + Dc) % Dm L = L1 + 1 R = min(L + K - 1 + D1, N) R=R-K+1 #print min_arr,L,R,min_arr[L:R+1] if L==R: tmp=min_arr[L] else: tmp=min(min_arr[L:R+1]) res_sum+=tmp res_pro=(res_pro*tmp)% mod print(res_sum,res_pro)
train
APPS_structured
### Task: Your job is to take a pair of parametric equations, passed in as strings, and convert them into a single rectangular equation by eliminating the parameter. Both parametric halves will represent linear equations of x as a function of time and y as a function of time respectively. The format of the final equation must be `Ax + By = C` or `Ax - By = C` where A and B must be positive and A, B, and C are integers. The final equation also needs to have the lowest possible whole coefficients. Omit coefficients equal to one. The method is called `para_to_rect` or `EquationsManager.paraToRect` and takes in two strings in the form `x = at +(or -) b` and `y = ct +(or -) d` respectively, where `a` and `c` must be integers, and `b` and `d` must be positive integers. If `a` or `c` is omitted, the coefficient of _t_ is obviously assumed to be 1 (see final case in the example tests). There will NEVER be double signs in the equations inputted (For example: `"x = -12t + -18"` and `"y = -12t - -18"` won't show up.) ### Examples: ```python para_to_rect("x = 12t + 18", "y = 8t + 7") => "2x - 3y = 15" ``` > __CALCULATION:__ x = 12t + 18 y = 8t + 7 2x = 24t + 36 3y = 24t + 21 2x - 3y = (24t + 36) - (24t + 21) 2x - 3y = 15 ```python para_to_rect("x = -12t - 18", "y = 8t + 7") => "2x + 3y = -15" ``` > __CALCULATION:__ x = -12t - 18 y = 8t + 7 2x = -24t - 36 3y = 24t + 21 2x + 3y = (-24t - 36) + (24t + 21) 2x + 3y = -15 ```python para_to_rect("x = -t + 12", "y = 12t - 1") => "12x + y = 143" ``` > __CALCULATION:__ x = -t + 12 y = 12t - 1 12x = -12t + 144 y = 12t - 1 12x + y = 143 More examples in the sample test cases. ### Notes: As you can see above, sometimes you'll need to add the two parametric equations after multiplying by the necessary values; sometimes you'll need to subtract them – just get rid of the _t_!
import re from math import gcd def para_to_rect(eqn1, eqn2): eqn1, eqn2 = [re.sub(r'\bt', '1t', e) for e in [eqn1, eqn2]] (a,b), (c,d) = ([[int(x.replace(' ', '')) for x in re.findall('-?\d+|[-+] \d+', e)] for e in [eqn1, eqn2]]) x = c*b - a*d g = gcd(gcd(c, a), x) if c < 0: g = -g c, a, x = c//g, a//g, x//g return re.sub(r'\b1([xy])', r'\1', f'{c}x {"+-"[a > 0]} {abs(a)}y = {x}')
import re from math import gcd def para_to_rect(eqn1, eqn2): eqn1, eqn2 = [re.sub(r'\bt', '1t', e) for e in [eqn1, eqn2]] (a,b), (c,d) = ([[int(x.replace(' ', '')) for x in re.findall('-?\d+|[-+] \d+', e)] for e in [eqn1, eqn2]]) x = c*b - a*d g = gcd(gcd(c, a), x) if c < 0: g = -g c, a, x = c//g, a//g, x//g return re.sub(r'\b1([xy])', r'\1', f'{c}x {"+-"[a > 0]} {abs(a)}y = {x}')
train
APPS_structured
It is a well-known fact that behind every good comet is a UFO. These UFOs often come to collect loyal supporters from here on Earth. Unfortunately, they only have room to pick up one group of followers on each trip. They do, however, let the groups know ahead of time which will be picked up for each comet by a clever scheme: they pick a name for the comet which, along with the name of the group, can be used to determine if it is a particular group's turn to go (who do you think names the comets?). The details of the matching scheme are given below; your job is to write a program which takes the names of a group and a comet and then determines whether the group should go with the UFO behind that comet. Both the name of the group and the name of the comet are converted into a number in the following manner: the final number is just the product of all the letters in the name, where "A" is 1 and "Z" is 26. For instance, the group "USACO" would be `21 * 19 * 1 * 3 * 15` = 17955. If the group's number mod 47 is the same as the comet's number mod 47, then you need to tell the group to get ready! (Remember that "a mod b" is the remainder left over after dividing a by b; 34 mod 10 is 4.) Write a program which reads in the name of the comet and the name of the group and figures out whether according to the above scheme the names are a match, printing "GO" if they match and "STAY" if not. The names of the groups and the comets will be a string of capital letters with no spaces or punctuation, up to 6 characters long. Example: Converting the letters to numbers: ``` C O M E T Q 3 15 13 5 20 17 H V N G A T 8 22 14 7 1 20 ``` then calculate the product mod 47: ``` 3 * 15 * 13 * 5 * 20 * 17 = 994500 mod 47 = 27 8 * 22 * 14 * 7 * 1 * 20 = 344960 mod 47 = 27 ``` Because both products evaluate to 27 (when modded by 47), the mission is 'GO'.
from functools import reduce def ride(group, comet): return "GO" if score(group) == score(comet) else "STAY" def score(word): return reduce(int.__mul__, (ord(c) - 64 for c in word)) % 47
from functools import reduce def ride(group, comet): return "GO" if score(group) == score(comet) else "STAY" def score(word): return reduce(int.__mul__, (ord(c) - 64 for c in word)) % 47
train
APPS_structured
# Task Sorting is one of the most basic computational devices used in Computer Science. Given a sequence (length ≤ 1000) of 3 different key values (7, 8, 9), your task is to find the minimum number of exchange operations necessary to make the sequence sorted. One operation is the switching of 2 key values in the sequence. # Example For `sequence = [7, 7, 8, 8, 9, 9]`, the result should be `0`. It's already a sorted sequence. For `sequence = [9, 7, 8, 8, 9, 7]`, the result should be `1`. We can switching `sequence[0]` and `sequence[5]`. For `sequence = [8, 8, 7, 9, 9, 9, 8, 9, 7]`, the result should be `4`. We can: ``` [8, 8, 7, 9, 9, 9, 8, 9, 7] switching sequence[0] and sequence[3] --> [9, 8, 7, 8, 9, 9, 8, 9, 7] switching sequence[0] and sequence[8] --> [7, 8, 7, 8, 9, 9, 8, 9, 9] switching sequence[1] and sequence[2] --> [7, 7, 8, 8, 9, 9, 8, 9, 9] switching sequence[5] and sequence[7] --> [7, 7, 8, 8, 8, 9, 9, 9, 9] ``` So `4` is the minimum number of operations for the sequence to become sorted. # Input/Output - `[input]` integer array `sequence` The Sequence. - `[output]` an integer the minimum number of operations.
def exchange_sort(sequence): print(sequence) # Reduce the sequence into its useful data counts = [sequence.count(n) for n in [7, 8, 9]] dividers = [0] + [sum(counts[:i]) for i in range(1,4)] groupings = [[sequence[dividers[i]:dividers[i+1]].count(n) for n in [7, 8, 9]] for i in range(3)] # Perform swaps en masse until done n = 0 def swap(t0, t1, n0, n1): swappable = min(groupings[t0][n1], groupings[t1][n0]) groupings[t0][n0] += swappable groupings[t0][n1] -= swappable groupings[t1][n1] += swappable groupings[t1][n0] -= swappable return swappable for a, b in [(0, 1), (0, 2), (1, 2)]: n += swap(a, b, a, b) for a, b, c in [(0, 1, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0), (1, 0, 2), (0, 2, 1)]: n += swap(a, b, a, c) for a, b in [(0, 1), (0, 2), (1, 2)]: n += swap(a, b, a, b) return n
def exchange_sort(sequence): print(sequence) # Reduce the sequence into its useful data counts = [sequence.count(n) for n in [7, 8, 9]] dividers = [0] + [sum(counts[:i]) for i in range(1,4)] groupings = [[sequence[dividers[i]:dividers[i+1]].count(n) for n in [7, 8, 9]] for i in range(3)] # Perform swaps en masse until done n = 0 def swap(t0, t1, n0, n1): swappable = min(groupings[t0][n1], groupings[t1][n0]) groupings[t0][n0] += swappable groupings[t0][n1] -= swappable groupings[t1][n1] += swappable groupings[t1][n0] -= swappable return swappable for a, b in [(0, 1), (0, 2), (1, 2)]: n += swap(a, b, a, b) for a, b, c in [(0, 1, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0), (1, 0, 2), (0, 2, 1)]: n += swap(a, b, a, c) for a, b in [(0, 1), (0, 2), (1, 2)]: n += swap(a, b, a, b) return n
train
APPS_structured
Implement a function, `multiples(m, n)`, which returns an array of the first `m` multiples of the real number `n`. Assume that `m` is a positive integer. Ex. ``` multiples(3, 5.0) ``` should return ``` [5.0, 10.0, 15.0] ```
def multiples(m, n): solution = [] for i in range(1, m+1): solution.insert(i, n * i) return solution
def multiples(m, n): solution = [] for i in range(1, m+1): solution.insert(i, n * i) return solution
train
APPS_structured
There is enough money available on ATM in nominal value 10, 20, 50, 100, 200 and 500 dollars. You are given money in nominal value of `n` with `1<=n<=1500`. Try to find minimal number of notes that must be used to repay in dollars, or output -1 if it is impossible. Good Luck!!!
def solve(n): t=0 for d in [500,200,100,50,20,10]: a,n=divmod(n,d) t+=a if n: return -1 return t
def solve(n): t=0 for d in [500,200,100,50,20,10]: a,n=divmod(n,d) t+=a if n: return -1 return t
train
APPS_structured
# Introduction and Warm-up (Highly recommended) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) ___ # Task **_Given_** an *array/list [] of integers* , **_Find_** **_The maximum difference_** *between the successive elements in its sorted form*. ___ # Notes * **_Array/list_** size is *at least 3* . * **_Array/list's numbers_** Will be **mixture of positives and negatives also zeros_** * **_Repetition_** of numbers in *the array/list could occur*. * **_The Maximum Gap_** is *computed Regardless the sign*. ___ # Input >> Output Examples ``` maxGap ({13,10,5,2,9}) ==> return (4) ``` ## **_Explanation_**: * **_The Maximum Gap_** *after sorting the array is* `4` , *The difference between* ``` 9 - 5 = 4 ``` . ___ ``` maxGap ({-3,-27,-4,-2}) ==> return (23) ``` ## **_Explanation_**: * **_The Maximum Gap_** *after sorting the array is* `23` , *The difference between* ` |-4- (-27) | = 23` . * **_Note_** : *Regardless the sign of negativity* . ___ ``` maxGap ({-7,-42,-809,-14,-12}) ==> return (767) ``` ## **_Explanation_**: * **_The Maximum Gap_** *after sorting the array is* `767` , *The difference between* ` | -809- (-42) | = 767` . * **_Note_** : *Regardless the sign of negativity* . ___ ``` maxGap ({-54,37,0,64,640,0,-15}) //return (576) ``` ## **_Explanation_**: * **_The Maximum Gap_** *after sorting the array is* `576` , *The difference between* ` | 64 - 640 | = 576` . * **_Note_** : *Regardless the sign of negativity* . ___ ___ ___ # [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) # [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored) ___ ## ALL translations are welcomed ## Enjoy Learning !! # Zizou
def max_gap(numbers): return max(abs(a-b) for a, b in zip(sorted(numbers),sorted(numbers)[1:]))
def max_gap(numbers): return max(abs(a-b) for a, b in zip(sorted(numbers),sorted(numbers)[1:]))
train
APPS_structured
In this kata, your task is to write a function `to_bytes(n)` (or `toBytes(n)` depending on language) that produces a list of bytes that represent a given non-negative integer `n`. Each byte in the list is represented by a string of `'0'` and `'1'` of length 8. The most significant byte is first in the list. The example test cases should provide you with all the details. You may assume that the argument `n` is valid.
to_bytes=b=lambda n,f=1:n and b(n>>8,0)+[format(n&255,'08b')]or['0'*8]*f
to_bytes=b=lambda n,f=1:n and b(n>>8,0)+[format(n&255,'08b')]or['0'*8]*f
train
APPS_structured
N Soldiers are lined up for a memory test. They are numbered from 0 to N-1 from left to right. In the test, there are M rounds. In each round, Captain selects one position. Soldier at that position will be numbered 0. All the soldiers to the right of selected position will be numbered one greater than the soldier to his left. All the soldiers to the left of selected position will be numbered one greater than the soldier to his right. eg. if N = 6 and selected position is 3, then the numbering will be [3, 2, 1, 0, 1, 2]. After M rounds, Captain asked each soldier to shout out the greatest number he was assigned during the M rounds. In order to check the correctness, Captain asked you to produce the correct values for each soldier (That is the correct value each soldier should shout out). -----Input----- The first line of the input contains an integer T denoting the number of test cases. First line of each test case contains two integers, N and M. Second line of each test case contains M integers, the positions selected by Captain, in that order. -----Output----- For each test case, output one line with N space separated integers. -----Constraints----- - 1 ≤ T ≤ 10^4 - 1 ≤ N ≤ 10^5 - 1 ≤ M ≤ 10^5 - 1 ≤ Sum of N over all testcases ≤ 10^5 - 1 ≤ Sum of M over all testcases ≤ 10^5 - 0 ≤ Positions selected by captain ≤ N-1 -----Example----- Input 2 4 1 1 6 2 2 3 Output 1 0 1 2 3 2 1 1 2 3
# cook your dish here for _ in range(int(input())): n,m=map(int,input().split()) l=list(map(int,input().split())) ma=max(l) mi=min(l) for i in range(n): y=max(ma-i,i-mi) print(y,end=" ") print()
# cook your dish here for _ in range(int(input())): n,m=map(int,input().split()) l=list(map(int,input().split())) ma=max(l) mi=min(l) for i in range(n): y=max(ma-i,i-mi) print(y,end=" ") print()
train
APPS_structured
The goal of this Kata is to remind/show you, how Z-algorithm works and test your implementation. For a string str[0..n-1], Z array is of same length as string. An element Z[i] of Z array stores length of the longest substring starting from str[i] which is also a prefix of str[0..n-1]. The first entry of Z array is meaning less as complete string is always prefix of itself. Example: Index: 0 1 2 3 4 5 6 7 8 9 10 11 Text: "a a b c a a b x a a a z" Z values: [11, 1, 0, 0, 3, 1, 0, 0, 2, 2, 1, 0] Your task will be to implement Z algorithm in your code and return Z-array. For empty string algorithm should return []. Input: string str Output: Z array For example: print zfunc('ababcaba') [8, 0, 2, 0, 0, 3, 0, 1] Note, that an important part of this kata is that you have to use efficient way to get Z-array (O(n))
def prefix1(a, b): cnt = 0 for i, j in zip(a, b): if i == j: cnt += 1 else: return cnt return cnt def prefix2(a, b, num): for i in range(num, -1, -1): if b.startswith(a[:i]): return i def zfunc(str_): z = [] k = len(str_) for i in range(len(str_)): z.append(prefix2(str_[i:], str_[: k - i], k - i)) #z.append(prefix1(str_[i:], str_[: k - i])) #poor timing return z
def prefix1(a, b): cnt = 0 for i, j in zip(a, b): if i == j: cnt += 1 else: return cnt return cnt def prefix2(a, b, num): for i in range(num, -1, -1): if b.startswith(a[:i]): return i def zfunc(str_): z = [] k = len(str_) for i in range(len(str_)): z.append(prefix2(str_[i:], str_[: k - i], k - i)) #z.append(prefix1(str_[i:], str_[: k - i])) #poor timing return z
train
APPS_structured
Chef bought a huge (effectively infinite) planar island and built $N$ restaurants (numbered $1$ through $N$) on it. For each valid $i$, the Cartesian coordinates of restaurant $i$ are $(X_i, Y_i)$. Now, Chef wants to build $N-1$ straight narrow roads (line segments) on the island. The roads may have arbitrary lengths; restaurants do not have to lie on the roads. The slope of each road must be $1$ or $-1$, i.e. for any two points $(x_1, y_1)$ and $(x_2, y_2)$ on the same road, $|x_1-x_2| = |y_1-y_2|$ must hold. Let's denote the minimum distance Chef has to walk from restaurant $i$ to reach a road by $D_i$. Then, let's denote $a = \mathrm{max}\,(D_1, D_2, \ldots, D_N)$; Chef wants this distance to be minimum possible. Chef is a busy person, so he decided to give you the job of building the roads. You should find a way to build them that minimises $a$ and compute $a \cdot \sqrt{2}$. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains a single integer $N$. - $N$ lines follow. For each valid $i$, the $i$-th of these lines contains two space-separated integers $X_i$ and $Y_i$. -----Output----- For each test case, print a single line containing one real number — the minimum distance $a$ multiplied by $\sqrt{2}$. Your answer will be considered correct if its absolute or relative error does not exceed $10^{-6}$. -----Constraints----- - $1 \le T \le 100$ - $2 \le N \le 10^4$ - $|X_i|, |Y_i| \le 10^9$ for each valid $i$ -----Subtasks----- Subtask #1 (10 points): - $1 \le T \le 10$ - $2 \le N \le 5$ - $|X_i|, |Y_i| \le 10$ for each valid $i$ - $a \cdot \sqrt{2}$ is an integer Subtask #2 (90 points): original constraints -----Example Input----- 2 3 0 0 0 1 0 -1 3 0 1 1 0 -1 0 -----Example Output----- 0.5 0 -----Explanation----- Example case 1: We should build roads described by equations $y-x+0.5 = 0$ and $y-x-0.5 = 0$. Example case 2: We should build roads described by equations $y-x-1 = 0$ and $y+x-1 = 0$.
t = int(input()) for _ in range(t): n = int(input()) co = [] suma = [] diff = [] for i in range(n): x,y = map(int,input().strip().split()) co.append([x,y]) suma.append(x+y) diff.append(x-y) # print(co) suma.sort() diff.sort() # print(suma) # print(diff) mina = 10**9 mina = (abs((suma[0]-suma[1])/2)) mina = min(mina,abs((diff[0]-diff[1])/2)) # print(mina) for i in range(1,n-1): mina = min(mina,abs((suma[i]-suma[i+1])/2),abs((diff[i]-diff[i+1])/2)) # print(i,mina) if(mina == 0.0): break print(mina)
t = int(input()) for _ in range(t): n = int(input()) co = [] suma = [] diff = [] for i in range(n): x,y = map(int,input().strip().split()) co.append([x,y]) suma.append(x+y) diff.append(x-y) # print(co) suma.sort() diff.sort() # print(suma) # print(diff) mina = 10**9 mina = (abs((suma[0]-suma[1])/2)) mina = min(mina,abs((diff[0]-diff[1])/2)) # print(mina) for i in range(1,n-1): mina = min(mina,abs((suma[i]-suma[i+1])/2),abs((diff[i]-diff[i+1])/2)) # print(i,mina) if(mina == 0.0): break print(mina)
train
APPS_structured
Given an array of integers A, find the number of triples of indices (i, j, k) such that: 0 <= i < A.length 0 <= j < A.length 0 <= k < A.length A[i] & A[j] & A[k] == 0, where & represents the bitwise-AND operator. Example 1: Input: [2,1,3] Output: 12 Explanation: We could choose the following i, j, k triples: (i=0, j=0, k=1) : 2 & 2 & 1 (i=0, j=1, k=0) : 2 & 1 & 2 (i=0, j=1, k=1) : 2 & 1 & 1 (i=0, j=1, k=2) : 2 & 1 & 3 (i=0, j=2, k=1) : 2 & 3 & 1 (i=1, j=0, k=0) : 1 & 2 & 2 (i=1, j=0, k=1) : 1 & 2 & 1 (i=1, j=0, k=2) : 1 & 2 & 3 (i=1, j=1, k=0) : 1 & 1 & 2 (i=1, j=2, k=0) : 1 & 3 & 2 (i=2, j=0, k=1) : 3 & 2 & 1 (i=2, j=1, k=0) : 3 & 1 & 2 Note: 1 <= A.length <= 1000 0 <= A[i] < 2^16
class Solution: def countTriplets(self, A: List[int]) -> int: c = Counter(x&y for x in A for y in A) return sum([c[xy] for xy in c for z in A if xy&z == 0])
class Solution: def countTriplets(self, A: List[int]) -> int: c = Counter(x&y for x in A for y in A) return sum([c[xy] for xy in c for z in A if xy&z == 0])
train
APPS_structured
This is the performance edition of [this kata](https://www.codewars.com/kata/ulam-sequences). If you didn't do it yet, you should begin there. --- The Ulam sequence U is defined by `u0=u`, `u1=v`, with the general term `u_n` for `n>2` given by the least integer expressible uniquely as the sum of two distinct earlier terms. In other words, the next number is always the smallest, unique sum of any two previous terms. The first 10 terms of the sequence `U(u0=1, u1=2)` are `[1, 2, 3, 4, 6, 8, 11, 13, 16, 18]`. * Here, the first term after the initial `1, 2` is obviously `3` since `3=1+2`. * The next term is `4=1+3` (we don't have to worry about `4=2+2` since it is a sum of a single term instead of two distinct terms) * `5` is not a member of the sequence since it is representable in two ways: `5=1+4=2+3`, but `6=2+4` is a member (since `3+3` isn't a valid calculation). You'll have to write a code that creates an Ulam Sequence starting with `u0`, `u1` and containing `n` terms. --- # ___The pitfall...___ While the passing solutions of the first version could have a time complexity of O(N^(3)) (or even O(N^(4))!!), with 20 tests up to 100 terms only, here you'll have to manage generation of sequences up to 1500 terms before time out. ___Inputs:___ * `u0` and `u1`: integers, greater than or equal to 1 * `n`: integer greater than 1, length of the returned list ___Configuration of the tests:___ ```if:python * 6 small fixed tests * 20 random tests on small sequences (10 to 30 terms) * 13 large random tests (1500 terms) ``` ```if:ruby * 6 small fixed tests * 20 random tests on small sequences (10 to 30 terms) * 16 large random tests (1500 terms) ``` ```if:javascript,go * 6 small fixed tests * 40 random tests on small sequences (10 to 30 terms) * 30 large random tests (2450 terms) ``` --- Description Reference: http://mathworld.wolfram.com/UlamSequence.html
from collections import defaultdict from heapq import heappop, heappush def ulam_sequence(u0, u1, n): q, seen, lst = [u1], defaultdict(int), [u0] seen[u1] = 1 while len(lst) < n: while 1: # Extract next Ulam number last = heappop(q) if seen[last] == 1: break for v in lst: # Generate all possible new Ulam numbers, using the last found x = v+last if x not in seen: heappush(q,x) # candidate found seen[x] += 1 lst.append(last) return lst
from collections import defaultdict from heapq import heappop, heappush def ulam_sequence(u0, u1, n): q, seen, lst = [u1], defaultdict(int), [u0] seen[u1] = 1 while len(lst) < n: while 1: # Extract next Ulam number last = heappop(q) if seen[last] == 1: break for v in lst: # Generate all possible new Ulam numbers, using the last found x = v+last if x not in seen: heappush(q,x) # candidate found seen[x] += 1 lst.append(last) return lst
train
APPS_structured
To celebrate today's launch of my Hero's new book: Alan Partridge: Nomad, We have a new series of kata arranged around the great man himself. Given an array of terms, if any of those terms relate to Alan Partridge, return Mine's a Pint! The number of ! after the t should be determined by the number of Alan related terms you find in the provided array (x). The related terms are: Partridge PearTree Chat Dan Toblerone Lynn AlphaPapa Nomad If you don't find any related terms, return 'Lynn, I've pierced my foot on a spike!!' All Hail King Partridge Other katas in this series: Alan Partridge II - Apple Turnover Alan Partridge III - London
def part(arr): l = ["Partridge", "PearTree", "Chat", "Dan", "Toblerone", "Lynn", "AlphaPapa", "Nomad"] s = len([i for i in arr if i in l]) return "Mine's a Pint"+"!"*s if s>0 else 'Lynn, I\'ve pierced my foot on a spike!!'
def part(arr): l = ["Partridge", "PearTree", "Chat", "Dan", "Toblerone", "Lynn", "AlphaPapa", "Nomad"] s = len([i for i in arr if i in l]) return "Mine's a Pint"+"!"*s if s>0 else 'Lynn, I\'ve pierced my foot on a spike!!'
train
APPS_structured
Vlad enjoys listening to music. He lives in Sam's Town. A few days ago he had a birthday, so his parents gave him a gift: MP3-player! Vlad was the happiest man in the world! Now he can listen his favorite songs whenever he wants! Vlad built up his own playlist. The playlist consists of N songs, each has a unique positive integer length. Vlad likes all the songs from his playlist, but there is a song, which he likes more than the others. It's named "Uncle Johny". After creation of the playlist, Vlad decided to sort the songs in increasing order of their lengths. For example, if the lengths of the songs in playlist was {1, 3, 5, 2, 4} after sorting it becomes {1, 2, 3, 4, 5}. Before the sorting, "Uncle Johny" was on K-th position (1-indexing is assumed for the playlist) in the playlist. Vlad needs your help! He gives you all the information of his playlist. Your task is to find the position of "Uncle Johny" in the sorted playlist. -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains one integer N denoting the number of songs in Vlad's playlist. The second line contains N space-separated integers A1, A2, ..., AN denoting the lenghts of Vlad's songs. The third line contains the only integer K - the position of "Uncle Johny" in the initial playlist. -----Output----- For each test case, output a single line containing the position of "Uncle Johny" in the sorted playlist. -----Constraints----- 1 ≤ T ≤ 1000 1 ≤ K ≤ N ≤ 100 1 ≤ Ai ≤ 109 -----Example----- Input: 3 4 1 3 4 2 2 5 1 2 3 9 4 5 5 1 2 3 9 4 1 Output: 3 4 1 -----Explanation----- In the example test there are T=3 test cases. Test case 1 In the first test case N equals to 4, K equals to 2, A equals to {1, 3, 4, 2}. The answer is 3, because {1, 3, 4, 2} -> {1, 2, 3, 4}. A2 now is on the 3-rd position. Test case 2 In the second test case N equals to 5, K equals to 5, A equals to {1, 2, 3, 9, 4}. The answer is 4, because {1, 2, 3, 9, 4} -> {1, 2, 3, 4, 9}. A5 now is on the 4-th position. Test case 3 In the third test case N equals to 5, K equals to 1, A equals to {1, 2, 3, 9, 4}. The answer is 1, because {1, 2, 3, 9, 4} -> {1, 2, 3, 4, 9}. A1 stays on the 1-th position. -----Note----- "Uncle Johny" is a real song performed by The Killers.
import sys def johnny(a,k): n = len(a) a = sorted(a) l = 0 h = n-1 while l <= h: mid = (l+h)//2 if a[mid] == k: return mid + 1 if a[mid] > k: h = mid-1 else: l = mid+1 return -1 t = int(input()) while t: n = int(input()) a = [int(k) for k in input().split()] k = int(input()) x = a[k-1] ans = johnny(a,x) print(ans) t -= 1 # cook your dish here
import sys def johnny(a,k): n = len(a) a = sorted(a) l = 0 h = n-1 while l <= h: mid = (l+h)//2 if a[mid] == k: return mid + 1 if a[mid] > k: h = mid-1 else: l = mid+1 return -1 t = int(input()) while t: n = int(input()) a = [int(k) for k in input().split()] k = int(input()) x = a[k-1] ans = johnny(a,x) print(ans) t -= 1 # cook your dish here
train
APPS_structured
You certainly can tell which is the larger number between 2^(10) and 2^(15). But what about, say, 2^(10) and 3^(10)? You know this one too. Things tend to get a bit more complicated with **both** different bases and exponents: which is larger between 3^(9) and 5^(6)? Well, by now you have surely guessed that you have to build a function to compare powers, returning -1 if the first member is larger, 0 if they are equal, 1 otherwise; powers to compare will be provided in the `[base, exponent]` format: ```python compare_powers([2,10],[2,15])==1 compare_powers([2,10],[3,10])==1 compare_powers([2,10],[2,10])==0 compare_powers([3,9],[5,6])==-1 compare_powers([7,7],[5,8])==-1 ``` ```if:nasm int compare_powers(const int n1[2], const int n2[2]) ``` Only positive integers will be tested, incluing bigger numbers - you are warned now, so be diligent try to implement an efficient solution not to drain too much on CW resources ;)!
from math import log def compare_powers(*numbers): a,b = map(lambda n: n[1]*log(n[0]), numbers) return (a<b) - (a>b)
from math import log def compare_powers(*numbers): a,b = map(lambda n: n[1]*log(n[0]), numbers) return (a<b) - (a>b)
train
APPS_structured