input
stringlengths 50
13.9k
| output_program
stringlengths 5
655k
| output_answer
stringlengths 5
655k
| split
stringclasses 1
value | dataset
stringclasses 1
value |
---|---|---|---|---|
Today is rose day, batch mates of Kabir and Tara decided to celebrate this day by exchanging roses with each other.
Note:$Note:$ exchanging means both the boy and the girl will give rose to each other.
In the class there are B$B$ boys and G$G$ girls.
Exchange of rose will take place if and only if at least one of them hasn't received a rose from anyone else and a rose can be exchanged only once.
Tara has to bring maximum sufficient roses for everyone and is confused as she don't know how many roses to buy.You are a friend of Kabir, so help him to solve the problem so that he can impress Tara by helping her.
-----Input:-----
- First line will contain T$T$, number of test cases.
- Each test case contains two space separated integers B$B$ (Number of boys) and G$G$ (Number of Girls).
-----Output:-----
For each test case, output in a single line the total number of roses exchanged.
-----Constraints:-----
- 1≤T≤105$1 \leq T \leq 10^5$
- 1≤B≤109$1 \leq B \leq 10^{9}$
- 1≤G≤109$1 \leq G \leq 10^{9}$
-----Sample Input:-----
1
2 3
-----Sample Output:-----
8 | # cook your dish here
for i in range(int(input())):
print(2*(sum(list(map(int, input().split())))-1)) | # cook your dish here
for i in range(int(input())):
print(2*(sum(list(map(int, input().split())))-1)) | train | APPS_structured |
You are given three numbers $a$, $b$, $c$ . Write a program to determine the largest number that is less than or equal to $c$ and leaves a remainder $b$ when divided by $a$.
-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains a single line of input, having three integers $a$, $b$, $c$.
-----Output:-----
- For each testcase, output in a single line the largest number less than or equal to $c$.
-----Constraints:-----
- $1 \leq T \leq 100000$
- $0 \leq b < a < c \leq$ $10$^18
-----Sample Input:-----
1
7 2 10
-----Sample Output:-----
9 | # cook your dish here
t = int(input())
for i in range(0,t):
a=input().split()
b=list(map(int,a))
n=int(b[2]/b[0])
if((b[0])*n+b[1]<=b[2]):
print((b[0])*n+b[1])
else:
print((b[0])*(n-1)+b[1]) | # cook your dish here
t = int(input())
for i in range(0,t):
a=input().split()
b=list(map(int,a))
n=int(b[2]/b[0])
if((b[0])*n+b[1]<=b[2]):
print((b[0])*n+b[1])
else:
print((b[0])*(n-1)+b[1]) | train | APPS_structured |
This is the simple version of Shortest Code series. If you need some challenges, please try the [challenge version](http://www.codewars.com/kata/570f45fab29c705d330004e3)
## Task:
There is a rectangular land and we need to plant trees on the edges of that land.
I will give you three parameters:
```width``` and ```length```, two integers > 1 that represents the land's width and length;
```gaps```, an integer >= 0, that is the distance between two trees.
Return how many trees have to be planted, if you can't achieve a symmetrical layout(see Example 3) then return 0.
### Example:
```
Example1:
width=3, length=3, gaps=1 o - o
we can plant 4 trees - -
sc(3,3,1)=4 o - o
Example2:
width=3, length=3, gaps=3 o - -
we can plant 2 trees - -
sc(3,3,3)=2 - - o
Example3:
width=3, length=3, gaps=2 o - -
if we plant 2 trees, some x o
gaps of two trees will >2 x x x
if we plant 3 trees, some o - -
gaps of two trees will <2 x o
so we can not finish it o - -
sc(3,3,2)=0
Example4:
width=7, length=7, gaps=3 o - - - o - -
we can plant 6 trees - -
sc(3,3,3)=6 - o
- -
o -
- -
- - o - - - o
some corner case:
Example5:
width=3, length=3, gaps=0 o o o
we can plant 8 trees o o
sc(3,3,0)=8 o o o
Example6:
width=3, length=3, gaps=10 o 1 2
in this case, the max gaps 1 3
of two trees is 3 2 3 o
gaps=10 can not finished
so sc(3,3,10)=0
```
### Series:
- [Bug in Apple](http://www.codewars.com/kata/56fe97b3cc08ca00e4000dc9)
- [Father and Son](http://www.codewars.com/kata/56fe9a0c11086cd842000008)
- [Jumping Dutch act](http://www.codewars.com/kata/570bcd9715944a2c8e000009)
- [Planting Trees](http://www.codewars.com/kata/5710443187a36a9cee0005a1)
- [Give me the equation](http://www.codewars.com/kata/56fe9b65cc08cafbc5000de3)
- [Find the murderer](http://www.codewars.com/kata/570f3fc5b29c702c5500043e)
- [Reading a Book](http://www.codewars.com/kata/570ca6a520c69f39dd0016d4)
- [Eat watermelon](http://www.codewars.com/kata/570df12ce6e9282a7d000947)
- [Special factor](http://www.codewars.com/kata/570e5d0b93214b1a950015b1)
- [Guess the Hat](http://www.codewars.com/kata/570ef7a834e61306da00035b)
- [Symmetric Sort](http://www.codewars.com/kata/5705aeb041e5befba20010ba)
- [Are they symmetrical?](http://www.codewars.com/kata/5705cc3161944b10fd0004ba)
- [Max Value](http://www.codewars.com/kata/570771871df89cf59b000742)
- [Trypophobia](http://www.codewars.com/kata/56fe9ffbc25bf33fff000f7c)
- [Virus in Apple](http://www.codewars.com/kata/5700af83d1acef83fd000048)
- [Balance Attraction](http://www.codewars.com/kata/57033601e55d30d3e0000633)
- [Remove screws I](http://www.codewars.com/kata/5710a50d336aed828100055a)
- [Remove screws II](http://www.codewars.com/kata/5710a8fd336aed00d9000594)
- [Regular expression compression](http://www.codewars.com/kata/570bae4b0237999e940016e9)
- [Collatz Array(Split or merge)](http://www.codewars.com/kata/56fe9d579b7bb6b027000001)
- [Tidy up the room](http://www.codewars.com/kata/5703ace6e55d30d3e0001029)
- [Waiting for a Bus](http://www.codewars.com/kata/57070eff924f343280000015) | def sc(width,length,gaps):
#your code here
a, b = divmod(2*width + 2*length - 4, gaps+1)
return 0 if b else a | def sc(width,length,gaps):
#your code here
a, b = divmod(2*width + 2*length - 4, gaps+1)
return 0 if b else a | train | APPS_structured |
You are given two integer sequences, each of length N: a_1, ..., a_N and b_1, ..., b_N.
There are N^2 ways to choose two integers i and j such that 1 \leq i, j \leq N. For each of these N^2 pairs, we will compute a_i + b_j and write it on a sheet of paper.
That is, we will write N^2 integers in total.
Compute the XOR of these N^2 integers.
Definition of XOR
The XOR of integers c_1, c_2, ..., c_m is defined as follows:
- Let the XOR be X. In the binary representation of X, the digit in the 2^k's place (0 \leq k; k is an integer) is 1 if there are an odd number of integers among c_1, c_2, ...c_m whose binary representation has 1 in the 2^k's place, and 0 if that number is even.
For example, let us compute the XOR of 3 and 5. The binary representation of 3 is 011, and the binary representation of 5 is 101, thus the XOR has the binary representation 110, that is, the XOR is 6.
-----Constraints-----
- All input values are integers.
- 1 \leq N \leq 200,000
- 0 \leq a_i, b_i < 2^{28}
-----Input-----
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
b_1 b_2 ... b_N
-----Output-----
Print the result of the computation.
-----Sample Input-----
2
1 2
3 4
-----Sample Output-----
2
On the sheet, the following four integers will be written: 4(1+3), 5(1+4), 5(2+3) and 6(2+4). | N = int(input())
A = [int(a) for a in input().split()]
B = [int(a) for a in input().split()]
def xor(L):
a = 0
for l in L: a ^= l
return a
def chk(L1, L2, k):
L1.sort()
L2.sort()
s, j = 0, 0
for i in range(N)[::-1]:
while j < N and L1[i] + L2[j] < k:
j += 1
s += N - j
return s % 2 * k
t = (xor(A) ^ xor(B)) * (N % 2)
for i in range(28):
m = (1 << i+1) - 1
t ^= chk([a&m for a in A], [b&m for b in B], m + 1)
print(t) | N = int(input())
A = [int(a) for a in input().split()]
B = [int(a) for a in input().split()]
def xor(L):
a = 0
for l in L: a ^= l
return a
def chk(L1, L2, k):
L1.sort()
L2.sort()
s, j = 0, 0
for i in range(N)[::-1]:
while j < N and L1[i] + L2[j] < k:
j += 1
s += N - j
return s % 2 * k
t = (xor(A) ^ xor(B)) * (N % 2)
for i in range(28):
m = (1 << i+1) - 1
t ^= chk([a&m for a in A], [b&m for b in B], m + 1)
print(t) | train | APPS_structured |
## Description:
Remove all exclamation marks from the end of words. Words are separated by spaces in the sentence.
### Examples
```
remove("Hi!") === "Hi"
remove("Hi!!!") === "Hi"
remove("!Hi") === "!Hi"
remove("!Hi!") === "!Hi"
remove("Hi! Hi!") === "Hi Hi"
remove("!!!Hi !!hi!!! !hi") === "!!!Hi !!hi !hi"
``` | import re
def remove(s):
return re.sub(r"(?<=\w)!+(?=\W)*", "", s) | import re
def remove(s):
return re.sub(r"(?<=\w)!+(?=\W)*", "", s) | train | APPS_structured |
# Task
Suppose there are `n` people standing in a circle and they are numbered 1 through n in order.
Person 1 starts off with a sword and kills person 2. He then passes the sword to the next person still standing, in this case person 3. Person 3 then uses the sword to kill person 4, and passes it to person 5. This pattern continues around and around the circle until just one person remains.
What is the number of this person?
# Example:
For `n = 5`, the result should be `3`.
```
1 kills 2, passes to 3.
3 kills 4, passes to 5.
5 kills 1, passes to 3.
3 kills 5 and wins.```
# Input/Output
- `[input]` integer `n`
The number of people. 1 through n standing in a circle.
`1 <= n <= 1e9`
- `[output]` an integer
The index of the last person standing. | circle_slash=lambda n:int(bin(n)[3:]+'1',2) | circle_slash=lambda n:int(bin(n)[3:]+'1',2) | train | APPS_structured |
## Snail Sort
Given an `n x n` array, return the array elements arranged from outermost elements to the middle element, traveling clockwise.
```
array = [[1,2,3],
[4,5,6],
[7,8,9]]
snail(array) #=> [1,2,3,6,9,8,7,4,5]
```
For better understanding, please follow the numbers of the next array consecutively:
```
array = [[1,2,3],
[8,9,4],
[7,6,5]]
snail(array) #=> [1,2,3,4,5,6,7,8,9]
```
This image will illustrate things more clearly:
NOTE: The idea is not sort the elements from the lowest value to the highest; the idea is to traverse the 2-d array in a clockwise snailshell pattern.
NOTE 2: The 0x0 (empty matrix) is represented as en empty array inside an array `[[]]`. | def trans(array):
#Do an inverse transpose (i.e. rotate left by 90 degrees
return [[row[-i-1] for row in array] for i in range(len(array[0]))] if len(array)>0 else array
def snail(array):
output=[]
while len(array)>0:
#Add the 1st row of the array
output+=array[0]
#Chop off the 1st row and transpose
array=trans(array[1:])
return output | def trans(array):
#Do an inverse transpose (i.e. rotate left by 90 degrees
return [[row[-i-1] for row in array] for i in range(len(array[0]))] if len(array)>0 else array
def snail(array):
output=[]
while len(array)>0:
#Add the 1st row of the array
output+=array[0]
#Chop off the 1st row and transpose
array=trans(array[1:])
return output | train | APPS_structured |
Some languages like Chinese, Japanese, and Thai do not have spaces between words. However, most natural languages processing tasks like part-of-speech tagging require texts that have segmented words. A simple and reasonably effective algorithm to segment a sentence into its component words is called "MaxMatch".
## MaxMatch
MaxMatch starts at the first character of a sentence and tries to find the longest valid word starting from that character. If no word is found, the first character is deemed the longest "word", regardless of its validity. In order to find the rest of the words, MaxMatch is then recursively invoked on all of the remaining characters until no characters remain. A list of all of the words that were found is returned.
So for the string `"happyday"`, `"happy"` is found because `"happyday"` is not a valid word, nor is `"happyda"`, nor `"happyd"`. Then, MaxMatch is called on `"day"`, and `"day"` is found. The output is the list `["happy", "day"]` in that order.
## The Challenge
```if:javascript
Write `maxMatch`, which takes an alphanumeric, spaceless, lowercased `String` as input and returns an `Array` of all the words found, in the order they were found.
**All valid words are in the** `Set` `VALID_WORDS`, which only contains around 500 English words.
```
```if:haskell
Write `maxMatch`, which takes an alphanumeric, spaceless, lowercased `String` as input and returns a `[String]` of all the words found, in the order they were found. All valid words are in the `[String]` `validWords`, which only contains around 500 English words.
```
```if:java
Write `maxMatch`, which takes an alphanumeric, spaceless, lowercased `String` as input and returns a `List` of `String`s which are all the words found, in the order they were found. All valid words are in the `Set` `Preloaded.VALID_WORDS`, , which only contains around 500 English words.
```
```if:python
Write `max_match`, which takes an alphanumeric, spaceless, lowercased `String` as input and returns a `List` of `String`s of all the words found, in the order they were found. **All valid words are in the** `Set` `VALID_WORDS`, which only contains around 500 English words.
```
```if:ruby
Write `max_match`, which takes an alphanumeric, spaceless, lowercased `String` as input and returns an `Array` of `String`s of all the words found, in the order they were found. All valid words are in the `Array` `VALID_WORDS`, which only contains around 500 English words.
```
```if:kotlin
Write `maxMatch`, which takes an alphanumeric, spaceless, lowercased `String` as input and returns a `List` of `String`s which are all the words found, in the order they were found. All valid words are in the `Set` `VALID_WORDS`, which only contains around 500 English words.
```
**Note:** This algorithm is simple and operates better on Chinese text, so accept the fact that some words will be segmented wrongly.
Happy coding :) | # KenKamau's solution
def max_match(st):
for i in range(len(st),0,-1):
if i == 1 or st[:i] in VALID_WORDS:
return [st[:i]] + max_match(st[i:])
return [] | # KenKamau's solution
def max_match(st):
for i in range(len(st),0,-1):
if i == 1 or st[:i] in VALID_WORDS:
return [st[:i]] + max_match(st[i:])
return [] | train | APPS_structured |
Dhruvil has always been a studious person and will be completing his Engineering soon. He is always kneen about solving problems and is preparing hard for his next interview at Hackerrank. He has practiced lots of problems and now he came across this problem.
Given a message containing English letters(A-Z), it is being encoded to numbers using the following mapping:
'A' -> 1,'B' -> 2 ……………… 'Z' -> 26.
Now, given a non-empty string containing only digits, help Dhruvil determine the total number of ways to decode it.
While decoding you need to choose a substring of charachters and not a subsequence. Also a chosen substring should not contain any leading "0"s, but can contain trailing "0"s. Since the output can be very large print the answer as modulo 10^9 + 7 i.e 1000000007.
-----Input:-----
The first line of the input consists of single integer T, the number of test cases.
Each test case consists of a string.
-----Output:-----
For each test case print a single integer - the total number of ways to decode the digit string.
-----Constraints-----
- $1 \leq T \leq 1000$
- $2 \leq S \leq 10^9$
-----Sample Input:-----
2
12
226
-----Sample Output:-----
2
3
-----EXPLANATION:-----
There are 2 possible ways. It could be decoded as "AB" {1,2} or "L" {12}.
There are 3 possible ways. It could be decoded as "BZ" {2,26}, "VF" {22,6}, or "BBF" {2,2,6}. | import sys
import math
import bisect
from sys import stdin,stdout
from math import gcd,floor,sqrt,log
from collections import defaultdict as dd
from bisect import bisect_left as bl,bisect_right as br
sys.setrecursionlimit(100000000)
ii =lambda: int(input())
si =lambda: input()
jn =lambda x,l: x.join(map(str,l))
sl =lambda: list(map(str,input().strip()))
mi =lambda: list(map(int,input().split()))
mif =lambda: list(map(float,input().split()))
lii =lambda: list(map(int,input().split()))
ceil =lambda x: int(x) if(x==int(x)) else int(x)+1
ceildiv=lambda x,d: x//d if(x%d==0) else x//d+1
flush =lambda: stdout.flush()
stdstr =lambda: stdin.readline()
stdint =lambda: int(stdin.readline())
stdpr =lambda x: stdout.write(str(x))
mod=1000000007
def sol(s):
dp = [0] * (len(s) + 2)
dp[0] = 1
for i in range(len(s)):
if int(s[i]) != 0:
dp[i+1] += dp[i]
if int(s[i:i+2]) >= 10 and int(s[i:i+2]) <= 26:
dp[i+2] += dp[i]
return dp[len(s)]
#main code
for _ in range(ii()):
s=si()
ans=sol(s)
print(ans%mod)
| import sys
import math
import bisect
from sys import stdin,stdout
from math import gcd,floor,sqrt,log
from collections import defaultdict as dd
from bisect import bisect_left as bl,bisect_right as br
sys.setrecursionlimit(100000000)
ii =lambda: int(input())
si =lambda: input()
jn =lambda x,l: x.join(map(str,l))
sl =lambda: list(map(str,input().strip()))
mi =lambda: list(map(int,input().split()))
mif =lambda: list(map(float,input().split()))
lii =lambda: list(map(int,input().split()))
ceil =lambda x: int(x) if(x==int(x)) else int(x)+1
ceildiv=lambda x,d: x//d if(x%d==0) else x//d+1
flush =lambda: stdout.flush()
stdstr =lambda: stdin.readline()
stdint =lambda: int(stdin.readline())
stdpr =lambda x: stdout.write(str(x))
mod=1000000007
def sol(s):
dp = [0] * (len(s) + 2)
dp[0] = 1
for i in range(len(s)):
if int(s[i]) != 0:
dp[i+1] += dp[i]
if int(s[i:i+2]) >= 10 and int(s[i:i+2]) <= 26:
dp[i+2] += dp[i]
return dp[len(s)]
#main code
for _ in range(ii()):
s=si()
ans=sol(s)
print(ans%mod)
| train | APPS_structured |
**This Kata is intended as a small challenge for my students**
All Star Code Challenge #16
Create a function called noRepeat() that takes a string argument and returns a single letter string of the **first** not repeated character in the entire string.
``` haskell
noRepeat "aabbccdde" `shouldBe` 'e'
noRepeat "wxyz" `shouldBe` 'w'
noRepeat "testing" `shouldBe` 'e'
```
Note:
ONLY letters from the english alphabet will be used as input
There will ALWAYS be at least one non-repeating letter in the input string | def no_repeat(string):
if string.count(string[0]) == 1:
return string[0]
else:
return no_repeat(string.replace(string[0], '')) | def no_repeat(string):
if string.count(string[0]) == 1:
return string[0]
else:
return no_repeat(string.replace(string[0], '')) | train | APPS_structured |
In Finite Encyclopedia of Integer Sequences (FEIS), all integer sequences of lengths between 1 and N (inclusive) consisting of integers between 1 and K (inclusive) are listed.
Let the total number of sequences listed in FEIS be X. Among those sequences, find the (X/2)-th (rounded up to the nearest integer) lexicographically smallest one.
-----Constraints-----
- 1 \leq N,K \leq 3 × 10^5
- N and K are integers.
-----Input-----
Input is given from Standard Input in the following format:
K N
-----Output-----
Print the (X/2)-th (rounded up to the nearest integer) lexicographically smallest sequence listed in FEIS, with spaces in between, where X is the total number of sequences listed in FEIS.
-----Sample Input-----
3 2
-----Sample Output-----
2 1
There are 12 sequences listed in FEIS: (1),(1,1),(1,2),(1,3),(2),(2,1),(2,2),(2,3),(3),(3,1),(3,2),(3,3).
The (12/2 = 6)-th lexicographically smallest one among them is (2,1). | # coding: utf-8
# Your code here!
import sys
read = sys.stdin.read
readline = sys.stdin.readline
sys.setrecursionlimit(10**5)
k,n = list(map(int, read().split()))
if k%2==0:
print((*([k//2]+[k]*(n-1))))
return
if k==1:
print((*[1]*((n+1)//2)))
return
ans = [(k+1)//2]*n
d = 0
def f(k,i,d):
# d <= 1+k+...+k^i?
v = 1
for j in range(i):
v *= k
v += 1
if v > d: return True
return False
def g(k,i):
# 1+k+...+k^i
v = 1
for j in range(i):
v *= k
v += 1
return v
for i in range(1,n):
if f(k,n-i-1,d):
d += 1
continue
"""
以下 300000 >= d >= 1+k+...+k^(n-i-1)
i 番目の項から真ん中にならない
v 番目を目指す
"""
v = (g(k,n-i)+d+1)//2 - d - 1
for j in range(i,n):
#print(v)
if v==0:
ans[j] = 0
continue
p = g(k,n-j-1)
q = (v-1)//p
#print(v,j,p,q)
ans[j] = q+1
v -= 1+q*p
break
while ans[-1]==0:
ans.pop()
print((*ans))
| # coding: utf-8
# Your code here!
import sys
read = sys.stdin.read
readline = sys.stdin.readline
sys.setrecursionlimit(10**5)
k,n = list(map(int, read().split()))
if k%2==0:
print((*([k//2]+[k]*(n-1))))
return
if k==1:
print((*[1]*((n+1)//2)))
return
ans = [(k+1)//2]*n
d = 0
def f(k,i,d):
# d <= 1+k+...+k^i?
v = 1
for j in range(i):
v *= k
v += 1
if v > d: return True
return False
def g(k,i):
# 1+k+...+k^i
v = 1
for j in range(i):
v *= k
v += 1
return v
for i in range(1,n):
if f(k,n-i-1,d):
d += 1
continue
"""
以下 300000 >= d >= 1+k+...+k^(n-i-1)
i 番目の項から真ん中にならない
v 番目を目指す
"""
v = (g(k,n-i)+d+1)//2 - d - 1
for j in range(i,n):
#print(v)
if v==0:
ans[j] = 0
continue
p = g(k,n-j-1)
q = (v-1)//p
#print(v,j,p,q)
ans[j] = q+1
v -= 1+q*p
break
while ans[-1]==0:
ans.pop()
print((*ans))
| train | APPS_structured |
Implement a function which convert the given boolean value into its string representation. | def boolean_to_string(b):
#your code he
p = str(b);
print (type(p))
print (p)
return p | def boolean_to_string(b):
#your code he
p = str(b);
print (type(p))
print (p)
return p | train | APPS_structured |
Chef has a strip of length $N$ units and he wants to tile it using $4$ kind of tiles
-A Red tile of $2$ unit length
-A Red tile of $1$ unit length
-A Blue tile of $2$ unit length
-A Blue tile of $1$ unit length
Chef is having an infinite supply of each of these tiles. He wants to find out the number of ways in which he can tile the strip. Help him find this number.
Since this number can be large, output your answer modulo 1000000007 ($10^9 + 7$).
-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, an integer $N$.
-----Output:-----
For each testcase, output in a single line your answer modulo 1000000007.
-----Constraints-----
- $1 \leq T \leq 1000$
- $2 \leq N \leq 10^{18}$
-----Sample Input:-----
1
2
-----Sample Output:-----
6
-----EXPLANATION:-----
It can be seen that for a strip of length $2$, there are $6$ possible configurations.
$NOTE : $ 2 tiles of 1 unit length are different from 1 tile of 2 unit length. | # Fibonacci Series using
# Optimized Method
# function that returns nth
# Fibonacci number
MOD = 1000000007
def fib(n):
F = [[2, 2],
[1, 0]]
power(F, n - 1)
ans = [6, 2]
return (F[0][0] * 6 + F[0][1] * 2) % MOD
# return F[0][0]
def multiply(F, M):
x = (F[0][0] * M[0][0] +
F[0][1] * M[1][0]) % MOD
y = (F[0][0] * M[0][1] +
F[0][1] * M[1][1]) % MOD
z = (F[1][0] * M[0][0] +
F[1][1] * M[1][0]) % MOD
w = (F[1][0] * M[0][1] +
F[1][1] * M[1][1]) % MOD
F[0][0] = x
F[0][1] = y
F[1][0] = z
F[1][1] = w
def power(F, n):
if n == 0 or n == 1:
return
M = [[2, 2],
[1, 0]]
power(F, n // 2)
multiply(F, F)
if n % 2 != 0:
multiply(F, M)
for _ in range(int(input())):
n = int(input())
ans = 1
if n == 0:
ans = 1
elif n == 1:
ans = 2
elif n == 2:
ans = 6
else:
ans = fib(n-1)
print(ans)
| # Fibonacci Series using
# Optimized Method
# function that returns nth
# Fibonacci number
MOD = 1000000007
def fib(n):
F = [[2, 2],
[1, 0]]
power(F, n - 1)
ans = [6, 2]
return (F[0][0] * 6 + F[0][1] * 2) % MOD
# return F[0][0]
def multiply(F, M):
x = (F[0][0] * M[0][0] +
F[0][1] * M[1][0]) % MOD
y = (F[0][0] * M[0][1] +
F[0][1] * M[1][1]) % MOD
z = (F[1][0] * M[0][0] +
F[1][1] * M[1][0]) % MOD
w = (F[1][0] * M[0][1] +
F[1][1] * M[1][1]) % MOD
F[0][0] = x
F[0][1] = y
F[1][0] = z
F[1][1] = w
def power(F, n):
if n == 0 or n == 1:
return
M = [[2, 2],
[1, 0]]
power(F, n // 2)
multiply(F, F)
if n % 2 != 0:
multiply(F, M)
for _ in range(int(input())):
n = int(input())
ans = 1
if n == 0:
ans = 1
elif n == 1:
ans = 2
elif n == 2:
ans = 6
else:
ans = fib(n-1)
print(ans)
| train | APPS_structured |
Your task is to find the number couple with the greatest difference from a given array of number-couples.
All number couples will be given as strings and all numbers in them will be positive integers.
For instance: ['56-23','1-100']; in this case, you should identify '1-100' as the number couple with the greatest difference and return it.
In case there are more than one option, for instance ['1-3','5-7','2-3'], you should identify whichever is first, so in this case '1-3'.
If there is no difference, like so ['11-11', '344-344'], return false. | def diff(arr):
r = arr and max(arr, key = lambda x : abs(eval(x)))
return bool(arr and eval(r)) and r | def diff(arr):
r = arr and max(arr, key = lambda x : abs(eval(x)))
return bool(arr and eval(r)) and r | train | APPS_structured |
Chef and Paja are bored, so they are playing an infinite game of ping pong. The rules of the game are as follows:
- The players play an infinite number of games. At the end of each game, the player who won it scores a point.
- In each game, one of the players serves. Chef serves in the first game.
- After every $K$ points are scored (regardless of which players scored them), i.e. whenever $K$ games have been played since the last time the serving player changed, the player that serves in the subsequent games changes: if Chef served in the game that just finished, then Paja will serve in the next game and all subsequent games until the serving player changes again; if Paja served, then Chef will serve.
The players got a little too caught up in the game and they forgot who is supposed to serve in the next game. Will you help them determine that? So far, Chef has scored $X$ points and Paja has scored $Y$ points.
-----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 three space-separated integers $X$, $Y$ and $K$.
-----Output-----
For each test case, print a single line containing the string "Chef" if Chef is supposed to serve next or "Paja" otherwise (without quotes).
-----Constraints-----
- $1 \le T \le 50$
- $0 \le X, Y \le 10^9$
- $1 \le K \le 10^9$
-----Subtasks-----
Subtask #1 (100 points): original constraints
-----Example Input-----
3
1 3 3
5 7 2
38657 76322 564
-----Example Output-----
Paja
Chef
Paja
-----Explanation-----
Example case 1: Chef served for the first three games, after that Paja started serving. He only served in one game, so he is supposed to serve next. | # cook your dish here
# cook your dish here
t=int(input())
for i in range(t):
x,y,k=map(int,input().split())
a=x+y
b=a//k
if b%2==0:
print("Chef")
else:
print("Paja") | # cook your dish here
# cook your dish here
t=int(input())
for i in range(t):
x,y,k=map(int,input().split())
a=x+y
b=a//k
if b%2==0:
print("Chef")
else:
print("Paja") | train | APPS_structured |
Given a string, capitalize the letters that occupy even indexes and odd indexes separately, and return as shown below. Index `0` will be considered even.
For example, `capitalize("abcdef") = ['AbCdEf', 'aBcDeF']`. See test cases for more examples.
The input will be a lowercase string with no spaces.
Good luck!
If you like this Kata, please try:
[Indexed capitalization](https://www.codewars.com/kata/59cfc09a86a6fdf6df0000f1)
[Even-odd disparity](https://www.codewars.com/kata/59c62f1bdcc40560a2000060) | def capitalize(s):
Even = ''
Odd = ''
Result = []
for i in range(len(s)):
if i % 2 == 0:
Even += s[i].upper()
else:
Even += s[i]
if i % 2 != 0:
Odd += s[i].upper()
else:
Odd += s[i]
Result.append(Even)
Result.append(Odd)
return Result;
| def capitalize(s):
Even = ''
Odd = ''
Result = []
for i in range(len(s)):
if i % 2 == 0:
Even += s[i].upper()
else:
Even += s[i]
if i % 2 != 0:
Odd += s[i].upper()
else:
Odd += s[i]
Result.append(Even)
Result.append(Odd)
return Result;
| train | APPS_structured |
Complete the solution so that it returns true if it contains any duplicate argument values. Any number of arguments may be passed into the function.
The array values passed in will only be strings or numbers. The only valid return values are `true` and `false`.
Examples:
```
solution(1, 2, 3) --> false
solution(1, 2, 3, 2) --> true
solution('1', '2', '3', '2') --> true
``` | def solution(*args):
# your code here
l = list(args)
s = set(l)
return len(s)!=len(l) | def solution(*args):
# your code here
l = list(args)
s = set(l)
return len(s)!=len(l) | train | APPS_structured |
You are teaching students to generate strings consisting of unique lowercase latin characters (a-z). You give an example reference string $s$ to the students.
You notice that your students just copy paste the reference string instead of creating their own string. So, you tweak the requirements for strings submitted by the students.
Let us define a function F(s, t) where s and t are strings as the number of characters that are same in both the strings. Note that the position doesn't matter. Here are a few examples of F(s, t):
F("abc", "def") = 0
F("abc", "acb") = 3
F("back", "abcd") = 3
Now you ask your students to output a string t with lowercase unique characters of the same length as $s$, such that F(s, t) $\leq k$ where you are also given the value of $k$. If there are multiple such strings, you ask them to output the lexicographically smallest possible string. If no such string is possible, output the string "NOPE" without quotes.
-----Input:-----
- The first line will contain $T$, the number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, which contains a string $s$ and an integer $k$.
-----Output:-----
For each testcase, output in a single line the lexicographically smallest string t such that F(s, t) <= k or "NOPE" without quotes if no such string exists.
-----Constraints-----
- $1 \leq T \leq 10000$
- $1 \leq $length of string s $(|s|) \leq 26$
- $s$ only consists of characters $a$ to $z$
- There are no repeating characters in s
- $0 \leq k \leq |s|$
-----Sample Input:-----
4
helowrd 0
background 0
abcdefghijklmnopqrstuvwxyz 0
b 1
-----Sample Output:-----
abcfgij
efhijlmpqs
NOPE
a | t=int(input())
for _ in range(t):
#lol={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q' ,'r','s','t','u','v','w','x','y','z'}
s,k=input().split()
k=int(k)
n=len(s)
x=list(set(s))
final=''
for i in range(97,123):
if(chr(i) in x):
if(k>0):
final+=chr(i)
k-=1
else:
continue
else:
final+=chr(i)
if(len(s)<=len(final)):
print(final[:n])
else:
print('NOPE')
| t=int(input())
for _ in range(t):
#lol={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q' ,'r','s','t','u','v','w','x','y','z'}
s,k=input().split()
k=int(k)
n=len(s)
x=list(set(s))
final=''
for i in range(97,123):
if(chr(i) in x):
if(k>0):
final+=chr(i)
k-=1
else:
continue
else:
final+=chr(i)
if(len(s)<=len(final)):
print(final[:n])
else:
print('NOPE')
| train | APPS_structured |
In a special ranking system, each voter gives a rank from highest to lowest to all teams participated in the competition.
The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter.
Given an array of strings votes which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above.
Return a string of all teams sorted by the ranking system.
Example 1:
Input: votes = ["ABC","ACB","ABC","ACB","ACB"]
Output: "ACB"
Explanation: Team A was ranked first place by 5 voters. No other team was voted as first place so team A is the first team.
Team B was ranked second by 2 voters and was ranked third by 3 voters.
Team C was ranked second by 3 voters and was ranked third by 2 voters.
As most of the voters ranked C second, team C is the second team and team B is the third.
Example 2:
Input: votes = ["WXYZ","XYZW"]
Output: "XWYZ"
Explanation: X is the winner due to tie-breaking rule. X has same votes as W for the first position but X has one vote as second position while W doesn't have any votes as second position.
Example 3:
Input: votes = ["ZMNAGUEDSJYLBOPHRQICWFXTVK"]
Output: "ZMNAGUEDSJYLBOPHRQICWFXTVK"
Explanation: Only one voter so his votes are used for the ranking.
Example 4:
Input: votes = ["BCA","CAB","CBA","ABC","ACB","BAC"]
Output: "ABC"
Explanation:
Team A was ranked first by 2 voters, second by 2 voters and third by 2 voters.
Team B was ranked first by 2 voters, second by 2 voters and third by 2 voters.
Team C was ranked first by 2 voters, second by 2 voters and third by 2 voters.
There is a tie and we rank teams ascending by their IDs.
Example 5:
Input: votes = ["M","M","M","M"]
Output: "M"
Explanation: Only team M in the competition so it has the first rank.
Constraints:
1 <= votes.length <= 1000
1 <= votes[i].length <= 26
votes[i].length == votes[j].length for 0 <= i, j < votes.length.
votes[i][j] is an English upper-case letter.
All characters of votes[i] are unique.
All the characters that occur in votes[0] also occur in votes[j] where 1 <= j < votes.length. | class Solution:
def rankTeams(self, votes: List[str]) -> str:
'''
ABC
ACB
X 1 2 3
A 2 0 0
B 0 1 1
C 0 1 1
'''
mem = {}
for vote in votes:
for i in range(len(vote)):
team = vote[i]
if team not in mem:
mem[team] = [0 for _ in range(len(vote))]
mem[team][i] += 1
standings = []
for k, v in mem.items():
standings.append(tuple(v) + (-ord(k), k))
standings.sort(reverse=True)
res = [s[-1] for s in standings]
return ''.join(res) | class Solution:
def rankTeams(self, votes: List[str]) -> str:
'''
ABC
ACB
X 1 2 3
A 2 0 0
B 0 1 1
C 0 1 1
'''
mem = {}
for vote in votes:
for i in range(len(vote)):
team = vote[i]
if team not in mem:
mem[team] = [0 for _ in range(len(vote))]
mem[team][i] += 1
standings = []
for k, v in mem.items():
standings.append(tuple(v) + (-ord(k), k))
standings.sort(reverse=True)
res = [s[-1] for s in standings]
return ''.join(res) | train | APPS_structured |
**This Kata is intended as a small challenge for my students**
Create a function, called ``removeVowels`` (or ``remove_vowels``), that takes a string argument and returns that same string with all vowels removed (vowels are "a", "e", "i", "o", "u"). | REMOVE_VOWS = str.maketrans('','','aeiou')
def remove_vowels(s):
return s.translate(REMOVE_VOWS) | REMOVE_VOWS = str.maketrans('','','aeiou')
def remove_vowels(s):
return s.translate(REMOVE_VOWS) | train | APPS_structured |
Write a function called `sumIntervals`/`sum_intervals()` that accepts an array of intervals, and returns the sum of all the interval lengths. Overlapping intervals should only be counted once.
### Intervals
Intervals are represented by a pair of integers in the form of an array. The first value of the interval will always be less than the second value. Interval example: `[1, 5]` is an interval from 1 to 5. The length of this interval is 4.
### Overlapping Intervals
List containing overlapping intervals:
```
[
[1,4],
[7, 10],
[3, 5]
]
```
The sum of the lengths of these intervals is 7. Since [1, 4] and [3, 5] overlap, we can treat the interval as [1, 5], which has a length of 4.
### Examples:
```C#
// empty intervals
Intervals.SumIntervals(new (int, int)[]{ }); // => 0
Intervals.SumIntervals(new (int, int)[]{ (2, 2), (5, 5)}); // => 0
// disjoined intervals
Intervals.SumIntervals(new (int, int)[]{
(1, 2), (3, 5)
}); // => (2-1) + (5-3) = 3
// overlapping intervals
Intervals.SumIntervals(new (int, int)[]{
(1, 4), (3, 6), (2, 8)
}); // (1,8) => 7
``` | def sum_of_intervals(intervals):
list1=[]
for i in intervals:
for j in range(i[0],i[1]):
list1.append(j)
set1=set(list1)
return len(set1) | def sum_of_intervals(intervals):
list1=[]
for i in intervals:
for j in range(i[0],i[1]):
list1.append(j)
set1=set(list1)
return len(set1) | train | APPS_structured |
You want to build a standard house of cards, but you don't know how many cards you will need. Write a program which will count the minimal number of cards according to the number of floors you want to have. For example, if you want a one floor house, you will need 7 of them (two pairs of two cards on the base floor, one horizontal card and one pair to get the first floor). Here you can see which kind of house of cards I mean:
http://www.wikihow.com/Build-a-Tower-of-Cards
## Note about floors:
This kata uses the British numbering system for building floors. If you want your house of cards to have a first floor, it needs a ground floor and then a first floor above that.
### Details (Ruby & JavaScript & Python & R)
The input must be an integer greater than 0, for other input raise an error.
### Details (Haskell)
The input must be an integer greater than 0, for other input return `Nothing`. | def house_of_cards(floors):
if floors < 1: raise Exception()
return (floors + 1) * (3*floors + 4) // 2 | def house_of_cards(floors):
if floors < 1: raise Exception()
return (floors + 1) * (3*floors + 4) // 2 | train | APPS_structured |
Create a function taking a positive integer as its parameter and returning a string containing the Roman Numeral representation of that integer.
Modern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. In Roman numerals 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC. 2008 is written as 2000=MM, 8=VIII; or MMVIII. 1666 uses each Roman symbol in descending order: MDCLXVI.
Example:
```python
solution(1000) # should return 'M'
```
Help:
```
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1,000
```
Remember that there can't be more than 3 identical symbols in a row.
More about roman numerals - http://en.wikipedia.org/wiki/Roman_numerals | units = " I II III IV V VI VII VIII IX".split(" ")
tens = " X XX XXX XL L LX LXX LXXX XC".split(" ")
hundreds = " C CC CCC CD D DC DCC DCCC CM".split(" ")
thousands = " M MM MMM".split(" ")
def solution(n):
return thousands[n//1000] + hundreds[n%1000//100] + tens[n%100//10] + units[n%10] | units = " I II III IV V VI VII VIII IX".split(" ")
tens = " X XX XXX XL L LX LXX LXXX XC".split(" ")
hundreds = " C CC CCC CD D DC DCC DCCC CM".split(" ")
thousands = " M MM MMM".split(" ")
def solution(n):
return thousands[n//1000] + hundreds[n%1000//100] + tens[n%100//10] + units[n%10] | train | APPS_structured |
You are asked to write a simple cypher that rotates every character (in range [a-zA-Z], special chars will be ignored by the cipher) by 13 chars. As an addition to the original ROT13 cipher, this cypher will also cypher numerical digits ([0-9]) with 5 chars.
Example:
"The quick brown fox jumps over the 2 lazy dogs"
will be cyphered to:
"Gur dhvpx oebja sbk whzcf bire gur 7 ynml qbtf"
Your task is to write a ROT13.5 (ROT135) method that accepts a string and encrypts it.
Decrypting is performed by using the same method, but by passing the encrypted string again.
Note: when an empty string is passed, the result is also empty.
When passing your succesful algorithm, some random tests will also be applied. Have fun! | def ROT135(message):
first = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
trance = 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm5678901234'
return message.translate(str.maketrans(first, trance)) | def ROT135(message):
first = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
trance = 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm5678901234'
return message.translate(str.maketrans(first, trance)) | train | APPS_structured |
Complete the function which converts hex number (given as a string) to a decimal number. | hex_to_dec=lambda n: int(n, 16) | hex_to_dec=lambda n: int(n, 16) | train | APPS_structured |
Given a binary tree, return the vertical order traversal of its nodes values.
For each node at position (X, Y), its left and right children respectively will be at positions (X-1, Y-1) and (X+1, Y-1).
Running a vertical line from X = -infinity to X = +infinity, whenever the vertical line touches some nodes, we report the values of the nodes in order from top to bottom (decreasing Y coordinates).
If two nodes have the same position, then the value of the node that is reported first is the value that is smaller.
Return an list of non-empty reports in order of X coordinate. Every report will have a list of values of nodes.
Example 1:
Input: [3,9,20,null,null,15,7]
Output: [[9],[3,15],[20],[7]]
Explanation:
Without loss of generality, we can assume the root node is at position (0, 0):
Then, the node with value 9 occurs at position (-1, -1);
The nodes with values 3 and 15 occur at positions (0, 0) and (0, -2);
The node with value 20 occurs at position (1, -1);
The node with value 7 occurs at position (2, -2).
Example 2:
Input: [1,2,3,4,5,6,7]
Output: [[4],[2],[1,5,6],[3],[7]]
Explanation:
The node with value 5 and the node with value 6 have the same position according to the given scheme.
However, in the report "[1,5,6]", the node value of 5 comes first since 5 is smaller than 6.
Note:
The tree will have between 1 and 1000 nodes.
Each node's value will be between 0 and 1000. | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def verticalTraversal(self, root: TreeNode) -> List[List[int]]:
hmap = defaultdict(list)
x_min, x_max = 0, 0
queue = deque()
report = list()
if root:
queue.append((root, 0, 1))
else:
return report
while queue:
root, x, y = queue.popleft()
x_min = min(x, x_min)
x_max = max(x, x_max)
while y > len(hmap[x]):
hmap[x].append([])
hmap[x][-1].append(root.val)
if root.left:
queue.append((root.left, x - 1, y + 1))
if root.right:
queue.append((root.right, x + 1, y + 1))
print(hmap)
print(x_min, x_max)
for i in range(x_min, x_max + 1):
report.append([])
for l in hmap[i]:
print(l)
print(report)
if l:
l.sort()
report[-1].extend(l)
return report | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def verticalTraversal(self, root: TreeNode) -> List[List[int]]:
hmap = defaultdict(list)
x_min, x_max = 0, 0
queue = deque()
report = list()
if root:
queue.append((root, 0, 1))
else:
return report
while queue:
root, x, y = queue.popleft()
x_min = min(x, x_min)
x_max = max(x, x_max)
while y > len(hmap[x]):
hmap[x].append([])
hmap[x][-1].append(root.val)
if root.left:
queue.append((root.left, x - 1, y + 1))
if root.right:
queue.append((root.right, x + 1, y + 1))
print(hmap)
print(x_min, x_max)
for i in range(x_min, x_max + 1):
report.append([])
for l in hmap[i]:
print(l)
print(report)
if l:
l.sort()
report[-1].extend(l)
return report | train | APPS_structured |
Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string "aabccc" we replace "aa" by "a2" and replace "ccc" by "c3". Thus the compressed string becomes "a2bc3".
Notice that in this problem, we are not adding '1' after single characters.
Given a string s and an integer k. You need to delete at most k characters from s such that the run-length encoded version of s has minimum length.
Find the minimum length of the run-length encoded version of s after deleting at most k characters.
Example 1:
Input: s = "aaabcccd", k = 2
Output: 4
Explanation: Compressing s without deleting anything will give us "a3bc3d" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = "abcccd" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be "a3c3" of length 4.
Example 2:
Input: s = "aabbaa", k = 2
Output: 2
Explanation: If we delete both 'b' characters, the resulting compressed string would be "a4" of length 2.
Example 3:
Input: s = "aaaaaaaaaaa", k = 0
Output: 3
Explanation: Since k is zero, we cannot delete anything. The compressed string is "a11" of length 3.
Constraints:
1 <= s.length <= 100
0 <= k <= s.length
s contains only lowercase English letters. | class Solution:
def getLengthOfOptimalCompression(self, s: str, k: int) -> int:
@lru_cache(None)
def fuck(start,last,c,left):
if start >= len(s):
return 0
if left == 0:
return (1 if c==99 or c == 9 or c ==1 else 0) + fuck(start+1, last, c +1, left) if s[start]==last else 1 + fuck(start+1, s[start], 1, left)
return (1 if c==99 or c == 9 or c ==1 else 0) + fuck(start+1, last, c +1, left) if s[start]==last else min(fuck(start+1, last, c, left-1),1 + fuck(start+1, s[start], 1, left))
return fuck(0,'sb',0, k) | class Solution:
def getLengthOfOptimalCompression(self, s: str, k: int) -> int:
@lru_cache(None)
def fuck(start,last,c,left):
if start >= len(s):
return 0
if left == 0:
return (1 if c==99 or c == 9 or c ==1 else 0) + fuck(start+1, last, c +1, left) if s[start]==last else 1 + fuck(start+1, s[start], 1, left)
return (1 if c==99 or c == 9 or c ==1 else 0) + fuck(start+1, last, c +1, left) if s[start]==last else min(fuck(start+1, last, c, left-1),1 + fuck(start+1, s[start], 1, left))
return fuck(0,'sb',0, k) | train | APPS_structured |
Given the array arr of positive integers and the array queries where queries[i] = [Li, Ri], for each query i compute the XOR of elements from Li to Ri (that is, arr[Li] xor arr[Li+1] xor ... xor arr[Ri] ). Return an array containing the result for the given queries.
Example 1:
Input: arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]
Output: [2,7,14,8]
Explanation:
The binary representation of the elements in the array are:
1 = 0001
3 = 0011
4 = 0100
8 = 1000
The XOR values for queries are:
[0,1] = 1 xor 3 = 2
[1,2] = 3 xor 4 = 7
[0,3] = 1 xor 3 xor 4 xor 8 = 14
[3,3] = 8
Example 2:
Input: arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]
Output: [8,0,4,4]
Constraints:
1 <= arr.length <= 3 * 10^4
1 <= arr[i] <= 10^9
1 <= queries.length <= 3 * 10^4
queries[i].length == 2
0 <= queries[i][0] <= queries[i][1] < arr.length | class Solution:
def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:
n = len(arr)
out=[]
tree = [0]*(2*n)
for i in range(n):
tree[i+n] = arr[i]
for i in range(n-1,0,-1):
tree[i] = tree[i << 1]^tree[i << 1 | 1]
for q in queries:
res = 0
l = q[0]+n
r = q[1]+n+1
while l < r:
if l & 1:
res = res^tree[l]
l=l+1
if r & 1:
r=r-1
res = res^tree[r]
l>>=1
r>>=1
out.append(res)
return out | class Solution:
def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:
n = len(arr)
out=[]
tree = [0]*(2*n)
for i in range(n):
tree[i+n] = arr[i]
for i in range(n-1,0,-1):
tree[i] = tree[i << 1]^tree[i << 1 | 1]
for q in queries:
res = 0
l = q[0]+n
r = q[1]+n+1
while l < r:
if l & 1:
res = res^tree[l]
l=l+1
if r & 1:
r=r-1
res = res^tree[r]
l>>=1
r>>=1
out.append(res)
return out | train | APPS_structured |
Now that Chef has finished baking and frosting his cupcakes, it's time to package them. Chef has N cupcakes, and needs to decide how many cupcakes to place in each package. Each package must contain the same number of cupcakes. Chef will choose an integer A between 1 and N, inclusive, and place exactly A cupcakes into each package. Chef makes as many packages as possible. Chef then gets to eat the remaining cupcakes. Chef enjoys eating cupcakes very much. Help Chef choose the package size A that will let him eat as many cupcakes as possible.
-----Input-----
Input begins with an integer T, the number of test cases. Each test case consists of a single integer N, the number of cupcakes.
-----Output-----
For each test case, output the package size that will maximize the number of leftover cupcakes. If multiple package sizes will result in the same number of leftover cupcakes, print the largest such size.
-----Constraints-----
- 1 ≤ T ≤ 1000
- 2 ≤ N ≤ 100000000 (108)
-----Sample Input-----
2
2
5
-----Sample Output-----
2
3
-----Explanation-----
In the first test case, there will be no leftover cupcakes regardless of the size Chef chooses, so he chooses the largest possible size. In the second test case, there will be 2 leftover cupcakes. | for t in range(int(input())):
n=int(input())
print((n//2)+1)
| for t in range(int(input())):
n=int(input())
print((n//2)+1)
| train | APPS_structured |
Chef has $N$ dishes of different types arranged in a row: $A_1, A_2, \ldots, A_N$, where $A_i$ denotes the type of the $i^{th}$ dish. He wants to choose as many dishes as possible from the given list but while satisfying two conditions:
- He can choose only one type of dish.
- No two chosen dishes should be adjacent to each other.
Chef wants to know which type of dish he should choose from, so that he can pick the maximum number of dishes.
Example:
Given $N$=$9$ and $A$=$[1, 2, 2, 1, 2, 1, 1, 1, 1]$.
For type 1, Chef can choose at most four dishes. One of the ways to choose four dishes of type 1 is $A_1$, $A_4$, $A_7$ and $A_9$.
For type 2, Chef can choose at most two dishes. One way is to choose $A_3$ and $A_5$.
So in this case, Chef should go for type 1, in which he can pick more dishes.
-----Input:-----
- The first line contains $T$, the number of test cases. Then the test cases follow.
- For each test case, the first line contains a single integer $N$.
- The second line contains $N$ integers $A_1, A_2, \ldots, A_N$.
-----Output:-----
For each test case, print a single line containing one integer ― the type of the dish that Chef should choose from. If there are multiple answers, print the smallest one.
-----Constraints-----
- $1 \le T \le 10^3$
- $1 \le N \le 10^3$
- $1 \le A_i \le 10^3$
- Sum of $N$ over all test cases doesn't exceed $10^4$
-----Sample Input:-----
3
5
1 2 2 1 2
6
1 1 1 1 1 1
8
1 2 2 2 3 4 2 1
-----Sample Output:-----
1
1
2
-----Explanation:-----
Test case 1:
For both type 1 and type 2, Chef can pick at most two dishes. In the case of multiple answers, we pick the smallest one. Hence the answer will be $1$.
Test case 2:
There are only dishes of type 1. So the answer is $1$.
Test case 3:
For type 1, Chef can choose at most two dishes. For type 2, he can choose three dishes. For type 3 and type 4, Chef can choose the only dish available. Hence the maximum is in type 2 and so the answer is $2$. | for _ in range(int(input())):
n=int(input())
l=list(map(int,input().split()))
s=set(l)
for i in range(1,n):
if l[i]==l[i-1]:
l[i]=-1
# print(l)
m=0
sx=list(s)
sx.sort()
for i in sx:
x=l.count(i)
if m<x:
m=x
z=i
print(z) | for _ in range(int(input())):
n=int(input())
l=list(map(int,input().split()))
s=set(l)
for i in range(1,n):
if l[i]==l[i-1]:
l[i]=-1
# print(l)
m=0
sx=list(s)
sx.sort()
for i in sx:
x=l.count(i)
if m<x:
m=x
z=i
print(z) | train | APPS_structured |
Write a program that prints a chessboard with N rows and M columns with the following rules:
The top left cell must be an asterisk (*)
Any cell touching (left, right, up or down) a cell with an asterisk must be a dot (.)
Any cell touching (left, right, up or down) a cell with a dot must be an asterisk.
A chessboard of 8 rows and 8 columns printed using these rules would be:
```
*.*.*.*.
.*.*.*.*
*.*.*.*.
.*.*.*.*
*.*.*.*.
.*.*.*.*
*.*.*.*.
.*.*.*.*
```
Input
A single line with two integers N and M separated by space. The number N will represent the number of rows and M the number of columns.
Output
Return N lines each containing M characters with the chessboard pattern.
Empty string if N, M or both are 0.
From: 2016 AIPO National Finals
http://aipo.computing.dcu.ie/2016-aipo-national-finals-problems | def chessboard(s):m,n=map(int,s.split());return'\n'.join(('*.'*n)[i%2:n+i%2]for i in range(m)) | def chessboard(s):m,n=map(int,s.split());return'\n'.join(('*.'*n)[i%2:n+i%2]for i in range(m)) | train | APPS_structured |
Write a method `alternate_sq_sum()` (JS: `alternateSqSum` ) that takes an array of integers as input and finds the sum of squares of the elements at even positions (*i.e.,* 2nd, 4th, *etc.*) plus the sum of the rest of the elements at odd position.
NOTE:
The values at even *position* need to be squared. For a language with zero-based indices, this will occur at oddly-indexed locations. For instance, in Python, the values at indices 1, 3, 5, *etc.* should be squared because these are the second, fourth, and sixth positions in the list.
For Example:
```python
alternate_sq_sum([11, 12, 13, 14, 15]) #should return 379
```
Explanation:
Elements at indices 0, 2, 4 are 11, 13, 15 and they are at odd positions as 11 is at position #1, 13 is at position #3 and 15 at #5.
Elements at indices 1, 3 are 12 and 14 and they are at even position.
So we need to add 11, 13, 15 as they are and square of 12 and 14
--> 11 + 13 + 15 + 12^2 + 14^2
= 11 + 13 + 15 + 144 + 196
= 379
For empty arrays, result should be 0 (zero) (except for Haskell). | def alternate_sq_sum(arr):
return sum(num if not i%2 else num**2 for i,num in enumerate(arr)) | def alternate_sq_sum(arr):
return sum(num if not i%2 else num**2 for i,num in enumerate(arr)) | train | APPS_structured |
One player came to a casino and found a slot machine where everything depends only on how he plays. The rules follow.
A positive integer $a$ is initially on the screen. The player can put a coin into the machine and then add $1$ to or subtract $1$ from any two adjacent digits. All digits must remain from $0$ to $9$ after this operation, and the leading digit must not equal zero. In other words, it is forbidden to add $1$ to $9$, to subtract $1$ from $0$ and to subtract $1$ from the leading $1$. Once the number on the screen becomes equal to $b$, the player wins the jackpot. $a$ and $b$ have the same number of digits.
Help the player to determine the minimal number of coins he needs to spend in order to win the jackpot and tell how to play.
-----Input-----
The first line contains a single integer $n$ ($2 \le n \le 10^5$) standing for the length of numbers $a$ and $b$.
The next two lines contain numbers $a$ and $b$, each one on a separate line ($10^{n-1} \le a, b < 10^n$).
-----Output-----
If it is impossible to win the jackpot, print a single integer $-1$.
Otherwise, the first line must contain the minimal possible number $c$ of coins the player has to spend.
$\min(c, 10^5)$ lines should follow, $i$-th of them containing two integers $d_i$ and $s_i$ ($1\le d_i\le n - 1$, $s_i = \pm 1$) denoting that on the $i$-th step the player should add $s_i$ to the $d_i$-th and $(d_i + 1)$-st digits from the left (e. g. $d_i = 1$ means that two leading digits change while $d_i = n - 1$ means that there are two trailing digits which change).
Please notice that the answer may be very big and in case $c > 10^5$ you should print only the first $10^5$ moves. Your answer is considered correct if it is possible to finish your printed moves to win the jackpot in the minimal possible number of coins. In particular, if there are multiple ways to do this, you can output any of them.
-----Examples-----
Input
3
223
322
Output
2
1 1
2 -1
Input
2
20
42
Output
2
1 1
1 1
Input
2
35
44
Output
-1
-----Note-----
In the first example, we can make a +1 operation on the two first digits, transforming number $\textbf{22}3$ into $\textbf{33}3$, and then make a -1 operation on the last two digits, transforming $3\textbf{33}$ into $3\textbf{22}$.
It's also possible to do these operations in reverse order, which makes another correct answer.
In the last example, one can show that it's impossible to transform $35$ into $44$. | def main():
n = int(input())
a = list(map(int, (x for x in input())))
b = list(map(int, (x for x in input())))
x = [0] * (n - 1)
x[0] = b[0] - a[0]
for i in range(1, n - 1):
x[i] = b[i] - a[i] - x[i - 1]
if a[n - 1] + x[n - 2] != b[n - 1]:
print(-1)
return
cnt = sum(map(abs, x)) # prevbug: ftl
print(cnt)
cnt = min(cnt, 10 ** 5)
index = 0
def handle_zero_nine(cur_zero):
nonlocal cnt
nxt = index + 1
# cur_zero = True prevbug: preserved this line
while True:
if cur_zero and a[nxt + 1] != 9:
break
if not cur_zero and a[nxt + 1] != 0:
break
nxt += 1
cur_zero = not cur_zero
while nxt > index:
if cnt == 0:
break
if cur_zero:
print(nxt + 1, 1)
a[nxt] += 1
a[nxt + 1] += 1
else:
print(nxt + 1, -1)
a[nxt] -= 1
a[nxt + 1] -= 1
nxt -= 1
cnt -= 1
# print(a)
cur_zero = not cur_zero
while cnt > 0:
if a[index] == b[index]:
index += 1
continue
elif a[index] > b[index] and a[index + 1] == 0:
handle_zero_nine(True)
elif a[index] < b[index] and a[index + 1] == 9:
handle_zero_nine(False)
elif a[index] > b[index]:
print(index + 1, -1)
a[index] -= 1
a[index + 1] -= 1
cnt -= 1
# print(a)
elif a[index] < b[index]:
print(index + 1, 1)
a[index] += 1
a[index + 1] += 1
cnt -= 1
# print(a)
def __starting_point():
main()
__starting_point() | def main():
n = int(input())
a = list(map(int, (x for x in input())))
b = list(map(int, (x for x in input())))
x = [0] * (n - 1)
x[0] = b[0] - a[0]
for i in range(1, n - 1):
x[i] = b[i] - a[i] - x[i - 1]
if a[n - 1] + x[n - 2] != b[n - 1]:
print(-1)
return
cnt = sum(map(abs, x)) # prevbug: ftl
print(cnt)
cnt = min(cnt, 10 ** 5)
index = 0
def handle_zero_nine(cur_zero):
nonlocal cnt
nxt = index + 1
# cur_zero = True prevbug: preserved this line
while True:
if cur_zero and a[nxt + 1] != 9:
break
if not cur_zero and a[nxt + 1] != 0:
break
nxt += 1
cur_zero = not cur_zero
while nxt > index:
if cnt == 0:
break
if cur_zero:
print(nxt + 1, 1)
a[nxt] += 1
a[nxt + 1] += 1
else:
print(nxt + 1, -1)
a[nxt] -= 1
a[nxt + 1] -= 1
nxt -= 1
cnt -= 1
# print(a)
cur_zero = not cur_zero
while cnt > 0:
if a[index] == b[index]:
index += 1
continue
elif a[index] > b[index] and a[index + 1] == 0:
handle_zero_nine(True)
elif a[index] < b[index] and a[index + 1] == 9:
handle_zero_nine(False)
elif a[index] > b[index]:
print(index + 1, -1)
a[index] -= 1
a[index + 1] -= 1
cnt -= 1
# print(a)
elif a[index] < b[index]:
print(index + 1, 1)
a[index] += 1
a[index + 1] += 1
cnt -= 1
# print(a)
def __starting_point():
main()
__starting_point() | train | APPS_structured |
In this Kata, we define an arithmetic progression as a series of integers in which the differences between adjacent numbers are the same. You will be given an array of ints of `length > 2` and your task will be to convert it into an arithmetic progression by the following rule:
```Haskell
For each element there are exactly three options: an element can be decreased by 1, an element can be increased by 1
or it can be left unchanged.
```
Return the minimum number of changes needed to convert the array to an arithmetic progression. If not possible, return `-1`.
```Haskell
For example:
solve([1,1,3,5,6,5]) == 4 because [1,1,3,5,6,5] can be changed to [1,2,3,4,5,6] by making 4 changes.
solve([2,1,2]) == 1 because it can be changed to [2,2,2]
solve([1,2,3]) == 0 because it is already a progression, and no changes are needed.
solve([1,1,10) == -1 because it's impossible.
solve([5,6,5,3,1,1]) == 4. It becomes [6,5,4,3,2,1]
```
More examples in the test cases. Good luck! | def solve(ls):
result = [ls[each]-ls[each-1] for each in range(1, len(ls))]
gap = round(sum(result)/len(result))
tries = [ls[0]+1, ls[0], ls[0]-1]
answer = []
while True:
count = 0
copy_ls = ls[:]
copy_ls[0] = tries.pop(0)
if copy_ls[0] != ls[0]:
count += 1
for each in range(len(ls)-1):
sub_gap = copy_ls[each+1] - copy_ls[each]
if sub_gap < gap:
copy_ls[each+1] += 1
count += 1
elif sub_gap > gap:
copy_ls[each+1] -= 1
count += 1
result = [copy_ls[each]-copy_ls[each-1] for each in range(1, len(ls))]
if len(set(result)) == 1:
answer.append(count)
if len(tries) == 0:
if len(answer) == 0:
return -1
else:
answer.sort()
return answer[0] | def solve(ls):
result = [ls[each]-ls[each-1] for each in range(1, len(ls))]
gap = round(sum(result)/len(result))
tries = [ls[0]+1, ls[0], ls[0]-1]
answer = []
while True:
count = 0
copy_ls = ls[:]
copy_ls[0] = tries.pop(0)
if copy_ls[0] != ls[0]:
count += 1
for each in range(len(ls)-1):
sub_gap = copy_ls[each+1] - copy_ls[each]
if sub_gap < gap:
copy_ls[each+1] += 1
count += 1
elif sub_gap > gap:
copy_ls[each+1] -= 1
count += 1
result = [copy_ls[each]-copy_ls[each-1] for each in range(1, len(ls))]
if len(set(result)) == 1:
answer.append(count)
if len(tries) == 0:
if len(answer) == 0:
return -1
else:
answer.sort()
return answer[0] | train | APPS_structured |
Many websites use weighted averages of various polls to make projections for elections. They’re weighted based on a variety of factors, such as historical accuracy of the polling firm, sample size, as well as date(s). The weights, in this kata, are already calculated for you. All you need to do is convert a set of polls with weights, into a fixed projection for the result.
#### Task:
Your job is to convert an array of candidates (variable name `candidates`) and an array of polls (variable name `polls`), each poll with two parts, a result and a weight, into a guess of the result, with each value rounded to one decimal place, through use of a weighted average. Weights can be zero! Don't worry about the sum not totalling 100. The final result should be a hash in Ruby and Crystal, dictionary in Python, or object in JS in the format shown below:
```python
{
"": "",
"": "",
...
}
For your convenience, a function named round1 has been defined for you. You can
use it to round to the nearest tenth correctly (due to the inaccuracy of round
and floats in general).
```
_The input should not be modified._
#### Calculation for projections:
```
[(poll1 * weight1) + (poll2 * weight2) + ...] / (weight1 + weight2 + ...)
```
#### An example:
```python
candidates = ['A', 'B', 'C']
poll1res = [20, 30, 50]
poll1wt = 1
poll1 = [poll1res, poll1wt]
poll2res = [40, 40, 20]
poll2wt = 0.5
poll2 = [poll2res, poll2wt]
poll3res = [50, 40, 10]
poll3wt = 2
poll3 = [poll3res, poll3wt]
polls = [poll1, poll2, poll3]
predict(candidates, polls)
#=> {
'A': 40,
'B': 37.1,
'C': 22.9
}
# because...
candidate 'A' weighted average
= ((20 * 1) + (40 * 0.5) + (50 * 2)) / (1 + 0.5 + 2)
= (20 + 20 + 100) / 3.5
= 140 / 3.5
= 40
candidate 'B' weighted average
= ((30 * 1) + (40 * 0.5) + (40 * 2)) / (1 + 0.5 + 2)
= (30 + 20 + 80) / 3.5
= 130 / 3.5
= 37.142857...
≈ 37.1 (round to nearest tenth)
candidate 'C' weighted average
= ((50 * 1) + (20 * 0.5) + (10 * 2)) / (1 + 0.5 + 2)
= (50 + 10 + 20) / 3.5
= 80 / 3.5
= 22.857142...
≈ 22.9 (round to nearest tenth)
```
Also check out my other creations — [Keep the Order](https://www.codewars.com/kata/keep-the-order), [Naming Files](https://www.codewars.com/kata/naming-files), [Square and Cubic Factors](https://www.codewars.com/kata/square-and-cubic-factors), [Identify Case](https://www.codewars.com/kata/identify-case), [Split Without Loss](https://www.codewars.com/kata/split-without-loss), [Adding Fractions](https://www.codewars.com/kata/adding-fractions),
[Random Integers](https://www.codewars.com/kata/random-integers), [Implement String#transpose](https://www.codewars.com/kata/implement-string-number-transpose), [Implement Array#transpose!](https://www.codewars.com/kata/implement-array-number-transpose), [Arrays and Procs #1](https://www.codewars.com/kata/arrays-and-procs-number-1), and [Arrays and Procs #2](https://www.codewars.com/kata/arrays-and-procs-number-2).
If you notice any issues or have any suggestions/comments whatsoever, please don't hesitate to mark an issue or just comment. Thanks! | from operator import itemgetter
from numpy import average
def predict(candidates, polls):
votes = zip(*map(itemgetter(0), polls))
weights = list(map(itemgetter(1), polls))
return {x:round1(average(next(votes), weights=weights)) for x in candidates} | from operator import itemgetter
from numpy import average
def predict(candidates, polls):
votes = zip(*map(itemgetter(0), polls))
weights = list(map(itemgetter(1), polls))
return {x:round1(average(next(votes), weights=weights)) for x in candidates} | train | APPS_structured |
In the wake of the npm's `left-pad` debacle, you decide to write a new super padding method that superceds the functionality of `left-pad`. Your version will provide the same functionality, but will additionally add right, and justified padding of string -- the `super_pad`.
Your function `super_pad` should take three arguments: the string `string`, the width of the final string `width`, and a fill character `fill`. However, the fill character can be enriched with a format string resulting in different padding strategies. If `fill` begins with `'<'` the string is padded on the left with the remaining fill string and if `fill` begins with `'>'` the string is padded on the right. Finally, if `fill` begins with `'^'` the string is padded on the left and the right, where the left padding is always greater or equal to the right padding. The `fill` string can contain more than a single char, of course.
Some examples to clarify the inner workings:
- `super_pad("test", 10)` returns " test"
- `super_pad("test", 10, "x")` returns `"xxxxxxtest"`
- `super_pad("test", 10, "xO")` returns `"xOxOxOtest"`
- `super_pad("test", 10, "xO-")` returns `"xO-xO-test"`
- `super_pad("some other test", 10, "nope")` returns `"other test"`
- `super_pad("some other test", 10, "> ")` returns `"some other"`
- `super_pad("test", 7, ">nope")` returns `"testnop"`
- `super_pad("test", 7, "^more complex")` returns `"motestm"`
- `super_pad("test", 7, "")` returns `"test"`
The `super_pad` method always returns a string of length `width` if possible. We expect the `width` to be positive (including 0) and the fill could be also an empty string. | from itertools import chain, islice, cycle
padding = lambda fill, size: islice(cycle(fill), size)
def super_pad(string, width, fill=" "):
if not width: return ''
if not fill: return string[:width]
size = width - len(string)
if size <= 0: return string[:width] if fill[0] in '>^' else string[-width:]
if fill[0] == '>': return string + ''.join(padding(fill[1:], size))
if fill[0] == '^': return ''.join(padding(fill[1:], (size + 1) >> 1)) + string + ''.join(padding(fill[1:], size >> 1))
if fill[0] == '<': fill = fill[1:]
return ''.join(padding(fill, size)) + string | from itertools import chain, islice, cycle
padding = lambda fill, size: islice(cycle(fill), size)
def super_pad(string, width, fill=" "):
if not width: return ''
if not fill: return string[:width]
size = width - len(string)
if size <= 0: return string[:width] if fill[0] in '>^' else string[-width:]
if fill[0] == '>': return string + ''.join(padding(fill[1:], size))
if fill[0] == '^': return ''.join(padding(fill[1:], (size + 1) >> 1)) + string + ''.join(padding(fill[1:], size >> 1))
if fill[0] == '<': fill = fill[1:]
return ''.join(padding(fill, size)) + string | train | APPS_structured |
Given a number $n$, give the last digit of sum of all the prime numbers from 1 to $n$ inclusive.
-----Input:-----
- First line contains number of testcase $t$.
- Each testcase contains of a single line of input, number $n$.
-----Output:-----
Last digit of sum of every prime number till n.
-----Constraints-----
- $1 \leq T \leq 10$
- $2 \leq N \leq 10^6$
-----Sample Input:-----
1
10
-----Sample Output:-----
7 |
def sumOfPrimes(n):
prime = [True] * (n + 1)
p = 2
while p * p <= n:
if prime[p] == True:
i = p * 2
while i <= n:
prime[i] = False
i += p
p += 1
sum = 0
for i in range (2, n + 1):
if(prime[i]):
sum += i
return sum
for _ in range(int(input())):
n = int(input())
zzz = str(sumOfPrimes(n))
print(zzz[-1]) |
def sumOfPrimes(n):
prime = [True] * (n + 1)
p = 2
while p * p <= n:
if prime[p] == True:
i = p * 2
while i <= n:
prime[i] = False
i += p
p += 1
sum = 0
for i in range (2, n + 1):
if(prime[i]):
sum += i
return sum
for _ in range(int(input())):
n = int(input())
zzz = str(sumOfPrimes(n))
print(zzz[-1]) | train | APPS_structured |
Write a function to check whether an input string is a valid IPv4 address or IPv6 address or neither.
IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots ("."), e.g.,172.16.254.1;
Besides, leading zeros in the IPv4 is invalid. For example, the address 172.16.254.01 is invalid.
IPv6 addresses are represented as eight groups of four hexadecimal digits, each group representing 16 bits. The groups are separated by colons (":"). For example, the address 2001:0db8:85a3:0000:0000:8a2e:0370:7334 is a valid one. Also, we could omit some leading zeros among four hexadecimal digits and some low-case characters in the address to upper-case ones, so 2001:db8:85a3:0:0:8A2E:0370:7334 is also a valid IPv6 address(Omit leading zeros and using upper cases).
However, we don't replace a consecutive group of zero value with a single empty group using two consecutive colons (::) to pursue simplicity. For example, 2001:0db8:85a3::8A2E:0370:7334 is an invalid IPv6 address.
Besides, extra leading zeros in the IPv6 is also invalid. For example, the address 02001:0db8:85a3:0000:0000:8a2e:0370:7334 is invalid.
Note:
You may assume there is no extra space or special characters in the input string.
Example 1:
Input: "172.16.254.1"
Output: "IPv4"
Explanation: This is a valid IPv4 address, return "IPv4".
Example 2:
Input: "2001:0db8:85a3:0:0:8A2E:0370:7334"
Output: "IPv6"
Explanation: This is a valid IPv6 address, return "IPv6".
Example 3:
Input: "256.256.256.256"
Output: "Neither"
Explanation: This is neither a IPv4 address nor a IPv6 address. | class Solution:
def validIPAddress(self, IP):
"""
:type IP: str
:rtype: str
"""
def is_hex(hexs):
hex_set = set('0123456789abcdefABCDEF')
return set(hexs)<hex_set
result = 'Neither'
if '.' in IP:
sub_str = IP.split('.')
if len(sub_str)!=4:
return result
result = 'IPv4'
elif ':' in IP:
sub_str = IP.split(':')
if len(sub_str) != 8:
return result
result = 'IPv6'
else:
return result
for sub in sub_str:
if result == 'IPv4':
if not sub.isdigit():
result = 'Neither'
break
if len(str(int(sub)))!=len(sub) or int(sub)>255:
result = 'Neither'
break
if result == 'IPv6':
if len(sub)>4 or len(sub)==0 or not is_hex(sub):
result = 'Neither'
break
return result
| class Solution:
def validIPAddress(self, IP):
"""
:type IP: str
:rtype: str
"""
def is_hex(hexs):
hex_set = set('0123456789abcdefABCDEF')
return set(hexs)<hex_set
result = 'Neither'
if '.' in IP:
sub_str = IP.split('.')
if len(sub_str)!=4:
return result
result = 'IPv4'
elif ':' in IP:
sub_str = IP.split(':')
if len(sub_str) != 8:
return result
result = 'IPv6'
else:
return result
for sub in sub_str:
if result == 'IPv4':
if not sub.isdigit():
result = 'Neither'
break
if len(str(int(sub)))!=len(sub) or int(sub)>255:
result = 'Neither'
break
if result == 'IPv6':
if len(sub)>4 or len(sub)==0 or not is_hex(sub):
result = 'Neither'
break
return result
| train | APPS_structured |
In this kata, we will check is an array is (hyper)rectangular.
A rectangular array is an N-dimensional array with fixed sized within one dimension. Its sizes can be repsented like A1xA2xA3...xAN. That means a N-dimensional array has N sizes. The 'As' are the hyperrectangular properties of an array.
You should implement a functions that returns a N-tuple with the arrays hyperrectangular properties or None if the array is not hyperrectangular.
```
hyperrectangularity_properties(arr)
```
## Note
An empty array IS rectagular and has one dimension of length 0
```
hyperrectangularity_properties([]) == (0,)
```
## Example
```
1D array
hyperrectangularity_properties([1,2,3]) == (3,)
2D arrays
hyperrectangularity_properties(
[[0,1,2],
[3,4,5],
[6,7,8]] ) == (3,3)
hyperrectangularity_properties(
[[0,1,2],
[3,4,5]] ) == (2,3)
hyperrectangularity_properties(
[[0,1,2],
[3,4] ] ) == None
3D arrays
hyperrectangularity_properties(
[
[ [0], [2] ],
[ [0], [2] ],
[ [0], [2] ]
] ) == (3,2,1)
hyperrectangularity_properties(
[
[[0],[2]],
[[0],[2,2]],
[[0],[2]]
] ) == None
hyperrectangularity_properties(
[[ [], [], [] ]]
) == (1,3,0)
```
### Heterogeneous Arrays can appear too
```
hyperrectangularity_properties(
[[0,1,2],
3,
[[4],5,6]] ) == None
hyperrectangularity_properties(
[1,
[1,2],
[[3],[4,[5]],[6]]
] ) == None
hyperrectangularity_properties(
[[ [], [] ], [] ]
) == None
hyperrectangularity_properties(
[ 1, [], [2, [3]] ]
) == None
```
The first property shows the length of the outer layer. The second of the layer one step deeper and so on. The function should handle higher dimensions too.
## Input
##### N-dimensional array of integers
## Expected Ouput
##### An N-tuple with the hyperrectangularity properties | def hp(arr):
if not isinstance(arr, list):
return ()
elif not arr:
return (0,)
xs = list(map(hp, arr))
if None not in xs and all(x == xs[0] for x in xs):
return (len(arr),) + xs[0]
hyperrectangularity_properties = hp | def hp(arr):
if not isinstance(arr, list):
return ()
elif not arr:
return (0,)
xs = list(map(hp, arr))
if None not in xs and all(x == xs[0] for x in xs):
return (len(arr),) + xs[0]
hyperrectangularity_properties = hp | train | APPS_structured |
Chef and Abhishek both are fighting for the post of Chairperson to be part of ACE committee and are trying their best. To select only one student their teacher gave them a binary string (string consisting of only 0's and 1's) and asked them to find number of sub-strings present in the given string that satisfy the following condition:
The substring should start with 0 and end with 1 or the substring should start with 1 and end with 0 but not start with 0 and end with 0 and start with 1 and end with 1.
More formally, strings such as 100,0101 are allowed since they start and end with different characters. But strings such as 0110,1101 are not allowed because they start and end with same characters.
Both Chef and Abhishek try their best to solve it but couldn't do it. You being a very good friend of Chef, he asks for your help so that he can solve it and become the Chairperson.
-----Input:-----
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N denoting the length of the string.
The second line of each test case contains a binary string of length N.
-----Output:-----
For each test case, print a single line containing one integer ― the number of sub strings satisfying above conditions.
-----Constraints-----
- $1 \leq T \leq 1000$
- $2 \leq N \leq 10^9$
Binary string consist's only 0 and 1.
-----Sample Input:-----
1
4
1010
-----Sample Output:-----
4
-----EXPLANATION:-----
All possible substring are : { (1),(0),(1),(0),(10),(01),(10),(101),(010),(1010) }. Out of these only 4 substrings {(10),(01),(10),(1010)} start and end with different characters. Hence the answer 4. | for t in range(int(input())):
def csbstr(str,n,a,b):
tot,c=0,0
for i in range(n):
if(str[i]==a):
c+=1
if(str[i]==b):
tot+=c
return tot
n=int(input())
str=input()
count1=csbstr(str,n,"1","0")
count2=csbstr(str,n,"0","1")
print(count1+count2) | for t in range(int(input())):
def csbstr(str,n,a,b):
tot,c=0,0
for i in range(n):
if(str[i]==a):
c+=1
if(str[i]==b):
tot+=c
return tot
n=int(input())
str=input()
count1=csbstr(str,n,"1","0")
count2=csbstr(str,n,"0","1")
print(count1+count2) | train | APPS_structured |
Consider the following series:
`0,1,2,3,4,5,6,7,8,9,10,22,11,20,13,24...`There is nothing special between numbers `0` and `10`.
Let's start with the number `10` and derive the sequence. `10` has digits `1` and `0`. The next possible number that does not have a `1` or a `0` is `22`. All other numbers between `10` and `22` have a `1` or a `0`.
From `22`, the next number that does not have a `2` is `11`. Note that `30` is also a possibility because it is the next *higher* number that does not have a `2`, but we must select the *lowest* number that fits and **is not already in the sequence**.
From `11`, the next lowest number that does not have a `1` is `20`.
From `20`, the next lowest number that does not have a `2` or a `0` is `13`, then `24` , then `15` and so on.
Once a number appers in the series, it cannot appear again.
You will be given an index number and your task will be return the element at that position. See test cases for more examples.
Note that the test range is `n <= 500`.
Good luck!
If you like this Kata, please try:
[Sequence convergence](https://www.codewars.com/kata/59971e64bfccc70748000068)
[https://www.codewars.com/kata/unique-digit-sequence-ii-optimization-problem](https://www.codewars.com/kata/unique-digit-sequence-ii-optimization-problem) | M = [0]
while len(M) <= 500:
k, s = 0, {c for c in str(M[-1])}
while k in M or {c for c in str(k)} & s:
k += 1
M.append(k)
find_num = lambda n: M[n] | M = [0]
while len(M) <= 500:
k, s = 0, {c for c in str(M[-1])}
while k in M or {c for c in str(k)} & s:
k += 1
M.append(k)
find_num = lambda n: M[n] | train | APPS_structured |
**Steps**
1. Square the numbers that are greater than zero.
2. Multiply by 3 every third number.
3. Multiply by -1 every fifth number.
4. Return the sum of the sequence.
**Example**
`{ -2, -1, 0, 1, 2 }` returns `-6`
```
1. { -2, -1, 0, 1 * 1, 2 * 2 }
2. { -2, -1, 0 * 3, 1, 4 }
3. { -2, -1, 0, 1, -1 * 4 }
4. -6
```
P.S.: The sequence consists only of integers. And try not to use "for", "while" or "loop" statements. | def calc(a):
return sum(i**(1,2)[i>0]*(1,3)[idx%3==2]*(1,-1)[idx%5==4] for idx,i in enumerate(a)) | def calc(a):
return sum(i**(1,2)[i>0]*(1,3)[idx%3==2]*(1,-1)[idx%5==4] for idx,i in enumerate(a)) | train | APPS_structured |
Today a plane was hijacked by a maniac. All the passengers of the flight are taken as hostage. Chef is also one of them.
He invited one of the passengers to play a game with him. If he loses the game, he will release all the passengers, otherwise he will kill all of them. A high risk affair it is.
Chef volunteered for this tough task. He was blindfolded by Hijacker. Hijacker brought a big black bag from his pockets. The contents of the bag is not visible. He tells Chef that the bag contains R red, G green and B blue colored balloons.
Hijacker now asked Chef to take out some balloons from the box such that there are at least K balloons of the same color and hand him over. If the taken out balloons does not contain at least K balloons of the same color, then the hijacker will shoot everybody. Chef is very scared and wants to leave this game as soon as possible, so he will draw the minimum number of balloons so as to save the passengers. Can you please help scared Chef to find out the minimum number of balloons he should take out.
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a three space-separated integers R, G and B.
The second line contains only one integer K.
-----Output-----
For each test case, output a single line containing one integer - the minimum number of balloons Chef need to take out from the bag.
-----Constraints-----
- 1 ≤ T ≤ 1000
- 1 ≤ R, G, B ≤ 109
- 1 ≤ K ≤ max{R, G, B}
-----Subtasks-----
- Subtask 1 (44 points): 1 ≤ R, G, B ≤ 10
- Subtask 2 (56 points): No additional constraints
-----Example-----
Input:
2
3 3 3
1
3 3 3
2
Output:
1
4
-----Explanation-----
Example case 2. In the worst-case scenario first three balloons will be of the three different colors and only after fourth balloon Chef will have two balloons of the same color. So, Chef might need to fetch 4 balloons | T = eval(input())
for _ in range(T):
col = sorted(map(int, input().split()))
k = eval(input())
ans = min(col[0], k-1) + min(col[1], k-1) + min(col[2], k-1) + 1
print(ans) | T = eval(input())
for _ in range(T):
col = sorted(map(int, input().split()))
k = eval(input())
ans = min(col[0], k-1) + min(col[1], k-1) + min(col[2], k-1) + 1
print(ans) | train | APPS_structured |
It's your Birthday. Your colleagues buy you a cake. The numbers of candles on the cake is provided (x). Please note this is not reality, and your age can be anywhere up to 1,000. Yes, you would look a mess.
As a surprise, your colleagues have arranged for your friend to hide inside the cake and burst out. They pretend this is for your benefit, but likely it is just because they want to see you fall over covered in cake. Sounds fun!
When your friend jumps out of the cake, he/she will knock some of the candles to the floor. If the number of candles that fall is higher than 70% of total candles (x), the carpet will catch fire.
You will work out the number of candles that will fall from the provided string (y). You must add up the character ASCII code of each even indexed (assume a 0 based indexing) character in y, with the alphabetical position of each odd indexed character in y to give the string a total.
example: 'abc' --> a=97, b=2, c=99 --> y total = 198.
If the carpet catches fire, return 'Fire!', if not, return 'That was close!'. | def cake(candles,debris):
total = 0
for i,x in enumerate(list(debris)):
total += ord(x)-(96 if i%2==1 else 0)
return 'That was close!' if candles*0.7>total or candles==0 else 'Fire!'
| def cake(candles,debris):
total = 0
for i,x in enumerate(list(debris)):
total += ord(x)-(96 if i%2==1 else 0)
return 'That was close!' if candles*0.7>total or candles==0 else 'Fire!'
| train | APPS_structured |
Iahub likes trees very much. Recently he discovered an interesting tree named propagating tree. The tree consists of n nodes numbered from 1 to n, each node i having an initial value a_{i}. The root of the tree is node 1.
This tree has a special property: when a value val is added to a value of node i, the value -val is added to values of all the children of node i. Note that when you add value -val to a child of node i, you also add -(-val) to all children of the child of node i and so on. Look an example explanation to understand better how it works.
This tree supports two types of queries:
"1 x val" — val is added to the value of node x; "2 x" — print the current value of node x.
In order to help Iahub understand the tree better, you must answer m queries of the preceding type.
-----Input-----
The first line contains two integers n and m (1 ≤ n, m ≤ 200000). The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 1000). Each of the next n–1 lines contains two integers v_{i} and u_{i} (1 ≤ v_{i}, u_{i} ≤ n), meaning that there is an edge between nodes v_{i} and u_{i}.
Each of the next m lines contains a query in the format described above. It is guaranteed that the following constraints hold for all queries: 1 ≤ x ≤ n, 1 ≤ val ≤ 1000.
-----Output-----
For each query of type two (print the value of node x) you must print the answer to the query on a separate line. The queries must be answered in the order given in the input.
-----Examples-----
Input
5 5
1 2 1 1 2
1 2
1 3
2 4
2 5
1 2 3
1 1 2
2 1
2 2
2 4
Output
3
3
0
-----Note-----
The values of the nodes are [1, 2, 1, 1, 2] at the beginning.
Then value 3 is added to node 2. It propagates and value -3 is added to it's sons, node 4 and node 5. Then it cannot propagate any more. So the values of the nodes are [1, 5, 1, - 2, - 1].
Then value 2 is added to node 1. It propagates and value -2 is added to it's sons, node 2 and node 3. From node 2 it propagates again, adding value 2 to it's sons, node 4 and node 5. Node 3 has no sons, so it cannot propagate from there. The values of the nodes are [3, 3, - 1, 0, 1].
You can see all the definitions about the tree at the following link: http://en.wikipedia.org/wiki/Tree_(graph_theory) | class BIT():
"""区間加算、一点取得クエリをそれぞれO(logN)で応えるデータ構造を構築する
add: 区間[begin, end)にvalを加える
get_val: i番目(0-indexed)の値を求める
"""
def __init__(self, n):
self.n = n
self.bit = [0] * (n + 1)
def get_val(self, i):
i = i + 1
s = 0
while i <= self.n:
s += self.bit[i]
i += i & -i
return s
def _add(self, i, val):
while i > 0:
self.bit[i] += val
i -= i & -i
def add(self, i, j, val):
self._add(j, val)
self._add(i, -val)
from collections import deque
import sys
input = sys.stdin.readline
def eular_tour(tree: list, root: int):
"""頂点に対するオイラーツアーを行う
posの部分木に区間[begin[pos], end[pos])が対応する
"""
n = len(tree)
res = []
begin = [-1] * n
end = [-1] * n
visited = [False] * n
visited[root] = True
q = deque([root])
while q:
pos = q.pop()
res.append(pos)
end[pos] = len(res)
if begin[pos] == -1:
begin[pos] = len(res) - 1
for next_pos in tree[pos]:
if visited[next_pos]:
continue
else:
visited[next_pos] = True
q.append(pos)
q.append(next_pos)
return res, begin, end
n, q = map(int, input().split())
init_cost = list(map(int, input().split()))
info = [list(map(int, input().split())) for i in range(n-1)]
query = [list(map(int, input().split())) for i in range(q)]
tree = [[] for i in range(n)]
for i in range(n-1):
a, b = info[i]
a -= 1
b -= 1
tree[a].append(b)
tree[b].append(a)
res, begin, end = eular_tour(tree, 0)
even_res = []
odd_res = []
for i in range(len(res)):
if i % 2 == 0:
even_res.append(res[i])
else:
odd_res.append(res[i])
even_bit = BIT(len(even_res))
odd_bit = BIT(len(odd_res))
for i in range(q):
if query[i][0] == 1:
_, pos, cost = query[i]
pos -= 1
if begin[pos] % 2 == 0:
even_bit.add(begin[pos] // 2, (end[pos] + 1) // 2, cost)
odd_bit.add(begin[pos] // 2, end[pos] // 2, -cost)
else:
odd_bit.add(begin[pos] // 2, end[pos] // 2, cost)
even_bit.add((begin[pos] + 1) // 2, end[pos] // 2, -cost)
else:
_, pos = query[i]
pos -= 1
if begin[pos] % 2 == 0:
ans = even_bit.get_val(begin[pos] // 2)
else:
ans = odd_bit.get_val(begin[pos] // 2)
print(ans + init_cost[pos]) | class BIT():
"""区間加算、一点取得クエリをそれぞれO(logN)で応えるデータ構造を構築する
add: 区間[begin, end)にvalを加える
get_val: i番目(0-indexed)の値を求める
"""
def __init__(self, n):
self.n = n
self.bit = [0] * (n + 1)
def get_val(self, i):
i = i + 1
s = 0
while i <= self.n:
s += self.bit[i]
i += i & -i
return s
def _add(self, i, val):
while i > 0:
self.bit[i] += val
i -= i & -i
def add(self, i, j, val):
self._add(j, val)
self._add(i, -val)
from collections import deque
import sys
input = sys.stdin.readline
def eular_tour(tree: list, root: int):
"""頂点に対するオイラーツアーを行う
posの部分木に区間[begin[pos], end[pos])が対応する
"""
n = len(tree)
res = []
begin = [-1] * n
end = [-1] * n
visited = [False] * n
visited[root] = True
q = deque([root])
while q:
pos = q.pop()
res.append(pos)
end[pos] = len(res)
if begin[pos] == -1:
begin[pos] = len(res) - 1
for next_pos in tree[pos]:
if visited[next_pos]:
continue
else:
visited[next_pos] = True
q.append(pos)
q.append(next_pos)
return res, begin, end
n, q = map(int, input().split())
init_cost = list(map(int, input().split()))
info = [list(map(int, input().split())) for i in range(n-1)]
query = [list(map(int, input().split())) for i in range(q)]
tree = [[] for i in range(n)]
for i in range(n-1):
a, b = info[i]
a -= 1
b -= 1
tree[a].append(b)
tree[b].append(a)
res, begin, end = eular_tour(tree, 0)
even_res = []
odd_res = []
for i in range(len(res)):
if i % 2 == 0:
even_res.append(res[i])
else:
odd_res.append(res[i])
even_bit = BIT(len(even_res))
odd_bit = BIT(len(odd_res))
for i in range(q):
if query[i][0] == 1:
_, pos, cost = query[i]
pos -= 1
if begin[pos] % 2 == 0:
even_bit.add(begin[pos] // 2, (end[pos] + 1) // 2, cost)
odd_bit.add(begin[pos] // 2, end[pos] // 2, -cost)
else:
odd_bit.add(begin[pos] // 2, end[pos] // 2, cost)
even_bit.add((begin[pos] + 1) // 2, end[pos] // 2, -cost)
else:
_, pos = query[i]
pos -= 1
if begin[pos] % 2 == 0:
ans = even_bit.get_val(begin[pos] // 2)
else:
ans = odd_bit.get_val(begin[pos] // 2)
print(ans + init_cost[pos]) | train | APPS_structured |
*** Nova polynomial subtract***
This kata is from a series on polynomial handling. ( [#1](http://www.codewars.com/kata/nova-polynomial-1-add-1) [#2](http://www.codewars.com/kata/570eb07e127ad107270005fe) [#3](http://www.codewars.com/kata/5714041e8807940ff3001140 ) [#4](http://www.codewars.com/kata/571a2e2df24bdfd4e20001f5))
Consider a polynomial in a list where each element in the list element corresponds to the factors. The factor order is the position in the list. The first element is the zero order factor (the constant).
p = [a0, a1, a2, a3] signifies the polynomial a0 + a1x + a2x^2 + a3*x^3
In this kata subtract two polynomials:
```python
poly_subtract([1, 2], [1] ) = [0, 2]
poly_subtract([2, 4], [4, 5] ) = [-2, -1]
```
The first and second katas of this series are preloaded in the code and can be used:
* [poly_add](http://www.codewars.com/kata/nova-polynomial-1-add-1)
* [poly_multiply](http://www.codewars.com/kata/570eb07e127ad107270005fe). | from itertools import zip_longest
def poly_subtract(a, b):
return [x - y for x, y in zip_longest(a, b, fillvalue=0)] | from itertools import zip_longest
def poly_subtract(a, b):
return [x - y for x, y in zip_longest(a, b, fillvalue=0)] | train | APPS_structured |
_A mad sociopath scientist just came out with a brilliant invention! He extracted his own memories to forget all the people he hates! Now there's a lot of information in there, so he needs your talent as a developer to automatize that task for him._
> You are given the memories as a string containing people's surname and name (comma separated). The scientist marked one occurrence of each of the people he hates by putting a '!' right before their name.
**Your task is to destroy all the occurrences of the marked people.
One more thing ! Hate is contagious, so you also need to erase any memory of the person that comes after any marked name!**
---
Examples
---
---
Input:
```
"Albert Einstein, !Sarah Connor, Marilyn Monroe, Abraham Lincoln, Sarah Connor, Sean Connery, Marilyn Monroe, Bjarne Stroustrup, Manson Marilyn, Monroe Mary"
```
Output:
```
"Albert Einstein, Abraham Lincoln, Sean Connery, Bjarne Stroustrup, Manson Marilyn, Monroe Mary"
```
=> We must remove every memories of Sarah Connor because she's marked, but as a side-effect we must also remove all the memories about Marilyn Monroe that comes right after her! Note that we can't destroy the memories of Manson Marilyn or Monroe Mary, so be careful! | def select(memory):
lst = memory.split(', ')
bad = {who.strip('!') for prev,who in zip(['']+lst,lst+['']) if who.startswith('!') or prev.startswith('!')}
return ', '.join(who for who in map(lambda s: s.strip('!'), lst) if who not in bad) | def select(memory):
lst = memory.split(', ')
bad = {who.strip('!') for prev,who in zip(['']+lst,lst+['']) if who.startswith('!') or prev.startswith('!')}
return ', '.join(who for who in map(lambda s: s.strip('!'), lst) if who not in bad) | train | APPS_structured |
A product-sum number is a natural number N which can be expressed as both the product and the sum of the same set of numbers.
N = a1 × a2 × ... × ak = a1 + a2 + ... + ak
For example, 6 = 1 × 2 × 3 = 1 + 2 + 3.
For a given set of size, k, we shall call the smallest N with this property a minimal product-sum number. The minimal product-sum numbers for sets of size, k = 2, 3, 4, 5, and 6 are as follows.
```
k=2: 4 = 2 × 2 = 2 + 2
k=3: 6 = 1 × 2 × 3 = 1 + 2 + 3
k=4: 8 = 1 × 1 × 2 × 4 = 1 + 1 + 2 + 4
k=5: 8 = 1 × 1 × 2 × 2 × 2 = 1 + 1 + 2 + 2 + 2
k=6: 12 = 1 × 1 × 1 × 1 × 2 × 6 = 1 + 1 + 1 + 1 + 2 + 6
```
Hence for 2 ≤ k ≤ 6, the sum of all the minimal product-sum numbers is 4+6+8+12 = 30; note that 8 is only counted once in the sum.
Your task is to write an algorithm to compute the sum of all minimal product-sum numbers where 2 ≤ k ≤ n.
Courtesy of ProjectEuler.net | maxi = 12001
res = [2*maxi]*maxi
def rec(p, s, c, x):
k = p - s + c
if k >= maxi: return
res[k] = min(p, res[k])
[rec(p*i, s+i, c+1, i) for i in range(x, 2*maxi//p + 1)]
rec(1, 1, 1, 2)
def productsum(n):
return sum(set(res[2:n+1])) | maxi = 12001
res = [2*maxi]*maxi
def rec(p, s, c, x):
k = p - s + c
if k >= maxi: return
res[k] = min(p, res[k])
[rec(p*i, s+i, c+1, i) for i in range(x, 2*maxi//p + 1)]
rec(1, 1, 1, 2)
def productsum(n):
return sum(set(res[2:n+1])) | train | APPS_structured |
# Task
Imagine `n` horizontal lines and `m` vertical lines.
Some of these lines intersect, creating rectangles.
How many rectangles are there?
# Examples
For `n=2, m=2,` the result should be `1`.
there is only one 1x1 rectangle.
For `n=2, m=3`, the result should be `3`.
there are two 1x1 rectangles and one 1x2 rectangle. So `2 + 1 = 3`.
For n=3, m=3, the result should be `9`.
there are four 1x1 rectangles, two 1x2 rectangles, two 2x1 rectangles and one 2x2 rectangle. So `4 + 2 + 2 + 1 = 9`.
# Input & Output
- `[input]` integer `n`
Number of horizontal lines.
Constraints: `0 <= n <= 100`
- `[input]` integer `m`
Number of vertical lines.
Constraints: `0 <= m <= 100`
- `[output]` an integer
Number of rectangles. | def rectangles(n, m):
return n*m*(n-1)*(m-1)//4 | def rectangles(n, m):
return n*m*(n-1)*(m-1)//4 | train | APPS_structured |
Three Best Friends $AMAN$ , $AKBAR$ , $ANTHONY$ are planning to go to “GOA” , but just like every other goa trip plan there is a problem to their plan too.
Their parents will only give permission if they can solve this problem for them
They are a given a number N and they have to calculate the total number of triplets (x ,y ,z)
Satisfying the given condition y * x +z=n.
For ex if N=3
Then there exist 3 triplets( x ,y ,z): (1,1,2) , (1,2,1) , (2,1,1) which satisfy the condition
Help the group to get permission for the trip
-----Input:-----
- First line will contain the number $N$.
-----Output:-----
the possible number of triplets satisfying the given condition
-----Constraints-----
- $2 \leq N \leq 10^6$
-----Sample Input:-----
3
-----Sample Output:-----
3
-----EXPLANATION:-----
there exist 3 triplets ( x ,y ,z): (1,1,2) , (1,2,1) , (2,1,1) which satisfy the condition | N = int(input())
r = range(1, N + 1)
count = 0
for i in r:
for j in r:
if i * j >= N: break
count += 1
print(count) | N = int(input())
r = range(1, N + 1)
count = 0
for i in r:
for j in r:
if i * j >= N: break
count += 1
print(count) | train | APPS_structured |
# Task
Changu and Mangu are great buddies. Once they found an infinite paper which had 1,2,3,4,5,6,7,8,......... till infinity, written on it.
Both of them did not like the sequence and started deleting some numbers in the following way.
```
First they deleted every 2nd number.
So remaining numbers on the paper: 1,3,5,7,9,11..........till infinity.
Then they deleted every 3rd number.
So remaining numbers on the paper: 1,3,7,9,13,15..........till infinity..
Then they deleted every 4th number.
So remaining numbers on the paper: 1,3,7,13,15..........till infinity.```
Then kept on doing this (deleting every 5th, then every 6th ...) untill they got old and died.
It is obvious that some of the numbers will never get deleted(E.g. 1,3,7,13..) and hence are know to us as survivor numbers.
Given a number `n`, check whether its a survivor number or not.
# Input/Output
- `[input]` integer `n`
`0 < n <= 10^8`
- `[output]` a boolean value
`true` if the number is a survivor else `false`. | def survivor(n):
i=2
while i<=n:
if n%i==0:return False
n-=n//i
i+=1
return True | def survivor(n):
i=2
while i<=n:
if n%i==0:return False
n-=n//i
i+=1
return True | train | APPS_structured |
Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems.
The boy has found an online judge with tasks divided by topics they cover. He has picked $p^{k_i}$ problems from $i$-th category ($p$ is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced.
Formally, given $n$ numbers $p^{k_i}$, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo $10^{9}+7$.
-----Input-----
Input consists of multiple test cases. The first line contains one integer $t$ $(1 \leq t \leq 10^5)$ — the number of test cases. Each test case is described as follows:
The first line contains two integers $n$ and $p$ $(1 \leq n, p \leq 10^6)$. The second line contains $n$ integers $k_i$ $(0 \leq k_i \leq 10^6)$.
The sum of $n$ over all test cases doesn't exceed $10^6$.
-----Output-----
Output one integer — the reminder of division the answer by $1\,000\,000\,007$.
-----Example-----
Input
4
5 2
2 3 4 4 3
3 1
2 10 1000
4 5
0 1 1 100
1 8
89
Output
4
1
146981438
747093407
-----Note-----
You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to $2$, but there is also a distribution where the difference is $10^9 + 8$, then the answer is $2$, not $1$.
In the first test case of the example, there're the following numbers: $4$, $8$, $16$, $16$, and $8$. We can divide them into such two sets: ${4, 8, 16}$ and ${8, 16}$. Then the difference between the sums of numbers in sets would be $4$. | import sys
readline = sys.stdin.readline
T = int(readline())
Ans = [None]*T
MOD = 10**9+7
mod = 10**9+9
for qu in range(T):
N, P = map(int, readline().split())
A = list(map(int, readline().split()))
if P == 1:
if N&1:
Ans[qu] = 1
else:
Ans[qu] = 0
continue
if N == 1:
Ans[qu] = pow(P, A[0], MOD)
continue
A.sort(reverse = True)
cans = 0
carry = 0
res = 0
ra = 0
for a in A:
if carry == 0:
carry = pow(P, a, mod)
cans = pow(P, a, MOD)
continue
res = (res + pow(P, a, mod))%mod
ra = (ra + pow(P, a, MOD))%MOD
if res == carry and ra == cans:
carry = 0
cans = 0
ra = 0
res = 0
Ans[qu] = (cans-ra)%MOD
print('\n'.join(map(str, Ans))) | import sys
readline = sys.stdin.readline
T = int(readline())
Ans = [None]*T
MOD = 10**9+7
mod = 10**9+9
for qu in range(T):
N, P = map(int, readline().split())
A = list(map(int, readline().split()))
if P == 1:
if N&1:
Ans[qu] = 1
else:
Ans[qu] = 0
continue
if N == 1:
Ans[qu] = pow(P, A[0], MOD)
continue
A.sort(reverse = True)
cans = 0
carry = 0
res = 0
ra = 0
for a in A:
if carry == 0:
carry = pow(P, a, mod)
cans = pow(P, a, MOD)
continue
res = (res + pow(P, a, mod))%mod
ra = (ra + pow(P, a, MOD))%MOD
if res == carry and ra == cans:
carry = 0
cans = 0
ra = 0
res = 0
Ans[qu] = (cans-ra)%MOD
print('\n'.join(map(str, Ans))) | train | APPS_structured |
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem.
Allen's future parking lot can be represented as a rectangle with $4$ rows and $n$ ($n \le 50$) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having $k$ ($k \le 2n$) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places.
[Image] Illustration to the first example.
However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space.
Allen knows he will be a very busy man, and will only have time to move cars at most $20000$ times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.
-----Input-----
The first line of the input contains two space-separated integers $n$ and $k$ ($1 \le n \le 50$, $1 \le k \le 2n$), representing the number of columns and the number of cars, respectively.
The next four lines will contain $n$ integers each between $0$ and $k$ inclusive, representing the initial state of the parking lot. The rows are numbered $1$ to $4$ from top to bottom and the columns are numbered $1$ to $n$ from left to right.
In the first and last line, an integer $1 \le x \le k$ represents a parking spot assigned to car $x$ (you can only move this car to this place), while the integer $0$ represents a empty space (you can't move any car to this place).
In the second and third line, an integer $1 \le x \le k$ represents initial position of car $x$, while the integer $0$ represents an empty space (you can move any car to this place).
Each $x$ between $1$ and $k$ appears exactly once in the second and third line, and exactly once in the first and fourth line.
-----Output-----
If there is a sequence of moves that brings all of the cars to their parking spaces, with at most $20000$ car moves, then print $m$, the number of moves, on the first line. On the following $m$ lines, print the moves (one move per line) in the format $i$ $r$ $c$, which corresponds to Allen moving car $i$ to the neighboring space at row $r$ and column $c$.
If it is not possible for Allen to move all the cars to the correct spaces with at most $20000$ car moves, print a single line with the integer $-1$.
-----Examples-----
Input
4 5
1 2 0 4
1 2 0 4
5 0 0 3
0 5 0 3
Output
6
1 1 1
2 1 2
4 1 4
3 4 4
5 3 2
5 4 2
Input
1 2
1
2
1
2
Output
-1
Input
1 2
1
1
2
2
Output
2
1 1 1
2 4 1
-----Note-----
In the first sample test case, all cars are in front of their spots except car $5$, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most $20000$ will be accepted.
In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible. | n,k=list(map(int,input().split()))
m=[]
c=0
for i in range(4):
m.append(list(map(int,input().split())))
res=[]
for i in range(n):
if m[1][i] != 0:
if m[1][i] == m[0][i]:
res.append([m[1][i],1,i+1])
m[1][i] = 0
k-=1
for i in range(n):
if m[2][i] != 0:
if m[2][i] == m[3][i]:
res.append([m[2][i],4,i+1])
m[2][i] = 0
k-=1
if k >= n*2:
print(-1)
return
if True:
while True:
c+=1
for i in range(n):
if m[1][i] != 0:
if i != 0:
if m[1][i-1] == 0:
res.append([m[1][i],2,i])
m[1][i-1] = m[1][i]
m[1][i] = 0
if m[0][i-1] == m[1][i-1]:
res.append([m[1][i-1],1,i])
m[0][i-1] = m[1][i-1]
m[1][i-1] = 0
k-=1
elif i == 0:
if m[2][i] == 0:
res.append([m[1][i],3,i+1])
m[2][i] = m[1][i]
m[1][i] = 0
if m[3][i] == m[2][i]:
res.append([m[2][i],4,i+1])
m[3][i] = m[2][i]
m[2][i] = 0
k-=1
for i in range(n):
if m[2][i] != 0:
if i != n-1:
if m[2][i+1] == 0:
res.append([m[2][i],3,i+2])
m[2][i+1] = m[2][i]
m[2][i] = 0
if m[3][i+1] == m[2][i+1]:
res.append([m[2][i+1],4,i+2])
m[3][i+1] = m[2][i+1]
m[2][i+1] = 0
k-=1
else:
if m[1][i] == 0:
res.append([m[2][i],2,i+1])
m[1][i] = m[2][i]
m[2][i] = 0
if m[0][i] == m[1][i]:
res.append([m[1][i],1,i+1])
m[0][i] = m[1][i]
m[1][i] = 0
k-=1
if k <= 0:
break
else:
print(-1)
return
print(len(res))
for i in res:
print(*i)
| n,k=list(map(int,input().split()))
m=[]
c=0
for i in range(4):
m.append(list(map(int,input().split())))
res=[]
for i in range(n):
if m[1][i] != 0:
if m[1][i] == m[0][i]:
res.append([m[1][i],1,i+1])
m[1][i] = 0
k-=1
for i in range(n):
if m[2][i] != 0:
if m[2][i] == m[3][i]:
res.append([m[2][i],4,i+1])
m[2][i] = 0
k-=1
if k >= n*2:
print(-1)
return
if True:
while True:
c+=1
for i in range(n):
if m[1][i] != 0:
if i != 0:
if m[1][i-1] == 0:
res.append([m[1][i],2,i])
m[1][i-1] = m[1][i]
m[1][i] = 0
if m[0][i-1] == m[1][i-1]:
res.append([m[1][i-1],1,i])
m[0][i-1] = m[1][i-1]
m[1][i-1] = 0
k-=1
elif i == 0:
if m[2][i] == 0:
res.append([m[1][i],3,i+1])
m[2][i] = m[1][i]
m[1][i] = 0
if m[3][i] == m[2][i]:
res.append([m[2][i],4,i+1])
m[3][i] = m[2][i]
m[2][i] = 0
k-=1
for i in range(n):
if m[2][i] != 0:
if i != n-1:
if m[2][i+1] == 0:
res.append([m[2][i],3,i+2])
m[2][i+1] = m[2][i]
m[2][i] = 0
if m[3][i+1] == m[2][i+1]:
res.append([m[2][i+1],4,i+2])
m[3][i+1] = m[2][i+1]
m[2][i+1] = 0
k-=1
else:
if m[1][i] == 0:
res.append([m[2][i],2,i+1])
m[1][i] = m[2][i]
m[2][i] = 0
if m[0][i] == m[1][i]:
res.append([m[1][i],1,i+1])
m[0][i] = m[1][i]
m[1][i] = 0
k-=1
if k <= 0:
break
else:
print(-1)
return
print(len(res))
for i in res:
print(*i)
| train | APPS_structured |
Write a function that checks the braces status in a string, and return `True` if all braces are properly closed, or `False` otherwise. Available types of brackets: `()`, `[]`, `{}`.
**Please note, you need to write this function without using regex!**
## Examples
```python
'([[some](){text}here]...)' => True
'{([])}' => True
'()[]{}()' => True
'(...[]...{(..())}[abc]())' => True
'1239(df){' => False
'[()])' => False
')12[x]34(' => False
```
Don't forget to rate this kata! Thanks :) | parens = dict([')(', '][', '}{'])
opens = set(parens.values())
def braces_status(s):
stack = []
for c in s:
if c in opens:
stack.append(c)
elif c in parens:
if not (stack and stack.pop() == parens[c]):
return False
return not stack | parens = dict([')(', '][', '}{'])
opens = set(parens.values())
def braces_status(s):
stack = []
for c in s:
if c in opens:
stack.append(c)
elif c in parens:
if not (stack and stack.pop() == parens[c]):
return False
return not stack | train | APPS_structured |
Blob is a computer science student. He recently got an internship from Chef's enterprise. Along with the programming he has various other skills too like graphic designing, digital marketing and social media management. Looking at his skills Chef has provided him different tasks A[1…N] which have their own scores. Blog wants to maximize the value of the expression A[d]-A[c]+A[b]-A[a] such that d>c>b>a.
Can you help him in this?
-----Input:-----
- The first line contain the integer N
- The second line contains N space separated integers representing A[1], A[2] … A[N]
-----Output:-----
The maximum score that is possible
-----Constraints-----
- $4 \leq N \leq 10^4$
- $0 \leq A[i] \leq 10^5$
-----Sample Input:-----
6
3 9 10 1 30 40
-----Sample Output:-----
46 | def maxval(arr):
fn = [float('-inf')]*(len(arr)+1)
sn = [float('-inf')]*len(arr)
tn = [float('-inf')]*(len(arr)-1)
fon = [float('-inf')]*(len(arr)-2)
for i in reversed(list(range(len(arr)))):
fn[i] = max(fn[i + 1], arr[i])
for i in reversed(list(range(len(arr) - 1))):
sn[i] = max(sn[i + 1], fn[i + 1] - arr[i])
for i in reversed(list(range(len(arr) - 2))):
tn[i] = max(tn[i + 1], sn[i + 1] + arr[i])
for i in reversed(list(range(len(arr) - 3))):
fon[i] = max(fon[i + 1], tn[i + 1] - arr[i])
return fon[0]
n = int(input())
arr = list(map(int,input().split()))
print(maxval(arr))
| def maxval(arr):
fn = [float('-inf')]*(len(arr)+1)
sn = [float('-inf')]*len(arr)
tn = [float('-inf')]*(len(arr)-1)
fon = [float('-inf')]*(len(arr)-2)
for i in reversed(list(range(len(arr)))):
fn[i] = max(fn[i + 1], arr[i])
for i in reversed(list(range(len(arr) - 1))):
sn[i] = max(sn[i + 1], fn[i + 1] - arr[i])
for i in reversed(list(range(len(arr) - 2))):
tn[i] = max(tn[i + 1], sn[i + 1] + arr[i])
for i in reversed(list(range(len(arr) - 3))):
fon[i] = max(fon[i + 1], tn[i + 1] - arr[i])
return fon[0]
n = int(input())
arr = list(map(int,input().split()))
print(maxval(arr))
| train | APPS_structured |
Given an array of integers nums, you start with an initial positive value startValue.
In each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right).
Return the minimum positive value of startValue such that the step by step sum is never less than 1.
Example 1:
Input: nums = [-3,2,-3,4,2]
Output: 5
Explanation: If you choose startValue = 4, in the third iteration your step by step sum is less than 1.
step by step sum
startValue = 4 | startValue = 5 | nums
(4 -3 ) = 1 | (5 -3 ) = 2 | -3
(1 +2 ) = 3 | (2 +2 ) = 4 | 2
(3 -3 ) = 0 | (4 -3 ) = 1 | -3
(0 +4 ) = 4 | (1 +4 ) = 5 | 4
(4 +2 ) = 6 | (5 +2 ) = 7 | 2
Example 2:
Input: nums = [1,2]
Output: 1
Explanation: Minimum start value should be positive.
Example 3:
Input: nums = [1,-2,-3]
Output: 5
Constraints:
1 <= nums.length <= 100
-100 <= nums[i] <= 100 | class Solution:
def minStartValue(self, nums: List[int]) -> int:
running_min = nums[0]
reduction = 0
for i in nums:
reduction += i
running_min = min(running_min, reduction)
return 1 if running_min >= 1 else 1 - running_min | class Solution:
def minStartValue(self, nums: List[int]) -> int:
running_min = nums[0]
reduction = 0
for i in nums:
reduction += i
running_min = min(running_min, reduction)
return 1 if running_min >= 1 else 1 - running_min | train | APPS_structured |
Given an array A of strings, find any smallest string that contains each string in A as a substring.
We may assume that no string in A is substring of another string in A.
Example 1:
Input: ["alex","loves","leetcode"]
Output: "alexlovesleetcode"
Explanation: All permutations of "alex","loves","leetcode" would also be accepted.
Example 2:
Input: ["catg","ctaagt","gcta","ttca","atgcatc"]
Output: "gctaagttcatgcatc"
Note:
1 <= A.length <= 12
1 <= A[i].length <= 20 | class Solution:
# https://www.youtube.com/watch?v=u_Wc4jwrp3Q
# time: O(n^2 * 2 ^ n), space(n * 2 ^ n)
def shortestSuperstring(self, A: List[str]) -> str:
# add string t in the end of string s. cost = # of chars can't be merged.
def mergecost(s, t):
c = len(t)
for i in range(1, min(len(s), len(t))):
if s[len(s) - i:] == t[0:i]:
c = len(t) - i
return c
n = len(A)
cost = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
for j in range(i + 1, n):
cost[i][j] = mergecost(A[i], A[j])
cost[j][i] = mergecost(A[j], A[i])
dp = [[float('inf') for _ in range(n)] for _ in range(1 << n)]
parent = [[-1 for _ in range(n)] for _ in range(1 << n)]
for i in range(n):
dp[1 << i][i] = len(A[i])
for s in range(1, 1 << n):
for i in range(n):
# s doesn't contain index i.
if not (s & (1 << i)):
continue
# connect i to prev set.
prev = s - (1 << i)
for j in range(n):
if dp[s][i] > dp[prev][j] + cost[j][i]:
dp[s][i] = dp[prev][j] + cost[j][i]
parent[s][i] = j
minCost, end = float('inf'), 0
for i in range(n):
if dp[-1][i] < minCost:
minCost = dp[-1][i]
end = i
# the state that all nodes are visited.
s = (1 << n) - 1
res = ''
while s:
prev = parent[s][end]
if prev < 0:
return A[end] + res
res = A[end][len(A[end]) - cost[prev][end]:] + res
s &= ~(1 << end)
end = prev
return res
| class Solution:
# https://www.youtube.com/watch?v=u_Wc4jwrp3Q
# time: O(n^2 * 2 ^ n), space(n * 2 ^ n)
def shortestSuperstring(self, A: List[str]) -> str:
# add string t in the end of string s. cost = # of chars can't be merged.
def mergecost(s, t):
c = len(t)
for i in range(1, min(len(s), len(t))):
if s[len(s) - i:] == t[0:i]:
c = len(t) - i
return c
n = len(A)
cost = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
for j in range(i + 1, n):
cost[i][j] = mergecost(A[i], A[j])
cost[j][i] = mergecost(A[j], A[i])
dp = [[float('inf') for _ in range(n)] for _ in range(1 << n)]
parent = [[-1 for _ in range(n)] for _ in range(1 << n)]
for i in range(n):
dp[1 << i][i] = len(A[i])
for s in range(1, 1 << n):
for i in range(n):
# s doesn't contain index i.
if not (s & (1 << i)):
continue
# connect i to prev set.
prev = s - (1 << i)
for j in range(n):
if dp[s][i] > dp[prev][j] + cost[j][i]:
dp[s][i] = dp[prev][j] + cost[j][i]
parent[s][i] = j
minCost, end = float('inf'), 0
for i in range(n):
if dp[-1][i] < minCost:
minCost = dp[-1][i]
end = i
# the state that all nodes are visited.
s = (1 << n) - 1
res = ''
while s:
prev = parent[s][end]
if prev < 0:
return A[end] + res
res = A[end][len(A[end]) - cost[prev][end]:] + res
s &= ~(1 << end)
end = prev
return res
| train | APPS_structured |
Two words rhyme if their last 3 letters are a match. Given N words, print the test case number (of the format Case : num) followed by the rhyming words in separate line adjacent to each other.
The output can be in anyorder.
-----Input-----
First line contains the number of test case T
The next line contains the number of words N
Next N words follow . They’ll contain only alphabets from ‘a’-‘z’.
-----Output-----
Print case number (for each test case) of the format Case : num followed by the words that rhyme in a new line.
-----Constraints-----
1 <= T <= 5
1 <= N <= 1000
3 <= length of each word <= 1000
-----Example-----
Input:
3
3
nope qwerty hope
5
brain drain request grain nest
4
these words dont rhyme
Output:
Case : 1
hope nope
qwerty
Case : 2
brain drain grain
nest request
Case : 3
these
dont
words
rhyme
-----Explanation-----
Case : 2
brain drain grain
nest request
Case : 3
these
dont
words
rhyme
Explanation for case 1: since hope and nope rhyme (suffix “ope” matches), we print them in the same line and qwerty In a new line.
Note that
qwerty
nope hope
is also correct (the output can be in any order ) | t = int(input())
for i in range(t):
n = int(input())
suffixes = {}
xx = input().split()
for x in range(n):
try:
a = suffixes[xx[x][-3:]]
except Exception as e:
a = []
a.append(xx[x])
suffixes.update({xx[x][-3:]: a})
print("Case : %d" % (i + 1))
for a in sorted(suffixes):
print("".join(b + " " for b in sorted(suffixes[a])).strip()) | t = int(input())
for i in range(t):
n = int(input())
suffixes = {}
xx = input().split()
for x in range(n):
try:
a = suffixes[xx[x][-3:]]
except Exception as e:
a = []
a.append(xx[x])
suffixes.update({xx[x][-3:]: a})
print("Case : %d" % (i + 1))
for a in sorted(suffixes):
print("".join(b + " " for b in sorted(suffixes[a])).strip()) | train | APPS_structured |
Given an encoded string, return it's decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].
Examples:
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef". | class Solution:
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
m = len(s)
if m == 0:
return ''
result = []
for i in s:
if i != ']':
result.append(i)
else:
char_temp = []
r1m = len(result)
for j in range(r1m-1, -1, -1):
if result[j] != '[':
char_temp.insert(0, result.pop())
else:
result.pop()
break
digit_char = []
r2m = len(result)
for j in range(r2m-1, -1, -1):
if result[j].isdigit():
digit_char.insert(0, result.pop())
else:
break
result += char_temp*(int(''.join(digit_char)))
return ''.join(result)
| class Solution:
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
m = len(s)
if m == 0:
return ''
result = []
for i in s:
if i != ']':
result.append(i)
else:
char_temp = []
r1m = len(result)
for j in range(r1m-1, -1, -1):
if result[j] != '[':
char_temp.insert(0, result.pop())
else:
result.pop()
break
digit_char = []
r2m = len(result)
for j in range(r2m-1, -1, -1):
if result[j].isdigit():
digit_char.insert(0, result.pop())
else:
break
result += char_temp*(int(''.join(digit_char)))
return ''.join(result)
| train | APPS_structured |
=====Function Descriptions=====
zeros
The zeros tool returns a new array with a given shape and type filled with 0's.
import numpy
print numpy.zeros((1,2)) #Default type is float
#Output : [[ 0. 0.]]
print numpy.zeros((1,2), dtype = numpy.int) #Type changes to int
#Output : [[0 0]]
ones
The ones tool returns a new array with a given shape and type filled with 1's.
import numpy
print numpy.ones((1,2)) #Default type is float
#Output : [[ 1. 1.]]
print numpy.ones((1,2), dtype = numpy.int) #Type changes to int
#Output : [[1 1]]
=====Problem Statement=====
You are given the shape of the array in the form of space-separated integers, each integer representing the size of different dimensions, your task is to print an array of the given shape and integer type using the tools numpy.zeros and numpy.ones.
=====Input Format=====
A single line containing the space-separated integers.
=====Constraints=====
1≤each integer≤3
=====Output Format=====
First, print the array using the numpy.zeros tool and then print the array with the numpy.ones tool. | import numpy
dims = [int(x) for x in input().strip().split()]
print(numpy.zeros(tuple(dims), dtype = numpy.int))
print(numpy.ones(tuple(dims), dtype = numpy.int)) | import numpy
dims = [int(x) for x in input().strip().split()]
print(numpy.zeros(tuple(dims), dtype = numpy.int))
print(numpy.ones(tuple(dims), dtype = numpy.int)) | train | APPS_structured |
You are required to create a simple calculator that returns the result of addition, subtraction, multiplication or division of two numbers.
Your function will accept three arguments:
The first and second argument should be numbers.
The third argument should represent a sign indicating the operation to perform on these two numbers.
```if-not:csharp
if the variables are not numbers or the sign does not belong to the list above a message "unknown value" must be returned.
```
```if:csharp
If the sign is not a valid sign, throw an ArgumentException.
```
# Example:
```python
calculator(1, 2, '+') => 3
calculator(1, 2, '$') # result will be "unknown value"
```
Good luck! | def calculator(x,y,op):
if type(x) != int or type(y) != int:
return('unknown value')
elif op == '/':
return(x/y)
elif op == '*':
return(x*y)
elif op == '-':
return(x-y)
elif op == '+':
return(x+y)
else:
return('unknown value')
pass | def calculator(x,y,op):
if type(x) != int or type(y) != int:
return('unknown value')
elif op == '/':
return(x/y)
elif op == '*':
return(x*y)
elif op == '-':
return(x-y)
elif op == '+':
return(x+y)
else:
return('unknown value')
pass | train | APPS_structured |
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Note:
You may assume the interval's end point is always bigger than its start point.
Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other.
Example 1:
Input: [ [1,2], [2,3], [3,4], [1,3] ]
Output: 1
Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
Example 2:
Input: [ [1,2], [1,2], [1,2] ]
Output: 2
Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.
Example 3:
Input: [ [1,2], [2,3] ]
Output: 0
Explanation: You don't need to remove any of the intervals since they're already non-overlapping. | # Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution:
def eraseOverlapIntervals(self, intervals):
"""
:type intervals: List[Interval]
:rtype: int
"""
start_end={}
for i in intervals:
if i.start in start_end:
if start_end[i.start]>i.end:
start_end[i.start]=i.end
else:
start_end[i.start]=i.end
final_list={}
if len(start_end)>1:
sorted_list=sorted(start_end)
for i,j in enumerate(sorted_list):
if i>0:
start2=j
#if j>-90 and j<-80:
# print(start1,end1,start2,start_end[start2])
if start2<end1:
if start_end[start2]<end1:
final_list.pop(start1,None)
end2=start_end[start2]
final_list[start2]=end2
end1=end2
start1=start2
#if j>-90 and j<-80:
# print(start1,end1)
elif end1<=start_end[start2]:
final_list[start1]=end1
end1=end1
start1=start1
#if j>-90 and j<-80:
# print(start1,end1)
elif start2>=end1:
final_list[start1]=end1
start1=start2
end1=start_end[start2]
if i==len(sorted_list)-1:
final_list[start2]=start_end[start2]
if i==0:
start1=j
end1 =start_end[j]
elif len(start_end)==1:
final_list=start_end
print(list((i,start_end[i]) for i in sorted(start_end)))
print('result')
print(list((i,final_list[i]) for i in sorted(final_list)))
return len(intervals)-len(final_list)
| # Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution:
def eraseOverlapIntervals(self, intervals):
"""
:type intervals: List[Interval]
:rtype: int
"""
start_end={}
for i in intervals:
if i.start in start_end:
if start_end[i.start]>i.end:
start_end[i.start]=i.end
else:
start_end[i.start]=i.end
final_list={}
if len(start_end)>1:
sorted_list=sorted(start_end)
for i,j in enumerate(sorted_list):
if i>0:
start2=j
#if j>-90 and j<-80:
# print(start1,end1,start2,start_end[start2])
if start2<end1:
if start_end[start2]<end1:
final_list.pop(start1,None)
end2=start_end[start2]
final_list[start2]=end2
end1=end2
start1=start2
#if j>-90 and j<-80:
# print(start1,end1)
elif end1<=start_end[start2]:
final_list[start1]=end1
end1=end1
start1=start1
#if j>-90 and j<-80:
# print(start1,end1)
elif start2>=end1:
final_list[start1]=end1
start1=start2
end1=start_end[start2]
if i==len(sorted_list)-1:
final_list[start2]=start_end[start2]
if i==0:
start1=j
end1 =start_end[j]
elif len(start_end)==1:
final_list=start_end
print(list((i,start_end[i]) for i in sorted(start_end)))
print('result')
print(list((i,final_list[i]) for i in sorted(final_list)))
return len(intervals)-len(final_list)
| train | APPS_structured |
Mothers arranged a dance party for the children in school. At that party, there are only mothers and their children. All are having great fun on the dance floor when suddenly all the lights went out. It's a dark night and no one can see each other. But you were flying nearby and you can see in the dark and have ability to teleport people anywhere you want.
Legend:
-Uppercase letters stands for mothers, lowercase stand for their children, i.e. "A" mother's children are "aaaa".
-Function input: String contains only letters, uppercase letters are unique.
Task:
Place all people in alphabetical order where Mothers are followed by their children, i.e. "aAbaBb" => "AaaBbb". | def find_children(db):
return ''.join(sorted(db, key = lambda a: (a.upper(), a))) | def find_children(db):
return ''.join(sorted(db, key = lambda a: (a.upper(), a))) | train | APPS_structured |
A manufacturing project consists of exactly $K$ tasks. The board overviewing the project wants to hire $K$ teams of workers — one for each task. All teams begin working simultaneously.
Obviously, there must be at least one person in each team. For a team of $A$ workers, it takes exactly $A$ days to complete the task they are hired for. Each team acts independently, unaware of the status of other teams (whether they have completed their tasks or not), and submits their result for approval on the $A$-th day.
However, the board approves the project only if all $K$ teams complete their tasks on the same day — it rejects everything submitted on any other day. The day after a team finds out that its result was rejected, it resumes work on the same task afresh. Therefore, as long as a team of $A$ workers keeps getting rejected, it submits a new result of their task for approval on the $A$-th, $2A$-th, $3A$-th day etc.
The board wants to hire workers in such a way that it takes exactly $X$ days to complete the project. Find the smallest number of workers it needs to hire.
-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains two space-separated integers $K$ and $X$.
-----Output-----
For each test case, print a single line containing one integer — the smallest required number of workers.
-----Constraints-----
- $1 \le T \le 40$
- $2 \le K, X \le 10^6$
-----Example Input-----
2
2 3
2 6
-----Example Output-----
4
5
-----Explanation-----
Example case 1: We can hire a team of $3$ workers for task $1$ and $1$ worker for task $2$. The one-man team working on task $2$ completes it and submits the result for approval on each day, but it is rejected on the first and second day. On the third day, the team working on task $1$ also completes their task, so the project gets approved after exactly $3$ days.
Example case 2: We can hire a team of $3$ workers for task $1$ and a team of $2$ workers for task $2$. | def find_div(x):
b=[]
e=int(x**0.5)+1
for i in range(2,e):
if x%i==0:
c=0
while x%i==0:
c+=1
x=x//i
b.append(i**c)
if x!=1:
b.append(x)
return b
def solve(a,div,pos):
if pos==len(div):
return sum(a)
ans=2**30
for i in range(len(a)):
a[i]*=div[pos]
ans=min(ans,solve(a,div,pos+1))
a[i]=a[i]//div[pos]
return ans
t=int(input())
for _ in range(t):
k,x=map(int,input().split())
div=find_div(x)
if len(div)<=k:
ans=sum(div)+k-len(div)
else:
a=[1]*k
ans=solve(a,div,0)
print(ans) | def find_div(x):
b=[]
e=int(x**0.5)+1
for i in range(2,e):
if x%i==0:
c=0
while x%i==0:
c+=1
x=x//i
b.append(i**c)
if x!=1:
b.append(x)
return b
def solve(a,div,pos):
if pos==len(div):
return sum(a)
ans=2**30
for i in range(len(a)):
a[i]*=div[pos]
ans=min(ans,solve(a,div,pos+1))
a[i]=a[i]//div[pos]
return ans
t=int(input())
for _ in range(t):
k,x=map(int,input().split())
div=find_div(x)
if len(div)<=k:
ans=sum(div)+k-len(div)
else:
a=[1]*k
ans=solve(a,div,0)
print(ans) | train | APPS_structured |
We'll create a function that takes in two parameters:
* a sequence (length and types of items are irrelevant)
* a function (value, index) that will be called on members of the sequence and their index. The function will return either true or false.
Your function will iterate through the members of the sequence in order until the provided function returns true; at which point your function will return that item's **index**.
If the function given returns false for all members of the sequence, your function should return -1.
```python
true_if_even = lambda value, index: value % 2 == 0
find_in_array([1,3,5,6,7], true_if_even) # --> 3
``` | def find_in_array(seq, predicate):
for index, value in enumerate(seq):
if predicate(value,index):
return index
return -1
# print(type(predicate)) #function
# print(type(seq)) #list
# print(predicate.__name__) lambda
| def find_in_array(seq, predicate):
for index, value in enumerate(seq):
if predicate(value,index):
return index
return -1
# print(type(predicate)) #function
# print(type(seq)) #list
# print(predicate.__name__) lambda
| train | APPS_structured |
As you might remember, the collector of Siruseri had ordered
a complete revision of the Voters List. He knew that constructing
the list of voters is a difficult task, prone to errors. Some
voters may have been away on vacation, others may have moved
during the enrollment and so on.
To be as accurate as possible, he entrusted the task to three different
officials. Each of them was to independently record the list of voters and
send it to the collector. In Siruseri, every one has a ID number and
the list would only list the ID numbers of the voters and not their names.
The officials were expected to arrange the ID numbers in ascending order
in their lists.
On receiving the lists, the Collector realised that there were
discrepancies - the three lists were not identical. He decided
to go with the majority. That is, he decided to construct the
final list including only those ID numbers that appeared in at
least 2 out of the 3 lists. For example if the three lists
were
23 30 42 57 90
21 23 35 57 90 92
21 23 30 57 90
then the final list compiled by the collector would be:
21 23 30 57 90
The ID numbers 35, 42 and 92 which appeared in only one list
each do not figure in the final list.
Your task is to help the collector by writing a program that
produces the final list from the three given lists.
Input format
The first line of the input contains 3 integers
N1, N2 and
N3. N1 is the number of
voters in the first list, N2 is the number of
voters in the second list and N3 is the number of
voters in the third list. The next N1 lines
(lines 2,...,N1+1) contain one positive integer
each and describe the first list in ascending order. The following
N2 lines (lines
N1+2,...,N1+N2+1)
describe the second list in ascending order and the final
N3 lines (lines
N1+N2+2,...,N1+N2+N3+1)
describe the third list in ascending order.
Output format
The first line of the output should contain a single integer
M indicating the number voters in the final list. The next
M lines (lines 2,...,M+1) should contain one
positive integer each, describing the list of voters in the final
list, in ascending order.
Test data
You may assume that 1 ≤
N1,N2,N3
≤ 50000. You may also assume that in 50% of the inputs 1 ≤ N1,N2,N3 ≤ 2000.
Example
Sample input:
5 6 5
23
30
42
57
90
21
23
35
57
90
92
21
23
30
57
90
Sample output:
5
21
23
30
57
90 | from sys import stdout, stdin
n,m,o = list(map(int, stdin.readline().split()))
n= n+m+o
l=[]
a=[]
for i in range(n):
b= int(stdin.readline())
if(b in l and b not in a):
l.append(b)
a.append(b)
elif(b not in l):
l.append(b)
a.sort()
stdout.write(str(len(a)) + '\n')
stdout.write(''.join([str(id) + '\n' for id in a]))
| from sys import stdout, stdin
n,m,o = list(map(int, stdin.readline().split()))
n= n+m+o
l=[]
a=[]
for i in range(n):
b= int(stdin.readline())
if(b in l and b not in a):
l.append(b)
a.append(b)
elif(b not in l):
l.append(b)
a.sort()
stdout.write(str(len(a)) + '\n')
stdout.write(''.join([str(id) + '\n' for id in a]))
| train | APPS_structured |
# Task
Given array of integers, for each position i, search among the previous positions for the last (from the left) position that contains a smaller value. Store this value at position i in the answer. If no such value can be found, store `-1` instead.
# Example
For `items = [3, 5, 2, 4, 5]`, the output should be `[-1, 3, -1, 2, 4]`.
# Input/Output
- `[input]` integer array `arr`
Non-empty array of positive integers.
Constraints: `3 ≤ arr.length ≤ 1000, 1 ≤ arr[i] ≤ 1000.`
- `[output]` an integer array
Array containing answer values computed as described above. | import numpy as np
def array_previous_less(arr):
arr = arr[::-1]
output = np.full(len(arr), -1)
for i in range(len(arr)):
for j in arr[i+1:]:
if j<arr[i]:
output[i] = j
break
return output.tolist()[::-1] | import numpy as np
def array_previous_less(arr):
arr = arr[::-1]
output = np.full(len(arr), -1)
for i in range(len(arr)):
for j in arr[i+1:]:
if j<arr[i]:
output[i] = j
break
return output.tolist()[::-1] | train | APPS_structured |
Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique.
Example 1:
Input: arr = [1,2,2,1,1,3]
Output: true
Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.
Example 2:
Input: arr = [1,2]
Output: false
Example 3:
Input: arr = [-3,0,1,-3,1,1,1,-3,10,0]
Output: true
Constraints:
1 <= arr.length <= 1000
-1000 <= arr[i] <= 1000 | class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
rec = [arr.count(elem) for elem in set(arr)]
return len(rec) == len(set(rec))
| class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
rec = [arr.count(elem) for elem in set(arr)]
return len(rec) == len(set(rec))
| train | APPS_structured |
When provided with a String, capitalize all vowels
For example:
Input : "Hello World!"
Output : "HEllO WOrld!"
Note: Y is not a vowel in this kata. | swap=lambda s:s.translate(s.maketrans('aiueo','AIUEO')) | swap=lambda s:s.translate(s.maketrans('aiueo','AIUEO')) | train | APPS_structured |
You are given a binary tree:
```python
class Node:
def __init__(self, L, R, n):
self.left = L
self.right = R
self.value = n
```
Your task is to return the list with elements from tree sorted by levels, which means the root element goes first, then root children (from left to right) are second and third, and so on.
```if:ruby
Return empty array if root is `nil`.
```
```if:haskell
Return empty list if root is `Nothing`.
```
```if:python
Return empty list if root is `None`.
```
```if:csharp
Return empty list if root is 'null'.
```
```if:java
Return empty list is root is 'null'.
```
Example 1 - following tree:
2
8 9
1 3 4 5
Should return following list:
[2,8,9,1,3,4,5]
Example 2 - following tree:
1
8 4
3 5
7
Should return following list:
[1,8,4,3,5,7] | # Use a queue. Add root node, then loop:
# get first queue element, add all its children in the queue, left to right
# and add the current node's value in the result
def tree_by_levels(node):
queue = []
result = []
if node == None:
return result
queue.append(node)
while len(queue) > 0:
n = queue.pop(0)
if n.left != None:
queue.append(n.left)
if n.right != None:
queue.append(n.right)
result.append(n.value)
return result | # Use a queue. Add root node, then loop:
# get first queue element, add all its children in the queue, left to right
# and add the current node's value in the result
def tree_by_levels(node):
queue = []
result = []
if node == None:
return result
queue.append(node)
while len(queue) > 0:
n = queue.pop(0)
if n.left != None:
queue.append(n.left)
if n.right != None:
queue.append(n.right)
result.append(n.value)
return result | train | APPS_structured |
Two moving objects A and B are moving accross the same orbit (those can be anything: two planets, two satellites, two spaceships,two flying saucers, or spiderman with batman if you prefer).
If the two objects start to move from the same point and the orbit is circular, write a function that gives the time the two objects will meet again, given the time the objects A and B need to go through a full orbit, Ta and Tb respectively, and the radius of the orbit r.
As there can't be negative time, the sign of Ta and Tb, is an indication of the direction in which the object moving: positive for clockwise and negative for anti-clockwise.
The function will return a string that gives the time, in two decimal points.
Ta and Tb will have the same unit of measurement so you should not expect it in the solution.
Hint: Use angular velocity "w" rather than the classical "u". | def meeting_time(Ta, Tb, r):
if Ta == 0 and Tb == 0: return "0.00"
if Ta == 0: return "%.2f" % abs(Tb)
if Tb == 0: return "%.2f" % abs(Ta)
if (Ta > 0 and Tb > 0) or (Ta < 0 and Tb < 0):
return "%.2f" % (Ta * Tb / abs(abs(Ta) - abs(Tb)))
if ((Ta > 0 and Tb < 0) or (Tb > 0 and Ta < 0)):
return "%.2f" % (abs(Ta * Tb) / abs(abs(Ta) + abs(Tb))) | def meeting_time(Ta, Tb, r):
if Ta == 0 and Tb == 0: return "0.00"
if Ta == 0: return "%.2f" % abs(Tb)
if Tb == 0: return "%.2f" % abs(Ta)
if (Ta > 0 and Tb > 0) or (Ta < 0 and Tb < 0):
return "%.2f" % (Ta * Tb / abs(abs(Ta) - abs(Tb)))
if ((Ta > 0 and Tb < 0) or (Tb > 0 and Ta < 0)):
return "%.2f" % (abs(Ta * Tb) / abs(abs(Ta) + abs(Tb))) | train | APPS_structured |
In recreational mathematics, a [Keith number](https://en.wikipedia.org/wiki/Keith_number) or repfigit number (short for repetitive Fibonacci-like digit) is a number in the following integer sequence:
`14, 19, 28, 47, 61, 75, 197, 742, 1104, 1537, 2208, 2580, 3684, 4788, 7385, 7647, 7909, ...` (sequence A007629 in the OEIS)
Keith numbers were introduced by Mike Keith in 1987. They are computationally very challenging to find, with only about 100 known.
Implement the code to check if the given number is a Keith number. Return the number number of iteration needed to confirm it; otherwise return `false`.
**Note:** 1-digit numbers are **not** Keith numbers by definition
## Examples
```
n = 197 # --> [1, 9, 7]
# calculation iteration
1 + 9 + 7 = 17 # 1
9 + 7 + 17 = 33 # 2
7 + 17 + 33 = 57 # 3
17 + 33 + 57 = 107 # 4
33 + 57 + 107 = 197 # 5
```
As `197` is the same as the initial number, so it's a Keith number: return `5`
Another example:
```
n = 196
# calculation iteration
1 + 9 + 6 = 16 # 1
...
```
`196` is not a Keith number, so return `false` | def is_keith_number(n):
numList = [int(i) for i in str(n)] # int array
if len(numList) > 1: # min 2 digits
itr = 0
while numList[0] <= n:
# replace array entries by its sum:
numList[itr % len(numList)] = sum(numList)
itr += 1
if n in numList: # keith-condition
return itr
return False | def is_keith_number(n):
numList = [int(i) for i in str(n)] # int array
if len(numList) > 1: # min 2 digits
itr = 0
while numList[0] <= n:
# replace array entries by its sum:
numList[itr % len(numList)] = sum(numList)
itr += 1
if n in numList: # keith-condition
return itr
return False | train | APPS_structured |
Freddy has a really fat left pinky finger, and every time Freddy tries to type an ```A```, he accidentally hits the CapsLock key!
Given a string that Freddy wants to type, emulate the keyboard misses where each ```A``` supposedly pressed is replaced with CapsLock, and return the string that Freddy actually types. It doesn't matter if the ```A``` in the string is capitalized or not. When CapsLock is enabled, capitalization is reversed, but punctuation is not affected.
Examples:
```
"The quick brown fox jumps over the lazy dog."
-> "The quick brown fox jumps over the lZY DOG."
"The end of the institution, maintenance, and administration of government, is to secure the existence of the body politic, to protect it, and to furnish the individuals who compose it with the power of enjoying in safety and tranquillity their natural rights, and the blessings of life: and whenever these great objects are not obtained, the people have a right to alter the government, and to take measures necessary for their safety, prosperity and happiness."
-> "The end of the institution, mINTENnce, ND dministrTION OF GOVERNMENT, IS TO SECURE THE EXISTENCE OF THE BODY POLITIC, TO PROTECT IT, nd to furnish the individuLS WHO COMPOSE IT WITH THE POWER OF ENJOYING IN Sfety ND TRnquillity their nTURl rights, ND THE BLESSINGS OF LIFE: nd whenever these greT OBJECTS re not obtINED, THE PEOPLE Hve RIGHT TO lter the government, ND TO Tke meSURES NECESSry for their sFETY, PROSPERITY nd hPPINESS."
"aAaaaaAaaaAAaAa"
-> ""
```
**Note!**
If (Caps Lock is Enabled) and then you (HOLD Shift + alpha character) it will always be the reverse
Examples:
```
(Caps Lock Enabled) + (HOLD Shift + Press 'b') = b
(Caps Lock Disabled) + (HOLD Shift + Press 'b') = B
```
If the given string is `""`, the answer should be evident.
Happy coding!
~~~if:fortran
*NOTE: In Fortran, your returned string is* **not** *permitted to contain any unnecessary leading/trailing whitespace.*
~~~
(Adapted from https://codegolf.stackexchange.com/questions/158132/no-a-just-caps-lock) | def fat_fingers(string):
if string == "":
return string
if string is None:
return None
new_string = ""
caps_lock = False
for l in string:
if l.isalpha():
if l.lower() == 'a':
caps_lock = not caps_lock
elif caps_lock and l.lower() == l:
new_string += l.upper()
elif caps_lock and l.upper() == l:
new_string += l.lower()
else:
new_string += l
else:
new_string += l
return new_string | def fat_fingers(string):
if string == "":
return string
if string is None:
return None
new_string = ""
caps_lock = False
for l in string:
if l.isalpha():
if l.lower() == 'a':
caps_lock = not caps_lock
elif caps_lock and l.lower() == l:
new_string += l.upper()
elif caps_lock and l.upper() == l:
new_string += l.lower()
else:
new_string += l
else:
new_string += l
return new_string | train | APPS_structured |
This is the simple version of Shortest Code series. If you need some challenges, please try the [challenge version](http://www.codewars.com/kata/56f928b19982cc7a14000c9d)
## Task:
Every uppercase letter is Father, The corresponding lowercase letters is the Son.
Give you a string ```s```, If the father and son both exist, keep them. If it is a separate existence, delete them. Return the result.
For example:
```sc("Aab")``` should return ```"Aa"```
```sc("AabBc")``` should return ```"AabB"```
```sc("AaaaAaab")``` should return ```"AaaaAaa"```(father can have a lot of son)
```sc("aAAAaAAb")``` should return ```"aAAAaAA"```(son also can have a lot of father ;-)
### Series:
- [Bug in Apple](http://www.codewars.com/kata/56fe97b3cc08ca00e4000dc9)
- [Father and Son](http://www.codewars.com/kata/56fe9a0c11086cd842000008)
- [Jumping Dutch act](http://www.codewars.com/kata/570bcd9715944a2c8e000009)
- [Planting Trees](http://www.codewars.com/kata/5710443187a36a9cee0005a1)
- [Give me the equation](http://www.codewars.com/kata/56fe9b65cc08cafbc5000de3)
- [Find the murderer](http://www.codewars.com/kata/570f3fc5b29c702c5500043e)
- [Reading a Book](http://www.codewars.com/kata/570ca6a520c69f39dd0016d4)
- [Eat watermelon](http://www.codewars.com/kata/570df12ce6e9282a7d000947)
- [Special factor](http://www.codewars.com/kata/570e5d0b93214b1a950015b1)
- [Guess the Hat](http://www.codewars.com/kata/570ef7a834e61306da00035b)
- [Symmetric Sort](http://www.codewars.com/kata/5705aeb041e5befba20010ba)
- [Are they symmetrical?](http://www.codewars.com/kata/5705cc3161944b10fd0004ba)
- [Max Value](http://www.codewars.com/kata/570771871df89cf59b000742)
- [Trypophobia](http://www.codewars.com/kata/56fe9ffbc25bf33fff000f7c)
- [Virus in Apple](http://www.codewars.com/kata/5700af83d1acef83fd000048)
- [Balance Attraction](http://www.codewars.com/kata/57033601e55d30d3e0000633)
- [Remove screws I](http://www.codewars.com/kata/5710a50d336aed828100055a)
- [Remove screws II](http://www.codewars.com/kata/5710a8fd336aed00d9000594)
- [Regular expression compression](http://www.codewars.com/kata/570bae4b0237999e940016e9)
- [Collatz Array(Split or merge)](http://www.codewars.com/kata/56fe9d579b7bb6b027000001)
- [Tidy up the room](http://www.codewars.com/kata/5703ace6e55d30d3e0001029)
- [Waiting for a Bus](http://www.codewars.com/kata/57070eff924f343280000015) | def sc(s):
return ''.join(i for i in s if i.swapcase() in set(s)) | def sc(s):
return ''.join(i for i in s if i.swapcase() in set(s)) | train | APPS_structured |
You may have tried your level best to help Chef but Dr Doof has managed to come up with his masterplan in the meantime. Sadly, you have to help Chef once again. Dr Doof has designed a parenthesis-inator. It throws a stream of $N$ brackets at the target, $1$ bracket per second. The brackets can either be opening or closing. Chef appears in front of the stream at time $t$. If Chef faces an opening bracket, he gets hit. However, if he faces a closing bracket, he may choose to let it pass through him (Chef is immune to closing brackets). Chef gets a chance to counter attack Doof as soon as he finds a balanced non-empty bracket sequence. Help Chef by providing him the minimum time $x$ at which he will be able to launch his counter attack. If Chef is unable to counter attack, answer $-1$.
Formally, you are given a string $S$ of length $N$ consisting only of opening brackets $($ and closing brackets $)$. The substring of $S$ starting at index $L$ and ending at index $R$, i.e. $S_L S_{L+1} \ldots S_{R}$ is denoted by $S[L, R]$ . Consider $Q$ cases. In the $i^{\text{th}}$ case, Chef appears at time $t_i$ $(1 \leq t_i \leq N)$ and faces all characters from index $t_i$ to $N$. Find the minimum index $x$ $(t_i \leq x \leq N)$ such that the substring $S[t_i, x]$ contains a non-empty balanced bracket subsequence containing the same number of opening brackets as $S[t_i, x]$ (i.e., you cannot remove any opening bracket from the substring). If such an $x$ does not exist, print $-1$.
A string $X$ is called a subsequence of a string $Y$ if it is possible to obtain $X$ by erasing some (possibly zero) characters from $Y$ without changing the order of the remaining characters.
A balanced bracket sequence is defined as:
- an empty string is a balanced bracket sequence.
- if $s$ is a balanced bracket sequence, then so is $(s)$.
- if $s$ and $t$ are balanced bracket sequences, then so is $st$.
$Note :-$ The input files are large. The use of Fast I/O is recommended.
-----Input-----
- The first line contains a single integer $T$ denoting the number of testcases.
- The first line of each test case contains the string $S$.
- The next line contains a single integer $Q$ denoting the number of cases to consider.
- The next line contains $Q$ space separated integers, each denoting $t_i$.
-----Output-----
For each query, print the minimum value of $x$ in a separate line. If no such $x$ exists, print $-1$.
-----Constraints-----
- $1 \leq T \leq 10^3$
- $1 \leq |S| \leq 10^7$
- $1 \leq Q \leq 10^6$
- $1 \leq t_i \leq N$
- Every character of $S$ is either $($ or $)$.
- Sum of $|S|$ and $Q$ over all testcases for a particular test file does not exceed $10^7$ and $10^6$ respectively.
-----Sample Input-----
1
)())((()
3
1 7 6
-----Sample Output-----
3
8
-1
-----Explanation-----
For the first query, Chef chooses to let $S_1$ pass through him, gets hit by $S_2$ and finally completes a balanced bracket sequence by adding $S_3$ to $S_2$ at time $x$ = $3$. | from collections import deque
from sys import stdin
input=stdin.readline
for _ in range(int(input())):
s=list(input())
n=len(s)
ans=[0]*n
x=0
y=0
a=n-1
b=n-1
stack=deque([])
prev=-1
while a>=0:
if s[a]==')':
stack.append(a)
ans[a] = prev
else:
if len(stack)==0:
ans[a]=-1
prev=-1
else:
prev=stack[-1]+1
ans[a]=prev
stack.pop()
a-=1
q=int(input())
x=list(map(int,input().split()))
for i in x:
i=i-1
print(ans[i])
| from collections import deque
from sys import stdin
input=stdin.readline
for _ in range(int(input())):
s=list(input())
n=len(s)
ans=[0]*n
x=0
y=0
a=n-1
b=n-1
stack=deque([])
prev=-1
while a>=0:
if s[a]==')':
stack.append(a)
ans[a] = prev
else:
if len(stack)==0:
ans[a]=-1
prev=-1
else:
prev=stack[-1]+1
ans[a]=prev
stack.pop()
a-=1
q=int(input())
x=list(map(int,input().split()))
for i in x:
i=i-1
print(ans[i])
| train | APPS_structured |
Cheffina challanges chef to rearrange the given array as arr[i] > arr[i+1] < arr[i+2] > arr[i+3].. and so on…, i.e. also arr[i] < arr[i+2] and arr[i+1] < arr[i+3] and arr[i] < arr[i+3] so on.. Chef accepts the challenge, chef starts coding but his code is not compiling help him to write new code.
-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains two lines of input, First $N$ as the size of the array.
- N space-separated distinct integers.
-----Output:-----
For each test case, output in a single line answer given to the Chefffina.
-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq N \leq 10^5$
- $1 \leq arr[i] \leq 10^5$
-----Sample Input:-----
2
4
4 1 6 3
5
4 5 1 6 3
-----Sample Output:-----
3 1 6 4
3 1 5 4 6 | # cook your dish here
for _ in range(int(input())):
n=int(input())
arr=[int(i) for i in input().split()]
arr=sorted(arr)
for i in range(n):
if i%2==0:
if i==n-1:
print(arr[i],'',end='')
else:
print(arr[i+1],'',end='')
else:
print(arr[i-1],'',end='')
print()
| # cook your dish here
for _ in range(int(input())):
n=int(input())
arr=[int(i) for i in input().split()]
arr=sorted(arr)
for i in range(n):
if i%2==0:
if i==n-1:
print(arr[i],'',end='')
else:
print(arr[i+1],'',end='')
else:
print(arr[i-1],'',end='')
print()
| train | APPS_structured |
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K (odd) to form a new pattern. Help the chef to code this pattern problem.
-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.
-----Output:-----
For each test case, output as the pattern.
-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$
-----Sample Input:-----
4
1
3
5
7
-----Sample Output:-----
*
*
**
*
*
**
* *
**
*
*
**
* *
* *
* *
**
*
-----EXPLANATION:-----
No need, else pattern can be decode easily. | import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")
inp = lambda: list(map(int,sys.stdin.readline().rstrip("\r\n").split()))
#______________________________________________________________________________________________________
# from math import *
# from bisect import *
# from heapq import *
# from collections import defaultdict as dd
# from collections import OrderedDict as odict
from collections import Counter as cc
# from collections import deque
# sys.setrecursionlimit(2*(10**5)+100) this is must for dfs
mod = 10**9+7; md = 998244353
# ______________________________________________________________________________________________________
# segment tree for range minimum query
# sys.setrecursionlimit(10**5)
# n = int(input())
# a = list(map(int,input().split()))
# st = [float('inf') for i in range(4*len(a))]
# def build(a,ind,start,end):
# if start == end:
# st[ind] = a[start]
# else:
# mid = (start+end)//2
# build(a,2*ind+1,start,mid)
# build(a,2*ind+2,mid+1,end)
# st[ind] = min(st[2*ind+1],st[2*ind+2])
# build(a,0,0,n-1)
# def query(ind,l,r,start,end):
# if start>r or end<l:
# return float('inf')
# if l<=start<=end<=r:
# return st[ind]
# mid = (start+end)//2
# return min(query(2*ind+1,l,r,start,mid),query(2*ind+2,l,r,mid+1,end))
# ______________________________________________________________________________________________________
# Checking prime in O(root(N))
# def isprime(n):
# if (n % 2 == 0 and n > 2) or n == 1: return 0
# else:
# s = int(n**(0.5)) + 1
# for i in range(3, s, 2):
# if n % i == 0:
# return 0
# return 1
# def lcm(a,b):
# return (a*b)//gcd(a,b)
# ______________________________________________________________________________________________________
# nCr under mod
# def C(n,r,mod):
# if r>n:
# return 0
# num = den = 1
# for i in range(r):
# num = (num*(n-i))%mod
# den = (den*(i+1))%mod
# return (num*pow(den,mod-2,mod))%mod
# M = 10**5 +10
# ______________________________________________________________________________________________________
# For smallest prime factor of a number
# M = 1000010
# pfc = [i for i in range(M)]
# def pfcs(M):
# for i in range(2,M):
# if pfc[i]==i:
# for j in range(i+i,M,i):
# if pfc[j]==j:
# pfc[j] = i
# return
# pfcs(M)
# ______________________________________________________________________________________________________
tc = 1
tc, = inp()
for _ in range(tc):
n, = inp()
if n==1:
print('*')
continue
n = n//2+1
print('*')
a = [' ']*(n)
a[0] = '*'
a[1] = '*'
print()
for i in range(1,n-1):
print('*'+' '*(i-1)+'*')
print()
print('*'+' '*(n-2)+'*')
print()
for i in range(n-2,0,-1):
print('*'+' '*(i-1)+'*')
print()
print('*') | import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")
inp = lambda: list(map(int,sys.stdin.readline().rstrip("\r\n").split()))
#______________________________________________________________________________________________________
# from math import *
# from bisect import *
# from heapq import *
# from collections import defaultdict as dd
# from collections import OrderedDict as odict
from collections import Counter as cc
# from collections import deque
# sys.setrecursionlimit(2*(10**5)+100) this is must for dfs
mod = 10**9+7; md = 998244353
# ______________________________________________________________________________________________________
# segment tree for range minimum query
# sys.setrecursionlimit(10**5)
# n = int(input())
# a = list(map(int,input().split()))
# st = [float('inf') for i in range(4*len(a))]
# def build(a,ind,start,end):
# if start == end:
# st[ind] = a[start]
# else:
# mid = (start+end)//2
# build(a,2*ind+1,start,mid)
# build(a,2*ind+2,mid+1,end)
# st[ind] = min(st[2*ind+1],st[2*ind+2])
# build(a,0,0,n-1)
# def query(ind,l,r,start,end):
# if start>r or end<l:
# return float('inf')
# if l<=start<=end<=r:
# return st[ind]
# mid = (start+end)//2
# return min(query(2*ind+1,l,r,start,mid),query(2*ind+2,l,r,mid+1,end))
# ______________________________________________________________________________________________________
# Checking prime in O(root(N))
# def isprime(n):
# if (n % 2 == 0 and n > 2) or n == 1: return 0
# else:
# s = int(n**(0.5)) + 1
# for i in range(3, s, 2):
# if n % i == 0:
# return 0
# return 1
# def lcm(a,b):
# return (a*b)//gcd(a,b)
# ______________________________________________________________________________________________________
# nCr under mod
# def C(n,r,mod):
# if r>n:
# return 0
# num = den = 1
# for i in range(r):
# num = (num*(n-i))%mod
# den = (den*(i+1))%mod
# return (num*pow(den,mod-2,mod))%mod
# M = 10**5 +10
# ______________________________________________________________________________________________________
# For smallest prime factor of a number
# M = 1000010
# pfc = [i for i in range(M)]
# def pfcs(M):
# for i in range(2,M):
# if pfc[i]==i:
# for j in range(i+i,M,i):
# if pfc[j]==j:
# pfc[j] = i
# return
# pfcs(M)
# ______________________________________________________________________________________________________
tc = 1
tc, = inp()
for _ in range(tc):
n, = inp()
if n==1:
print('*')
continue
n = n//2+1
print('*')
a = [' ']*(n)
a[0] = '*'
a[1] = '*'
print()
for i in range(1,n-1):
print('*'+' '*(i-1)+'*')
print()
print('*'+' '*(n-2)+'*')
print()
for i in range(n-2,0,-1):
print('*'+' '*(i-1)+'*')
print()
print('*') | train | APPS_structured |
Your task is the exact same as for the easy version. But this time, the marmots subtract the village's population P from their random number before responding to Heidi's request.
Also, there are now villages with as few as a single inhabitant, meaning that $1 \leq P \leq 1000$.
Can you help Heidi find out whether a village follows a Poisson or a uniform distribution?
-----Input-----
Same as for the easy and medium versions. But remember that now 1 ≤ P ≤ 1000 and that the marmots may provide positive as well as negative integers.
-----Output-----
Output one line per village, in the same order as provided in the input. The village's line shall state poisson if the village's distribution is of the Poisson type, and uniform if the answers came from a uniform distribution. | for i in range(int(input())):
a=list(map(int,input().split()))
mx=max(list(map(abs,a)))
std=(sum(list([x*x for x in a]))/len(a))**0.5
print('poisson'if mx/std>2 else'uniform')
| for i in range(int(input())):
a=list(map(int,input().split()))
mx=max(list(map(abs,a)))
std=(sum(list([x*x for x in a]))/len(a))**0.5
print('poisson'if mx/std>2 else'uniform')
| train | APPS_structured |
You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' $\rightarrow$ 'y' $\rightarrow$ 'x' $\rightarrow \ldots \rightarrow$ 'b' $\rightarrow$ 'a' $\rightarrow$ 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'.
What is the lexicographically minimum string that can be obtained from s by performing this shift exactly once?
-----Input-----
The only line of the input contains the string s (1 ≤ |s| ≤ 100 000) consisting of lowercase English letters.
-----Output-----
Print the lexicographically minimum string that can be obtained from s by shifting letters of exactly one non-empty substring.
-----Examples-----
Input
codeforces
Output
bncdenqbdr
Input
abacaba
Output
aaacaba
-----Note-----
String s is lexicographically smaller than some other string t of the same length if there exists some 1 ≤ i ≤ |s|, such that s_1 = t_1, s_2 = t_2, ..., s_{i} - 1 = t_{i} - 1, and s_{i} < t_{i}. | import sys
def shl(s, be, en):
t = s[:be];
for i in range(be, en):
if s[i]=='a':
t += 'z'
else:
t += chr(ord(s[i])-1)
return t+s[en:]
s = input()
i = 0
L = len(s)
while i<L and s[i]=='a':
i += 1
if i==L:
print(s[:L-1]+'z')
return
j = i+1
while j<L and s[j]!='a':
j += 1
print(shl(s,i,j))
| import sys
def shl(s, be, en):
t = s[:be];
for i in range(be, en):
if s[i]=='a':
t += 'z'
else:
t += chr(ord(s[i])-1)
return t+s[en:]
s = input()
i = 0
L = len(s)
while i<L and s[i]=='a':
i += 1
if i==L:
print(s[:L-1]+'z')
return
j = i+1
while j<L and s[j]!='a':
j += 1
print(shl(s,i,j))
| train | APPS_structured |
Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm.
Sereja takes a blank piece of paper. Then he starts writing out the sequence in m stages. Each time he either adds a new number to the end of the sequence or takes l first elements of the current sequence and adds them c times to the end. More formally, if we represent the current sequence as a_1, a_2, ..., a_{n}, then after we apply the described operation, the sequence transforms into a_1, a_2, ..., a_{n}[, a_1, a_2, ..., a_{l}] (the block in the square brackets must be repeated c times).
A day has passed and Sereja has completed the sequence. He wonders what are the values of some of its elements. Help Sereja.
-----Input-----
The first line contains integer m (1 ≤ m ≤ 10^5) — the number of stages to build a sequence.
Next m lines contain the description of the stages in the order they follow. The first number in the line is a type of stage (1 or 2). Type 1 means adding one number to the end of the sequence, in this case the line contains integer x_{i} (1 ≤ x_{i} ≤ 10^5) — the number to add. Type 2 means copying a prefix of length l_{i} to the end c_{i} times, in this case the line further contains two integers l_{i}, c_{i} (1 ≤ l_{i} ≤ 10^5, 1 ≤ c_{i} ≤ 10^4), l_{i} is the length of the prefix, c_{i} is the number of copyings. It is guaranteed that the length of prefix l_{i} is never larger than the current length of the sequence.
The next line contains integer n (1 ≤ n ≤ 10^5) — the number of elements Sereja is interested in. The next line contains the numbers of elements of the final sequence Sereja is interested in. The numbers are given in the strictly increasing order. It is guaranteed that all numbers are strictly larger than zero and do not exceed the length of the resulting sequence. Consider the elements of the final sequence numbered starting from 1 from the beginning to the end of the sequence.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
-----Output-----
Print the elements that Sereja is interested in, in the order in which their numbers occur in the input.
-----Examples-----
Input
6
1 1
1 2
2 2 1
1 3
2 5 2
1 4
16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Output
1 2 1 2 3 1 2 1 2 3 1 2 1 2 3 4 | from bisect import bisect_left
m = int(input())
t, s = [input().split() for i in range(m)], [0] * m
l, n = 0, int(input())
for j, i in enumerate(t):
l += 1 if i[0] == '1' else int(i[1]) * int(i[2])
t[j], s[j] = l, i[1] if i[0] == '1' else int(i[1])
F = {}
def f(i):
if not i in F:
k = bisect_left(t, i)
F[i] = s[k] if type(s[k]) == str else f((i - t[k] - 1) % s[k] + 1)
return F[i]
print(' '.join(f(i) for i in map(int, input().split())))
| from bisect import bisect_left
m = int(input())
t, s = [input().split() for i in range(m)], [0] * m
l, n = 0, int(input())
for j, i in enumerate(t):
l += 1 if i[0] == '1' else int(i[1]) * int(i[2])
t[j], s[j] = l, i[1] if i[0] == '1' else int(i[1])
F = {}
def f(i):
if not i in F:
k = bisect_left(t, i)
F[i] = s[k] if type(s[k]) == str else f((i - t[k] - 1) % s[k] + 1)
return F[i]
print(' '.join(f(i) for i in map(int, input().split())))
| train | APPS_structured |
You came across this story while reading a book. Long a ago when the modern entertainment systems did not exist people used to go to watch plays in theaters, where people would perform live in front of an audience. There was a beautiful actress who had a disability she could not pronounce the character $'r'$. To win her favours which many have been denied in past, you decide to write a whole play without the character $'r'$. Now you have to get the script reviewed by the editor before presenting it to her.
The editor was flattered by the script and agreed to you to proceed. The editor will edit the script in this way to suit her style. For each word replace it with a sub-sequence of itself such that it contains the character 'a'.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements Wikipedia
Now given a script with $N$ words, for each word in the script you wish to know the number of subsequences with which it can be replaced.
-----Input:-----
- First-line will contain $N$, the number of words in the script. Then next $N$ line with one test case each.
- Each test case contains a single word $W_i$
-----Output:-----
For each test case, output in a single line number of subsequences with which it can be replaced.
-----Constraints-----
- $1 \leq N \leq 1000$
- $1 \leq$ length of $W_i$ $\leq 20$
- $W_i$ on contains lowercase english alphabets and does not have the character 'r'
-----Sample Input 1:-----
2
abc
aba
-----Sample Output 1:-----
4
6
-----EXPLANATION:-----
This subsequences with which $abc$ can be replaed : ${a,ab,ac,abc}$.
This subsequences with which $aba$ can be replaed : ${a,ab,aba,a,ba,a}$.
-----Sample Input 2:-----
3
abcde
abcdea
xyz
-----Sample Output 2:-----
16
48
0 | # def count(a, b):
# m = len(a);n = 1
# lookup = [[0] * (n + 1) for i in range(m + 1)]
# for i in range(n+1): lookup[0][i] = 0
# for i in range(m + 1): lookup[i][0] = 1
# for i in range(1, m + 1):
# for j in range(1, n + 1):
# if a[i - 1] == b[j - 1]: lookup[i][j] = lookup[i - 1][j - 1] + lookup[i - 1][j]
# else: lookup[i][j] = lookup[i - 1][j]
# return lookup[m][n]
# for _ in range(int(input())):
# a = input()
# b = "a"
# print(count(a, b)) #this just counts the number of times a string occurs, nut the subsequences
#>>> if there are only a's, then answer is (2**len) - 1
#>>> if there are len - 1 a's and one diff, then answer is (2**len) - 2
#>>> if there are len - 1 diff's and one a, then answer is 2**(len - 1)
#>>> if there are all diff, then answer is 0
#>>> there has to be a direct relation somewhere...gottit..if there are equal a's and diffs, then answer is 2**len - 2**(len/2)
#>>> wait a minute...2**len - 2**(len/2) this works for inequalities also (?)
for _ in range(int(input())):
a = input();count = 0
for i in a:
if(i != "a"): count += 1
print(2**len(a) - 2**count) | # def count(a, b):
# m = len(a);n = 1
# lookup = [[0] * (n + 1) for i in range(m + 1)]
# for i in range(n+1): lookup[0][i] = 0
# for i in range(m + 1): lookup[i][0] = 1
# for i in range(1, m + 1):
# for j in range(1, n + 1):
# if a[i - 1] == b[j - 1]: lookup[i][j] = lookup[i - 1][j - 1] + lookup[i - 1][j]
# else: lookup[i][j] = lookup[i - 1][j]
# return lookup[m][n]
# for _ in range(int(input())):
# a = input()
# b = "a"
# print(count(a, b)) #this just counts the number of times a string occurs, nut the subsequences
#>>> if there are only a's, then answer is (2**len) - 1
#>>> if there are len - 1 a's and one diff, then answer is (2**len) - 2
#>>> if there are len - 1 diff's and one a, then answer is 2**(len - 1)
#>>> if there are all diff, then answer is 0
#>>> there has to be a direct relation somewhere...gottit..if there are equal a's and diffs, then answer is 2**len - 2**(len/2)
#>>> wait a minute...2**len - 2**(len/2) this works for inequalities also (?)
for _ in range(int(input())):
a = input();count = 0
for i in a:
if(i != "a"): count += 1
print(2**len(a) - 2**count) | train | APPS_structured |
"The Shell Game" involves cups upturned on a playing surface, with a ball placed underneath one of them. The index of the cups are swapped around multiple times. After that the players will try to find which cup contains the ball.
Your task is as follows. Given the cup that the ball starts under, and list of swaps, return the location of the ball at the end. Cups are given like array/list indices.
For example, given the starting position `0` and the swaps `[(0, 1), (1, 2), (1, 0)]`:
* The first swap moves the ball from `0` to `1`
* The second swap moves the ball from `1` to `2`
* The final swap doesn't affect the position of the ball.
So
```python
find_the_ball(0, [(0, 1), (2, 1), (0, 1)]) == 2
```
There aren't necessarily only three cups in this game, but there will be at least two. You can assume all swaps are valid, and involve two distinct indices. | def find_the_ball(pos, swaps):
for a, b in swaps:
pos = a if pos == b else b if pos == a else pos
return pos | def find_the_ball(pos, swaps):
for a, b in swaps:
pos = a if pos == b else b if pos == a else pos
return pos | train | APPS_structured |
=====Function Descriptions=====
itertools.combinations_with_replacement(iterable, r)
This tool returns
length subsequences of elements from the input iterable allowing individual elements to be repeated more than once.
Combinations are emitted in lexicographic sorted order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.
Sample Code
>>> from itertools import combinations_with_replacement
>>>
>>> print list(combinations_with_replacement('12345',2))
[('1', '1'), ('1', '2'), ('1', '3'), ('1', '4'), ('1', '5'), ('2', '2'), ('2', '3'), ('2', '4'), ('2', '5'), ('3', '3'), ('3', '4'), ('3', '5'), ('4', '4'), ('4', '5'), ('5', '5')]
>>>
>>> A = [1,1,3,3,3]
>>> print list(combinations(A,2))
[(1, 1), (1, 3), (1, 3), (1, 3), (1, 3), (1, 3), (1, 3), (3, 3), (3, 3), (3, 3)]
=====Problem Statement=====
You are given a string S.
Your task is to print all possible size k replacement combinations of the string in lexicographic sorted order.
=====Input Format=====
A single line containing the string S and integer value k separated by a space.
=====Constraints=====
0<k≤len(S)
The string contains only UPPERCASE characters.
=====Output Format=====
Print the combinations with their replacements of string S on separate lines. | from itertools import *
s,n = input().split()
n = int(n)
s = sorted(s)
for j in combinations_with_replacement(s,n):
print((''.join(j)))
| from itertools import *
s,n = input().split()
n = int(n)
s = sorted(s)
for j in combinations_with_replacement(s,n):
print((''.join(j)))
| train | APPS_structured |
Now that Heidi has made sure her Zombie Contamination level checker works, it's time to strike! This time, the zombie lair is a strictly convex polygon on the lattice. Each vertex of the polygon occupies a point on the lattice. For each cell of the lattice, Heidi knows the level of Zombie Contamination – the number of corners of the cell that are inside or on the border of the lair.
Given this information, Heidi wants to know the exact shape of the lair to rain destruction on the zombies. Help her!
[Image]
-----Input-----
The input contains multiple test cases.
The first line of each test case contains one integer N, the size of the lattice grid (5 ≤ N ≤ 500). The next N lines each contain N characters, describing the level of Zombie Contamination of each cell in the lattice. Every character of every line is a digit between 0 and 4.
Cells are given in the same order as they are shown in the picture above: rows go in the decreasing value of y coordinate, and in one row cells go in the order of increasing x coordinate. This means that the first row corresponds to cells with coordinates (1, N), ..., (N, N) and the last row corresponds to cells with coordinates (1, 1), ..., (N, 1).
The last line of the file contains a zero. This line should not be treated as a test case. The sum of the N values for all tests in one file will not exceed 5000.
-----Output-----
For each test case, give the following output:
The first line of the output should contain one integer V, the number of vertices of the polygon that is the secret lair. The next V lines each should contain two integers, denoting the vertices of the polygon in the clockwise order, starting from the lexicographically smallest vertex.
-----Examples-----
Input
8
00000000
00000110
00012210
01234200
02444200
01223200
00001100
00000000
5
00000
01210
02420
01210
00000
7
0000000
0122100
0134200
0013200
0002200
0001100
0000000
0
Output
4
2 3
2 4
6 6
5 2
4
2 2
2 3
3 3
3 2
3
2 5
4 5
4 2
-----Note-----
It is guaranteed that the solution always exists and is unique. It is guaranteed that in the correct solution the coordinates of the polygon vertices are between 2 and N - 2. A vertex (x_1, y_1) is lexicographically smaller than vertex (x_2, y_2) if x_1 < x_2 or $x_{1} = x_{2} \wedge y_{1} < y_{2}$. | import math
def lexComp(a, b):
if a[0] != b[0]:
return -1 if a[0] < b[0] else 1
if a[1] != b[1]:
return -1 if a[1] < b[1] else 1
return 0
def turn(a, b, c):
return (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0])
def dist2(a, b):
return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2
def solve(n):
a = [list(map(int, input())) for _ in range(n)]
points = []
for i in range(n):
for j in range(n):
if a[i][j] == 1:
curPoints = []
for dx in range(0, 2):
for dy in range(0, 2):
ok = True
for ddx in range(0, 2):
for ddy in range(0, 2):
x, y = i - 1 + dx + ddx, j - 1 + dy + ddy
if 0 <= x < n and 0 <= y < n and a[x][y] == 0:
ok = False
if ok:
curPoints.append((i + dx, j + dy))
points.append(curPoints[0])
points = list(set(points))
for i in range(1, len(points)):
if lexComp(points[0], points[i]) > 0:
points[0], points[i] = points[i], points[0]
points[1:] = sorted(points[1:], key=lambda p: (math.atan2(p[1] - points[0][1], p[0] - points[0][0]), dist2(p, points[0])))
hull = []
for p in points:
while len(hull) >= 2 and turn(hull[-2], hull[-1], p) <= 0:
hull.pop()
hull.append(p)
hull = [(p[1], n - p[0]) for p in hull]
hull = hull[::-1]
start = 0
for i in range(1, len(hull)):
if lexComp(hull[i], hull[start]) < 0:
start = i
newHull = hull[start:]
newHull.extend(hull[:start])
hull = newHull
print(len(hull))
for p in hull:
print(p[0], p[1])
while True:
n = int(input())
if n == 0:
break
solve(n)
| import math
def lexComp(a, b):
if a[0] != b[0]:
return -1 if a[0] < b[0] else 1
if a[1] != b[1]:
return -1 if a[1] < b[1] else 1
return 0
def turn(a, b, c):
return (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0])
def dist2(a, b):
return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2
def solve(n):
a = [list(map(int, input())) for _ in range(n)]
points = []
for i in range(n):
for j in range(n):
if a[i][j] == 1:
curPoints = []
for dx in range(0, 2):
for dy in range(0, 2):
ok = True
for ddx in range(0, 2):
for ddy in range(0, 2):
x, y = i - 1 + dx + ddx, j - 1 + dy + ddy
if 0 <= x < n and 0 <= y < n and a[x][y] == 0:
ok = False
if ok:
curPoints.append((i + dx, j + dy))
points.append(curPoints[0])
points = list(set(points))
for i in range(1, len(points)):
if lexComp(points[0], points[i]) > 0:
points[0], points[i] = points[i], points[0]
points[1:] = sorted(points[1:], key=lambda p: (math.atan2(p[1] - points[0][1], p[0] - points[0][0]), dist2(p, points[0])))
hull = []
for p in points:
while len(hull) >= 2 and turn(hull[-2], hull[-1], p) <= 0:
hull.pop()
hull.append(p)
hull = [(p[1], n - p[0]) for p in hull]
hull = hull[::-1]
start = 0
for i in range(1, len(hull)):
if lexComp(hull[i], hull[start]) < 0:
start = i
newHull = hull[start:]
newHull.extend(hull[:start])
hull = newHull
print(len(hull))
for p in hull:
print(p[0], p[1])
while True:
n = int(input())
if n == 0:
break
solve(n)
| train | APPS_structured |
Everybody loves **pi**, but what if **pi** were a square? Given a number of digits ```digits```, find the smallest integer whose square is greater or equal to the sum of the squares of the first ```digits``` digits of pi, including the ```3``` before the decimal point.
**Note:** Test cases will not extend beyond 100 digits; the first 100 digits of pi are pasted here for your convenience:
```
31415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679
```
## Examples
```
digits = 1 # [3]
expected = 3 # sqrt(3^2) = 3
digits = 3 # [3, 1, 4]
expected = 6 # sqrt(3^2 + 1^2 + 4^2) = 5.099 --> 6
``` | from math import ceil
from itertools import accumulate
digs = map(int,'031415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679')
MEMO = tuple( ceil(s**.5) for s in accumulate(d*d for d in digs))
square_pi = MEMO.__getitem__ | from math import ceil
from itertools import accumulate
digs = map(int,'031415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679')
MEMO = tuple( ceil(s**.5) for s in accumulate(d*d for d in digs))
square_pi = MEMO.__getitem__ | train | APPS_structured |
Your task is to form an integer array nums from an initial array of zeros arr that is the same size as nums.
Return the minimum number of function calls to make nums from arr.
The answer is guaranteed to fit in a 32-bit signed integer.
Example 1:
Input: nums = [1,5]
Output: 5
Explanation: Increment by 1 (second element): [0, 0] to get [0, 1] (1 operation).
Double all the elements: [0, 1] -> [0, 2] -> [0, 4] (2 operations).
Increment by 1 (both elements) [0, 4] -> [1, 4] -> [1, 5] (2 operations).
Total of operations: 1 + 2 + 2 = 5.
Example 2:
Input: nums = [2,2]
Output: 3
Explanation: Increment by 1 (both elements) [0, 0] -> [0, 1] -> [1, 1] (2 operations).
Double all the elements: [1, 1] -> [2, 2] (1 operation).
Total of operations: 2 + 1 = 3.
Example 3:
Input: nums = [4,2,5]
Output: 6
Explanation: (initial)[0,0,0] -> [1,0,0] -> [1,0,1] -> [2,0,2] -> [2,1,2] -> [4,2,4] -> [4,2,5](nums).
Example 4:
Input: nums = [3,2,2,4]
Output: 7
Example 5:
Input: nums = [2,4,8,16]
Output: 8
Constraints:
1 <= nums.length <= 10^5
0 <= nums[i] <= 10^9 | class Solution:
def minOperations(self, nums: List[int]) -> int:
count=0
res={}
for i in range(len(nums)):
if nums[i]!=0:
res[i]=nums[i]
zeros=[]
while res:
zeros.clear()
for key in res:
if res[key]%2!=0:
res[key]-=1
count+=1
minus=True
if res[key]==0:
zeros.append(key)
for zero in zeros:
res.pop(zero)
if res:
for key in res:
res[key]//=2
count+=1
return count
| class Solution:
def minOperations(self, nums: List[int]) -> int:
count=0
res={}
for i in range(len(nums)):
if nums[i]!=0:
res[i]=nums[i]
zeros=[]
while res:
zeros.clear()
for key in res:
if res[key]%2!=0:
res[key]-=1
count+=1
minus=True
if res[key]==0:
zeros.append(key)
for zero in zeros:
res.pop(zero)
if res:
for key in res:
res[key]//=2
count+=1
return count
| train | APPS_structured |
You are given an array A of strings.
A move onto S consists of swapping any two even indexed characters of S, or any two odd indexed characters of S.
Two strings S and T are special-equivalent if after any number of moves onto S, S == T.
For example, S = "zzxy" and T = "xyzz" are special-equivalent because we may make the moves "zzxy" -> "xzzy" -> "xyzz" that swap S[0] and S[2], then S[1] and S[3].
Now, a group of special-equivalent strings from A is a non-empty subset of A such that:
Every pair of strings in the group are special equivalent, and;
The group is the largest size possible (ie., there isn't a string S not in the group such that S is special equivalent to every string in the group)
Return the number of groups of special-equivalent strings from A.
Example 1:
Input: ["abcd","cdab","cbad","xyzz","zzxy","zzyx"]
Output: 3
Explanation:
One group is ["abcd", "cdab", "cbad"], since they are all pairwise special equivalent, and none of the other strings are all pairwise special equivalent to these.
The other two groups are ["xyzz", "zzxy"] and ["zzyx"]. Note that in particular, "zzxy" is not special equivalent to "zzyx".
Example 2:
Input: ["abc","acb","bac","bca","cab","cba"]
Output: 3
Note:
1 <= A.length <= 1000
1 <= A[i].length <= 20
All A[i] have the same length.
All A[i] consist of only lowercase letters. | class Solution:
def numSpecialEquivGroups(self, A: List[str]) -> int:
return len(set(''.join(sorted(s[0::2])) + ''.join(sorted(s[1::2])) for s in A))
| class Solution:
def numSpecialEquivGroups(self, A: List[str]) -> int:
return len(set(''.join(sorted(s[0::2])) + ''.join(sorted(s[1::2])) for s in A))
| train | APPS_structured |
In this kata, we're going to create the function `nato` that takes a `word` and returns a string that spells the word using the [NATO phonetic alphabet](https://en.wikipedia.org/wiki/NATO_phonetic_alphabet).
There should be a space between each word in the returned string, and the first letter of each word should be capitalized.
For those of you that don't want your fingers to bleed, this kata already has a dictionary typed out for you.
``` python
nato("Banana") # == "Bravo Alpha November Alpha November Alpha"
```
``` ruby
nato("Banana") # == "Bravo Alpha November Alpha November Alpha"
``` | letters = {
"A": "Alpha", "B": "Bravo", "C": "Charlie",
"D": "Delta", "E": "Echo", "F": "Foxtrot",
"G": "Golf", "H": "Hotel", "I": "India",
"J": "Juliett","K": "Kilo", "L": "Lima",
"M": "Mike", "N": "November","O": "Oscar",
"P": "Papa", "Q": "Quebec", "R": "Romeo",
"S": "Sierra", "T": "Tango", "U": "Uniform",
"V": "Victor", "W": "Whiskey", "X": "X-ray",
"Y": "Yankee", "Z": "Zulu"
}
def nato(word):
return " ".join([letters[c] for c in word.upper()]) | letters = {
"A": "Alpha", "B": "Bravo", "C": "Charlie",
"D": "Delta", "E": "Echo", "F": "Foxtrot",
"G": "Golf", "H": "Hotel", "I": "India",
"J": "Juliett","K": "Kilo", "L": "Lima",
"M": "Mike", "N": "November","O": "Oscar",
"P": "Papa", "Q": "Quebec", "R": "Romeo",
"S": "Sierra", "T": "Tango", "U": "Uniform",
"V": "Victor", "W": "Whiskey", "X": "X-ray",
"Y": "Yankee", "Z": "Zulu"
}
def nato(word):
return " ".join([letters[c] for c in word.upper()]) | train | APPS_structured |
Tranform of input array of zeros and ones to array in which counts number of continuous ones:
[1, 1, 1, 0, 1] -> [3,1] | def ones_counter(input):
c, result = 0, []
for x in input + [0]:
if x != 1 and c != 0:
result.append(c)
c = 0
elif x == 1:
c += 1
return result | def ones_counter(input):
c, result = 0, []
for x in input + [0]:
if x != 1 and c != 0:
result.append(c)
c = 0
elif x == 1:
c += 1
return result | train | APPS_structured |
# History
This kata is a sequel of my [Mixbonacci](https://www.codewars.com/kata/mixbonacci/python) kata. Zozonacci is a special integer sequence named after [**ZozoFouchtra**](https://www.codewars.com/users/ZozoFouchtra), who came up with this kata idea in the [Mixbonacci discussion](https://www.codewars.com/kata/mixbonacci/discuss/python).
This sequence combines the rules for computing the n-th elements of fibonacci, jacobstal, pell, padovan, tribonacci and tetranacci sequences according to a given pattern.
# Task
Compute the first `n` elements of the Zozonacci sequence for a given pattern `p`.
## Rules
1. `n` is given as integer and `p` is given as a list of as abbreviations as strings (e.g. `["fib", "jac", "pad"]`)
2. When `n` is 0 or `p` is empty return an empty list.
3. The first four elements of the sequence are determined by the first abbreviation in the pattern (see the table below).
4. Compute the fifth element using the formula corespoding to the first element of the pattern, the sixth element using the formula for the second element and so on. (see the table below and the examples)
5. If `n` is more than the length of `p` repeat the pattern.
```
+------------+--------------+------------------------------------------+---------------------+
| sequence | abbreviation | formula for n-th element | first four elements |
+------------|--------------+------------------------------------------|---------------------|
| fibonacci | fib | a[n] = a[n-1] + a[n-2] | 0, 0, 0, 1 |
| jacobsthal | jac | a[n] = a[n-1] + 2 * a[n-2] | 0, 0, 0, 1 |
| padovan | pad | a[n] = a[n-2] + a[n-3] | 0, 1, 0, 0 |
| pell | pel | a[n] = 2 * a[n-1] + a[n-2] | 0, 0, 0, 1 |
| tetranacci | tet | a[n] = a[n-1] + a[n-2] + a[n-3] + a[n-4] | 0, 0, 0, 1 |
| tribonacci | tri | a[n] = a[n-1] + a[n-2] + a[n-3] | 0, 0, 0, 1 |
+------------+--------------+------------------------------------------+---------------------+
```
## Example
```
zozonacci(["fib", "tri"], 7) == [0, 0, 0, 1, 1, 2, 3]
Explanation:
b d
/-----\/----\
[0, 0, 0, 1, 1, 2, 3]
\--------/
| \--------/
a c
a - [0, 0, 0, 1] as "fib" is the first abbreviation
b - 5th element is 1 as the 1st element of the pattern is "fib": 1 = 0 + 1
c - 6th element is 2 as the 2nd element of the pattern is "tri": 2 = 0 + 1 + 1
d - 7th element is 3 as the 3rd element of the pattern is "fib" (see rule no. 5): 3 = 2 + 1
```
## Sequences
* [fibonacci](https://oeis.org/A000045) : 0, 1, 1, 2, 3 ...
* [padovan](https://oeis.org/A000931): 1, 0, 0, 1, 0 ...
* [jacobsthal](https://oeis.org/A001045): 0, 1, 1, 3, 5 ...
* [pell](https://oeis.org/A000129): 0, 1, 2, 5, 12 ...
* [tribonacci](https://oeis.org/A000073): 0, 0, 1, 1, 2 ...
* [tetranacci](https://oeis.org/A000078): 0, 0, 0, 1, 1 ... | from itertools import cycle
def zozonacci(seq, n):
if not n or not seq:return []
common = {1: [0, 1, 0, 0], 0: [0, 0, 0, 1]}
ini = common[seq[0] == "pad"]
if n<=4:return ini[:n]
fib = lambda:sum(ini[-2:])
jac = lambda:ini[-1] + 2 * ini[-2]
pad = lambda:sum(ini[-3:-1])
pel = lambda:2 * ini[-1] + ini[-2]
tet = lambda:sum(ini[-4:])
tri = lambda:sum(ini[-3:])
for i in cycle(seq):
ini.append(locals()[i]())
if len(ini) == n : return ini | from itertools import cycle
def zozonacci(seq, n):
if not n or not seq:return []
common = {1: [0, 1, 0, 0], 0: [0, 0, 0, 1]}
ini = common[seq[0] == "pad"]
if n<=4:return ini[:n]
fib = lambda:sum(ini[-2:])
jac = lambda:ini[-1] + 2 * ini[-2]
pad = lambda:sum(ini[-3:-1])
pel = lambda:2 * ini[-1] + ini[-2]
tet = lambda:sum(ini[-4:])
tri = lambda:sum(ini[-3:])
for i in cycle(seq):
ini.append(locals()[i]())
if len(ini) == n : return ini | train | APPS_structured |
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.
-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.
-----Output:-----
For each test case, output as the pattern.
-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$
-----Sample Input:-----
2
2
4
-----Sample Output:-----
2
21
210
21
2
4
43
432
4321
43210
4321
432
43
4
-----EXPLANATION:-----
No need, else pattern can be decode easily. | for _ in range(int(input())):
n=int(input())
for i in range(n+1):
k=n
for j in range(1,n-i+1):
print(' ',end='')
for j in range(i+1):
print(k,end='')
k-=1
print()
for i in range(n-1,-1,-1):
k=n
for j in range(1,n-i+1):
print(' ',end='')
for j in range(i+1):
print(k,end='')
k-=1
print() | for _ in range(int(input())):
n=int(input())
for i in range(n+1):
k=n
for j in range(1,n-i+1):
print(' ',end='')
for j in range(i+1):
print(k,end='')
k-=1
print()
for i in range(n-1,-1,-1):
k=n
for j in range(1,n-i+1):
print(' ',end='')
for j in range(i+1):
print(k,end='')
k-=1
print() | train | APPS_structured |
Given the array orders, which represents the orders that customers have done in a restaurant. More specifically orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the name of the customer, tableNumberi is the table customer sit at, and foodItemi is the item customer orders.
Return the restaurant's “display table”. The “display table” is a table whose row entries denote how many of each food item each table ordered. The first column is the table number and the remaining columns correspond to each food item in alphabetical order. The first row should be a header whose first column is “Table”, followed by the names of the food items. Note that the customer names are not part of the table. Additionally, the rows should be sorted in numerically increasing order.
Example 1:
Input: orders = [["David","3","Ceviche"],["Corina","10","Beef Burrito"],["David","3","Fried Chicken"],["Carla","5","Water"],["Carla","5","Ceviche"],["Rous","3","Ceviche"]]
Output: [["Table","Beef Burrito","Ceviche","Fried Chicken","Water"],["3","0","2","1","0"],["5","0","1","0","1"],["10","1","0","0","0"]]
Explanation:
The displaying table looks like:
Table,Beef Burrito,Ceviche,Fried Chicken,Water
3 ,0 ,2 ,1 ,0
5 ,0 ,1 ,0 ,1
10 ,1 ,0 ,0 ,0
For the table 3: David orders "Ceviche" and "Fried Chicken", and Rous orders "Ceviche".
For the table 5: Carla orders "Water" and "Ceviche".
For the table 10: Corina orders "Beef Burrito".
Example 2:
Input: orders = [["James","12","Fried Chicken"],["Ratesh","12","Fried Chicken"],["Amadeus","12","Fried Chicken"],["Adam","1","Canadian Waffles"],["Brianna","1","Canadian Waffles"]]
Output: [["Table","Canadian Waffles","Fried Chicken"],["1","2","0"],["12","0","3"]]
Explanation:
For the table 1: Adam and Brianna order "Canadian Waffles".
For the table 12: James, Ratesh and Amadeus order "Fried Chicken".
Example 3:
Input: orders = [["Laura","2","Bean Burrito"],["Jhon","2","Beef Burrito"],["Melissa","2","Soda"]]
Output: [["Table","Bean Burrito","Beef Burrito","Soda"],["2","1","1","1"]]
Constraints:
1 <= orders.length <= 5 * 10^4
orders[i].length == 3
1 <= customerNamei.length, foodItemi.length <= 20
customerNamei and foodItemi consist of lowercase and uppercase English letters and the space character.
tableNumberi is a valid integer between 1 and 500. | class Solution:
def displayTable(self, orders: List[List[str]]) -> List[List[str]]:
table = []
output = [[]]
temp = []
for i in range(len(orders)):
if orders[i][1] not in table:
table.append(orders[i][1])
for j in range(len(table)):
temp.append(int(table[j]))
temp = sorted(temp)
temp2 = []
for k in range(len(table)):
temp2.append(str(temp[k]))
output.append(temp2)
temp2 = []
for l in range(len(orders)):
if orders[l][2] not in output[0]:
output[0].append(orders[l][2])
temp2 = sorted(output[0])
output[0] = [\"Table\"]+temp2
for r in range(1,len(output)):
for n in range(len(output[0])-1):
output[r].append(\"0\")
for m in range(len(orders)):
tab = int(orders[m][1])
idxt = temp.index(tab)+1
meal = orders[m][2]
idxm = output[0].index(meal)
stack = int(output[idxt][idxm])
stack += 1
output[idxt][idxm] = str(stack)
return output | class Solution:
def displayTable(self, orders: List[List[str]]) -> List[List[str]]:
table = []
output = [[]]
temp = []
for i in range(len(orders)):
if orders[i][1] not in table:
table.append(orders[i][1])
for j in range(len(table)):
temp.append(int(table[j]))
temp = sorted(temp)
temp2 = []
for k in range(len(table)):
temp2.append(str(temp[k]))
output.append(temp2)
temp2 = []
for l in range(len(orders)):
if orders[l][2] not in output[0]:
output[0].append(orders[l][2])
temp2 = sorted(output[0])
output[0] = [\"Table\"]+temp2
for r in range(1,len(output)):
for n in range(len(output[0])-1):
output[r].append(\"0\")
for m in range(len(orders)):
tab = int(orders[m][1])
idxt = temp.index(tab)+1
meal = orders[m][2]
idxm = output[0].index(meal)
stack = int(output[idxt][idxm])
stack += 1
output[idxt][idxm] = str(stack)
return output | train | APPS_structured |
## Task:
You have to write a function `pattern` which returns the following Pattern(See Examples) upto n number of rows.
* Note:```Returning``` the pattern is not the same as ```Printing``` the pattern.
### Rules/Note:
* The pattern should be created using only unit digits.
* If `n < 1` then it should return "" i.e. empty string.
* `The length of each line is same`, and is equal to the number of characters in a line i.e `n`.
* Range of Parameters (for the sake of CW Compiler) :
+ `n ∈ (-50,150]`
### Examples:
+ pattern(8):
88888888
87777777
87666666
87655555
87654444
87654333
87654322
87654321
+ pattern(17):
77777777777777777
76666666666666666
76555555555555555
76544444444444444
76543333333333333
76543222222222222
76543211111111111
76543210000000000
76543210999999999
76543210988888888
76543210987777777
76543210987666666
76543210987655555
76543210987654444
76543210987654333
76543210987654322
76543210987654321
[List of all my katas]("http://www.codewars.com/users/curious_db97/authored") | def pattern(n):
return "\n".join("".join(str(max(r, c) % 10) for c in range(n, 0, -1)) for r in range(n, 0, -1))
| def pattern(n):
return "\n".join("".join(str(max(r, c) % 10) for c in range(n, 0, -1)) for r in range(n, 0, -1))
| train | APPS_structured |
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example "Aa" is not considered a palindrome here.
Note:
Assume the length of given string will not exceed 1,010.
Example:
Input:
"abccccdd"
Output:
7
Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7. | class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
dic = {}
for ss in s:
dic[ss] = dic.get(ss, 0) + 1
res = 0
for _, value in list(dic.items()):
res += (value//2)*2
if res < len(s):
res += 1
return res
| class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
dic = {}
for ss in s:
dic[ss] = dic.get(ss, 0) + 1
res = 0
for _, value in list(dic.items()):
res += (value//2)*2
if res < len(s):
res += 1
return res
| train | APPS_structured |
The Golomb sequence $G_1, G_2, \ldots$ is a non-decreasing integer sequence such that for each positive integer $n$, $G_n$ is the number of occurrences of $n$ in this sequence. The first few elements of $G$ are $[1, 2, 2, 3, 3, 4, 4, 4, 5, \ldots]$. Do you know the recurrence relation for the Golomb sequence? It is $G_1 = 1$ and $G_{n+1} = 1+G_{n+1-G_{G_n}}$ for each $n \ge 1$. A self-describing sequence, isn't it?
Mr. Strange wants to learn CP, so he asked Chef, who is one of the best competitive programmers in the world, to teach him. Chef decided to test his ability by giving him the following task.
Find the sum of squares of the $L$-th through $R$-th term of the Golomb sequence, i.e. $S = \sum_{i=L}^R G_i^2$. Since the sum can be quite large, compute it modulo $10^9+7$.
Can you help Mr. Strange carry out this task given to him by his teacher?
-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains two space-separated integers $L$ and $R$.
-----Output-----
For each test case, print a single line containing one integer $S$ modulo $10^9+7$.
-----Constraints-----
- $1 \le T \le 10^5$
- $1 \le L \le R \le 10^{10}$
-----Subtasks-----
Subtask #1 (50 points):
- $T \le 10^2$
- $R \le 10^9$
Subtask #2 (50 points): original constraints
-----Example Input-----
3
1 5
2 4
100 100
-----Example Output-----
27
17
441
-----Explanation-----
Example case 1: $1^2 + 2^2 + 2^2 + 3^2 + 3^2 = 27$
Example case 2: $2^2 + 2^2 + 3^2 = 17$
Example case 3: $21^2 = 441$ | '''
Name : Jaymeet Mehta
codechef id :mj_13
Problem :
'''
from sys import stdin,stdout
import math
from bisect import bisect_left
mod=1000000007
def mul(a,b):
nonlocal mod
return ((a%mod)*(b%mod))%mod
def add(a,b):
nonlocal mod
return ((a%mod)+(b%mod))%mod
g=[0,1]
pre=[0,1]
ans=[0,1]
i=2
while(True):
g.append(1+g[i-g[g[i-1]]])
pre.append(pre[i-1]+g[i])
ans.append(add(ans[i-1],mul(mul(i,i),g[i])))
if pre[i]>10000000000:
break
i+=1
test=int(stdin.readline())
for _ in range(test):
l,r= list(map(int,stdin.readline().split()))
sm1,sm2=0,0
if l==1:
sm1=0
else:
l-=1
tl=bisect_left(pre,l)
sm1=add(ans[tl-1],mul(l-pre[tl-1],mul(tl,tl)))
tr=bisect_left(pre,r)
sm2=add(ans[tr-1],mul(r-pre[tr-1],mul(tr,tr)))
print((sm2-sm1)%mod)
| '''
Name : Jaymeet Mehta
codechef id :mj_13
Problem :
'''
from sys import stdin,stdout
import math
from bisect import bisect_left
mod=1000000007
def mul(a,b):
nonlocal mod
return ((a%mod)*(b%mod))%mod
def add(a,b):
nonlocal mod
return ((a%mod)+(b%mod))%mod
g=[0,1]
pre=[0,1]
ans=[0,1]
i=2
while(True):
g.append(1+g[i-g[g[i-1]]])
pre.append(pre[i-1]+g[i])
ans.append(add(ans[i-1],mul(mul(i,i),g[i])))
if pre[i]>10000000000:
break
i+=1
test=int(stdin.readline())
for _ in range(test):
l,r= list(map(int,stdin.readline().split()))
sm1,sm2=0,0
if l==1:
sm1=0
else:
l-=1
tl=bisect_left(pre,l)
sm1=add(ans[tl-1],mul(l-pre[tl-1],mul(tl,tl)))
tr=bisect_left(pre,r)
sm2=add(ans[tr-1],mul(r-pre[tr-1],mul(tr,tr)))
print((sm2-sm1)%mod)
| train | APPS_structured |
In a fictitious city of CODASLAM there were many skyscrapers. The mayor of the city decided to make the city beautiful and for this he decided to arrange the skyscrapers in descending order of their height, and the order must be strictly decreasing but he also didn’t want to waste much money so he decided to get the minimum cuts possible. Your job is to output the minimum value of cut that is possible to arrange the skyscrapers in descending order.
-----Input-----
*First line of input is the number of sky-scrappers in the city
*Second line of input is the height of the respective sky-scrappers
-----Output-----
* Your output should be the minimum value of cut required to arrange these sky-scrappers in descending order.
-----Example-----
Input:
5
1 2 3 4 5
Output:
8
By:
Chintan,Asad,Ashayam,Akanksha | import sys
num=int(sys.stdin.readline())
s=sys.stdin.readline().split()
sky=list(map(int,s))
sky.reverse()
cuts=0
change=0
t=False
i=1
while i<len(sky):
if sky[i]<=sky[i-1]:
for j in range(i-1,-1,-1):
if sky[j]<=sky[i]-(i-j):
break
else:
change+=sky[j]-(sky[i]-(i-j))
if change>=sky[i]:
change=sky[i]
t=True
break
cuts+=change
if t:
del sky[i]
t=False
i-=1
else:
for j in range(i-1,-1,-1):
if sky[j]<sky[i]-(i-j):
break
else:
sky[j]=sky[i]-(i-j)
i+=1
change=0
print(cuts) | import sys
num=int(sys.stdin.readline())
s=sys.stdin.readline().split()
sky=list(map(int,s))
sky.reverse()
cuts=0
change=0
t=False
i=1
while i<len(sky):
if sky[i]<=sky[i-1]:
for j in range(i-1,-1,-1):
if sky[j]<=sky[i]-(i-j):
break
else:
change+=sky[j]-(sky[i]-(i-j))
if change>=sky[i]:
change=sky[i]
t=True
break
cuts+=change
if t:
del sky[i]
t=False
i-=1
else:
for j in range(i-1,-1,-1):
if sky[j]<sky[i]-(i-j):
break
else:
sky[j]=sky[i]-(i-j)
i+=1
change=0
print(cuts) | train | APPS_structured |
Consider the word `"abode"`. We can see that the letter `a` is in position `1` and `b` is in position `2`. In the alphabet, `a` and `b` are also in positions `1` and `2`. Notice also that `d` and `e` in `abode` occupy the positions they would occupy in the alphabet, which are positions `4` and `5`.
Given an array of words, return an array of the number of letters that occupy their positions in the alphabet for each word. For example,
```
solve(["abode","ABc","xyzD"]) = [4, 3, 1]
```
See test cases for more examples.
Input will consist of alphabet characters, both uppercase and lowercase. No spaces.
Good luck!
If you like this Kata, please try:
[Last digit symmetry](https://www.codewars.com/kata/59a9466f589d2af4c50001d8)
[Alternate capitalization](https://www.codewars.com/kata/59cfc000aeb2844d16000075)
~~~if:fortran
## Fortran-Specific Notes
Due to how strings and arrays work in Fortran, some of the strings in the input array will inevitably contain trailing whitespace. **For this reason, please [trim](https://gcc.gnu.org/onlinedocs/gcc-4.3.4/gfortran/TRIM.html) your input strings before processing them.**
~~~ | def solve(arr):
abc = "abcdefghijklmnopqrstuvwxyz"
res = []
for word in arr:
count = 0
word = word.lower()
for i, letter in enumerate(word):
if i == abc.index(letter):
count += 1
res.append(count)
return res
| def solve(arr):
abc = "abcdefghijklmnopqrstuvwxyz"
res = []
for word in arr:
count = 0
word = word.lower()
for i, letter in enumerate(word):
if i == abc.index(letter):
count += 1
res.append(count)
return res
| train | APPS_structured |
# Description:
Move all exclamation marks to the end of the sentence
# Examples
```
remove("Hi!") === "Hi!"
remove("Hi! Hi!") === "Hi Hi!!"
remove("Hi! Hi! Hi!") === "Hi Hi Hi!!!"
remove("Hi! !Hi Hi!") === "Hi Hi Hi!!!"
remove("Hi! Hi!! Hi!") === "Hi Hi Hi!!!!"
``` | def remove(s):
return s.replace('!','') + s.count('!') * '!' | def remove(s):
return s.replace('!','') + s.count('!') * '!' | train | APPS_structured |
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. | class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
L, res, last = -1, 0, {}
for R, char in enumerate(s):
if char in last and last[char] > L:
L = last[char]
elif R-L > res:
res = R-L
last[char] = R
return res | class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
L, res, last = -1, 0, {}
for R, char in enumerate(s):
if char in last and last[char] > L:
L = last[char]
elif R-L > res:
res = R-L
last[char] = R
return res | train | APPS_structured |
Given a list of dominoes, dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (a==c and b==d), or (a==d and b==c) - that is, one domino can be rotated to be equal to another domino.
Return the number of pairs (i, j) for which 0 <= i < j < dominoes.length, and dominoes[i] is equivalent to dominoes[j].
Example 1:
Input: dominoes = [[1,2],[2,1],[3,4],[5,6]]
Output: 1
Constraints:
1 <= dominoes.length <= 40000
1 <= dominoes[i][j] <= 9 | class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
from collections import defaultdict
counter = defaultdict(int)
for domino in dominoes:
counter[tuple(sorted(domino))] +=1
return sum([v*(v-1)//2 for v in counter.values()]) | class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
from collections import defaultdict
counter = defaultdict(int)
for domino in dominoes:
counter[tuple(sorted(domino))] +=1
return sum([v*(v-1)//2 for v in counter.values()]) | train | APPS_structured |