Solve in Python:
Write a program that, given a word, computes the scrabble score for that word.

## Letter Values

You'll need these:

```
Letter                           Value
A, E, I, O, U, L, N, R, S, T       1
D, G                               2
B, C, M, P                         3
F, H, V, W, Y                      4
K                                  5
J, X                               8
Q, Z                               10
```

```if:ruby,javascript,cfml
There will be a preloaded hashtable `$dict` with all these values: `$dict["E"] == 1`.
```
```if:haskell
There will be a preloaded list of `(Char, Int)` tuples called `dict` with all these values.
```
```if:python
There will be a preloaded dictionary `dict_scores` with all these values: `dict_scores["E"] == 1`
```

## Examples
```
"cabbage" --> 14
```

"cabbage" should be scored as worth 14 points:

- 3 points for C
- 1 point for A, twice
- 3 points for B, twice
- 2 points for G
- 1 point for E

And to total:

`3 + 2*1 + 2*3 + 2 + 1` = `3 + 2 + 6 + 3` = `14`

Empty string should return `0`. The string can contain spaces and letters (upper and lower case), you should calculate the scrabble score only of the letters in that string.

```
""           --> 0
"STREET"    --> 6
"st re et"    --> 6
"ca bba g  e" --> 14
```

def scrabble_score(st):
    x = 0
    for y in st:
        if 'a' in y.lower():
            x += 1
        if 'e' in y.lower():
            x += 1
        if 'i' in y.lower():
            x += 1
        if 'o' in y.lower():
            x += 1
        if 'u' in y.lower():
            x += 1
        if 'l' in y.lower():
            x += 1
        if 'n' in y.lower():
            x += 1
        if 'r' in y.lower():
            x += 1
        if 's' in y.lower():
            x += 1
        if 't' in y.lower():
            x += 1
        if 'd' in y.lower():
            x += 2
        if 'g' in y.lower():
            x += 2
        if 'b' in y.lower():
            x += 3
        if 'c' in y.lower():
            x += 3
        if 'm' in y.lower():
            x += 3
        if 'p' in y.lower():
            x += 3
        if 'f' in y.lower():
            x += 4
        if 'h' in y.lower():
            x += 4
        if 'v' in y.lower():
            x += 4
        if 'w' in y.lower():
            x += 4
        if 'y' in y.lower():
            x += 4
        if 'k' in y.lower():
            x += 5
        if 'j' in y.lower():
            x += 8
        if 'x' in y.lower():
            x += 8
        if 'q' in y.lower():
            x += 10
        if 'z' in y.lower():
            x += 10
    return x


Solve in Python:
Write a program to check whether a given number is an ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.

Example 1:

Input: 6
Output: true
Explanation: 6 = 2 × 3

Example 2:

Input: 8
Output: true
Explanation: 8 = 2 × 2 × 2

Example 3:

Input: 14
Output: false
Explanation: 14 is not ugly since it includes another prime factor 7.

Note:

       1 is typically treated as an ugly number.
       Input is within the 32-bit signed integer range: [−231,  231 − 1].

class Solution:
     def isUgly(self, num):
         """
         :type num: int
         :rtype: bool
         """
         if num<1:
             return False
         if num==1:
             return True
         while num%2==0 or num%3==0 or num%5==0:
             if num%2==0:
                 num/=2
             elif num%3==0:
                 num/=3
             else:
                 num/=5
             if num==1:
                 return True
         return False


Solve in Python:
Write a program to check whether a triangle is valid or not, when the three angles of the triangle are the inputs. A triangle is valid if the sum of all the three angles is equal to 180 degrees.

-----Input-----

The first line contains an integer T, the total number of testcases. Then T lines follow, each line contains three angles  A, B and C, of the triangle separated by space.

-----Output-----
For each test case, display 'YES' if the triangle is valid, and 'NO', if it is not, in a new line.

-----Constraints-----
- 1 ≤ T ≤ 1000
- 1 ≤ A,B,C ≤ 180

-----Example-----
Input

3
40 40 100
45 45 90
180 1 1
Output

YES
YES
NO

# cook your dish here
for _ in range(int(input())):
    l=list(map(int,input().split(' ')))
    if(sum(l)==180):
        print('YES')
    else:
        print('NO')


Solve in Python:
Write a program to determine if a string contains only unique characters.
Return true if it does and false otherwise.

The string may contain any of the 128 ASCII characters.
Characters are case-sensitive, e.g. 'a' and 'A' are considered different characters.

def has_unique_chars(str):
  return len(set(str))==len(str)


Solve in Python:
Write a program to determine if two numbers are coprime. A pair of numbers are coprime if their greatest shared factor is 1. For example:
```
20 and 27
Factors of 20: 1, 2, 4, 5, 10, 20
Factors of 27: 1, 3, 9, 27
Greatest shared factor: 1
20 and 27 are coprime```
An example of two numbers that are not coprime:
```
12 and 39
Factors of 12: 1, 2, 3, 4, 6, 12
Factors of 39: 1, 3, 13, 39
Greatest shared factor: 3
12 and 39 are not coprime```
If the two inputs are coprime, your program should return true. If they are not coprime, your program should return false.

The inputs will always be two positive integers between 2 and 99.

def coprime(n,m):
    while n*m:
        if n>m: n %= m
        else: m %= n
    return max(n,m)

def are_coprime(n,m):
    return (coprime(n,m) == 1)


Solve in Python:
Write a program to find the factorial value of any number entered by the user.

-----Input-----

The first line contains an integer T, the total number of testcases. Then T lines follow, each line contains an integer N.

-----Output-----
For each test case, display the factorial of the given number N in a new line.

-----Constraints-----
- 1 ≤ T ≤ 1000
- 0 ≤ N ≤ 20

-----Example-----
Input
3
3
4
5

Output

6
24
120

# cook your dish here
try:
    t=int(input())

    for i in range(0,t):
        n=int(input())
        fact=1

        while(n!=0):
            fact=fact*n
            n-=1
        print(fact)
except:
    pass


Solve in Python:
Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.

Example:

Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note:

       1 is typically treated as an ugly number.
       n does not exceed 1690.

class Solution:
     res=[1]
     idx=[0,0,0]
     def nthUglyNumber(self, n):
         """
         :type n: int
         :rtype: int
         """
         if n<=0:
             return None
         idx2,idx3,idx5=Solution.idx
         while len(Solution.res)<n:
             Solution.res.append(min(Solution.res[idx2]*2,Solution.res[idx3]*3,Solution.res[idx5]*5))
             while idx2<len(Solution.res) and Solution.res[idx2]*2<=Solution.res[-1]:
                 idx2+=1
             while idx3<len(Solution.res) and Solution.res[idx3]*3<=Solution.res[-1]:
                 idx3+=1
             while idx5<len(Solution.res) and Solution.res[idx5]*5<=Solution.res[-1]:
                 idx5+=1
         Solution.idx=[idx2,idx3,idx5]
         return Solution.res[n-1]


Solve in Python:
Write a program to find the remainder when an integer A is divided by an integer B.

-----Input-----

The first line contains an integer T, the total number of test cases. Then T lines follow, each line contains two Integers A and B.

-----Output-----
For each test case, find the remainder when A is divided by  B, and display it in a new line.

-----Constraints-----
- 1 ≤ T ≤ 1000
- 1 ≤ A,B ≤ 10000

-----Example-----
Input
3
1 2
100 200
40 15

Output
1
100
10

n= int (eval(input()))
for i in range (0,n):
    a,b=list(map(int,input().split()))
    r=a%b
    print(r)


Solve in Python:
Write a program to find the n-th ugly number.
Ugly numbers are positive integers which are divisible by a or b or c.

Example 1:
Input: n = 3, a = 2, b = 3, c = 5
Output: 4
Explanation: The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4.
Example 2:
Input: n = 4, a = 2, b = 3, c = 4
Output: 6
Explanation: The ugly numbers are 2, 3, 4, 6, 8, 9, 10, 12... The 4th is 6.

Example 3:
Input: n = 5, a = 2, b = 11, c = 13
Output: 10
Explanation: The ugly numbers are 2, 4, 6, 8, 10, 11, 12, 13... The 5th is 10.

Example 4:
Input: n = 1000000000, a = 2, b = 217983653, c = 336916467
Output: 1999999984

Constraints:

1 <= n, a, b, c <= 10^9
1 <= a * b * c <= 10^18
It's guaranteed that the result will be in range [1, 2 * 10^9]

class Solution:
    def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int:

        def isEnough(num):
            total = num//a + num//b + num//c - num//ab - num//ac - num//bc + num//abc
            return total >= n

        ab = a*b // math.gcd(a,b)
        ac = a*c // math.gcd(a,c)
        bc = b*c // math.gcd(b,c)
        abc = a*bc // math.gcd(a,bc)

        left = 1
        right = 10 ** 10
        while left < right:
            mid = left + (right - left) // 2
            if isEnough(mid):
                right = mid
            else:
                left = mid + 1
        return left


Solve in Python:
Write a program to obtain a number $(N)$ from the user and display whether the number is a one digit number, 2 digit number, 3 digit number or more than 3 digit number

-----Input:-----
- First line will contain the number $N$,

-----Output:-----
Print "1" if N is a 1 digit number.
Print "2" if N is a 2 digit number.
Print "3" if N is a 3 digit number.
Print "More than 3 digits" if N has more than 3 digits.

-----Constraints-----
- $0 \leq N \leq 1000000$

-----Sample Input:-----
9

-----Sample Output:-----
1

# cook your dish here
n=input()
if(len(n)<4):
 print(str(len(n)))
else:
 print("More than 3 digits")


Solve in Python:
Write a program to obtain a number $N$ and increment its value by 1 if the number is divisible by 4 $otherwise$ decrement its value by 1.

-----Input:-----
- First line will contain a number $N$.

-----Output:-----
Output a single line, the new value of the number.

-----Constraints-----
- $0 \leq N \leq 1000$

-----Sample Input:-----
5

-----Sample Output:-----
4

-----EXPLANATION:-----
Since 5 is not divisible by 4 hence, its value is decreased by 1.

# cook your dish here
n=int(input())
if(n%4==0):
    print(n+1)
else:
    print(n-1)


Solve in Python:
Write a program to solve a Sudoku puzzle by filling the empty cells.

A sudoku solution must satisfy all of the following rules:

       Each of the digits 1-9 must occur exactly once in each row.
       Each of the digits 1-9 must occur exactly once in each column.
       Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.

Empty cells are indicated by the character '.'.

A sudoku puzzle...

...and its solution numbers marked in red.

Note:

       The given board contain only digits 1-9 and the character '.'.
       You may assume that the given Sudoku puzzle will have a single unique solution.
       The given board size is always 9x9.

class Solution:
     def reduceSingleOption(self, board, emptyGrid, valid):
         m = 1
         while m == 1:
             m = 10
             for k in range(len(emptyGrid) - 1, -1, -1):
                 i, j = emptyGrid[k]
                 option = set.intersection(valid[i],
                                           valid[j + 9],
                                           valid[(i // 3) * 3 + j // 3 + 18])
                 if not option:
                     return
                 if len(option) < m:
                     m = len(option)
                 if len(option) == 1:
                     option = option.pop()
                     board[i][j] = str(option)
                     emptyGrid.pop(k)
                     valid[i].remove(option)
                     valid[j + 9].remove(option)
                     valid[(i // 3) * 3 + j // 3 + 18].remove(option)

     def dfs(self, board, emptyGrid, valid, ans):
         if len(ans) == len(emptyGrid):
             return
         i, j = emptyGrid[len(ans)]
         options = set.intersection(valid[i],
                                    valid[j + 9],
                                    valid[(i // 3) * 3 + j // 3 + 18])
         if len(options) == 0:
             return
         else:
             for temp in options:
                 print(i, j, temp)
                 ans.append(temp)
                 valid[i].remove(temp)
                 valid[j + 9].remove(temp)
                 valid[(i // 3) * 3 + j // 3 + 18].remove(temp)
                 self.dfs(board, emptyGrid, valid, ans)
                 if len(ans) == len(emptyGrid):
                     break
                 temp = ans.pop()
                 valid[i].add(temp)
                 valid[j + 9].add(temp)
                 valid[(i // 3) * 3 + j // 3 + 18].add(temp)

     def solveSudoku(self, board):
         """
         :type board: List[List[str]]
         :rtype: void Do not return anything, modify board in-place instead.
         """
         valid = [set(range(1, 10)) for _ in...


Solve in Python:
Write a program to take two numbers as input and print their difference if the first number is greater than the second number otherwise$otherwise$ print their sum.

-----Input:-----
- First line will contain the first number (N1$N1$)
- Second line will contain the second number (N2$N2$)

-----Output:-----
Output a single line containing the difference of 2 numbers (N1−N2)$(N1 - N2)$ if the first number is greater than the second number otherwise output their sum (N1+N2)$(N1 + N2)$.

-----Constraints-----
- −1000≤N1≤1000$-1000 \leq N1 \leq 1000$
- −1000≤N2≤1000$-1000 \leq N2 \leq 1000$

-----Sample Input:-----
82
28

-----Sample Output:-----
54

N1,N2=int(input()),int(input())
if N1>N2 :
    print(N1-N2)
else :
    print(N1+N2)


Solve in Python:
Write a program, which takes an integer N and if the number is less than 10 then display "Thanks for helping Chef!" otherwise print "-1".

-----Input-----

The first line contains an integer T, total number of testcases. Then follow T lines, each line contains an integer N.

-----Output-----
For each test case, output the given string or -1 depending on conditions, in a new line.

-----Constraints-----
- 1 ≤ T ≤ 1000
- -20 ≤ N ≤ 20

-----Example-----
Input
3
1
12
-5
Output
Thanks for helping Chef!
-1
Thanks for helping Chef!

# cook your dish here
t=int(input())
for i in range(t):
    n=int(input())
    if n<10:
        print("Thanks for helping Chef!")
    else:
        print("-1")


Solve in Python:
Write a regex to validate a 24 hours time string.
See examples to figure out what you should check for:

Accepted:
01:00 - 1:00

Not accepted:

24:00

You should check for correct length and no spaces.

import re

def validate_time(time):
    return bool(re.match(r'([01]?[0-9]|2[0-3]):[0-5][0-9]', time))


Solve in Python:
Write a simple function that takes polar coordinates (an angle in degrees and a radius) and returns the equivalent cartesian coordinates (rouded to 10 places).

```
For example:

coordinates(90,1)
=> (0.0, 1.0)

coordinates(45, 1)
=> (0.7071067812, 0.7071067812)
```

from math import cos, sin, radians

def coordinates(deg, r, precision=10):
    x, y = r * cos(radians(deg)), r * sin(radians(deg))
    return round(x, precision), round(y, precision)


Solve in Python:
Write a simple parser that will parse and run Deadfish.

Deadfish has 4 commands, each 1 character long:
* `i` increments the value (initially `0`)
* `d` decrements the value
* `s` squares the value
* `o` outputs the value into the return array

Invalid characters should be ignored.

```python
parse("iiisdoso")  ==>  [8, 64]
```


Solve in Python:
Write a simple regex to validate a username. Allowed characters are:

- lowercase letters,
- numbers,
- underscore

Length should be between 4 and 16 characters (both included).

import re
def validate_usr(username):
    return re.match("^[a-z0-9_]{4,16}$", username) is not None


Solve in Python:
Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.

```python
move_zeros([False,1,0,1,2,0,1,3,"a"]) # returns[False,1,1,2,1,3,"a",0,0]
```

def move_zeros(array):
    without_zeros = list(filter(lambda n: not n == 0 or n is False, array))
    for i in range(len(array) - len(without_zeros)):
        without_zeros.append(0)
    return without_zeros


Solve in Python:
Write an algorithm to determine if a number is "happy".

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

Example:

Input: 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

class Solution:
     def isHappy(self, n):
         """
         :type n: int
         :rtype: bool
         """
         def next(n):
             res = 0
             while n > 0:
                 n, lsd = n // 10, n % 10
                 res += lsd * lsd
             return res

         seen = set()
         while True:
             seen.add(n)
             n = next(n)
             if n == 1:
                 return True
             if n in seen:
                 return False


Solve in Python:
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

       Integers in each row are sorted from left to right.
       The first integer of each row is greater than the last integer of the previous row.

Example 1:

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 3
Output: true

Example 2:

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 13
Output: false

class Solution:
     def searchMatrix(self, matrix, target):
         """
         :type matrix: List[List[int]]
         :type target: int
         :rtype: bool
         """
         print((len(matrix)))
         if(len(matrix)==0):
             return False
         if len(matrix)==1 and len(matrix[0])==0:
             return False
         existFlag=0
         last=len(matrix[0])-1
         for i in range(len(matrix)):
             if matrix[i][last]<target:
                 continue
             else:
                 print("falg set to 1")
                 existFlag=1
                 break
         if existFlag==1:
             #existFlag=0
             print("yes it is 1")
             for j in range(last,-1,-1):
                 print(("j= ",j))
                 if matrix[i][j]==target:
                     return True
         return False


Solve in Python:
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

       Integers in each row are sorted in ascending from left to right.
       Integers in each column are sorted in ascending from top to bottom.

Example:

Consider the following matrix:

[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]

Given target = 5, return true.

Given target = 20, return false.

class Solution:
     def searchMatrix(self, matrix, target):
         """
         :type matrix: List[List[int]]
         :type target: int
         :rtype: bool
         """
         if len(matrix) == 0 or len(matrix[0]) == 0:
             return False
         m = 0
         n = len(matrix[0]) - 1
         while m < len(matrix) and n >= 0:
             if target == matrix[m][n]:
                 return True
             elif target < matrix[m][n]:
                 n -= 1
             elif target > matrix[m][n]:
                 m += 1
         return False


Solve in Python:
Write function RemoveExclamationMarks which removes all exclamation marks from a given string.

def remove_exclamation_marks(s):
    a = ''
    for i in s:
        if i in '!':
            pass
        else:
            a += i
    return a


Solve in Python:
Write function ```splitSentence``` which will create a list of strings from a string.

Example:

```"hello world" -> ["hello", "world"]```

def splitSentence(s):
    sum = ""
    result = []
    for i in s:
        if i == " ":
            result.append(sum)
            sum = ""
            continue
        sum = sum + i
    result.append(sum)

    return result


Solve in Python:
Write function ```wordsToSentence``` which will create a string from a list of strings, separated by space.

Example:

```["hello", "world"] -> "hello world"```


Solve in Python:
Write function `makeParts` or `make_parts` (depending on your language) that will take an array as argument and the size of the chunk.

Example: if an array of size 123 is given and chunk size is 10 there will be 13 parts, 12 of size 10 and 1 of size 3.

from math import ceil; makeParts=lambda arr, c: [arr[i*c:i*c+c] for i in range(ceil(len(arr)/c))]


Solve in Python:
Write function alternateCase which switch every letter in string from upper to lower and from lower to upper.
E.g: Hello World -> hELLO wORLD

def alternateCase(s):
    newstring =''
    count1 = 0
    count2 = 0
    count3 = 0
    for a in s:
# Checking for lowercase letter and converting to uppercase.
        if (a.isupper()) == True:
            count1+= 1
            newstring+=(a.lower())
# Checking for uppercase letter and converting to lowercase.
        elif (a.islower()) == True:
            count2+= 1
            newstring+=(a.upper())
# Checking for whitespace letter and adding it to the new string as it is.
        elif (a.isspace()) == True:
            count3+= 1
            newstring+= a
    return newstring


Solve in Python:
Write function avg which calculates average of numbers in given list.

codewars = ["a","b","c"]
def find_average(codewars):
    average = (codewars[0]+codewars[1]+codewars[2])/3
    return average


Solve in Python:
Write function bmi that calculates body mass index (bmi = weight / height ^ 2).

if bmi <= 18.5 return "Underweight"

if bmi <= 25.0 return "Normal"

if bmi <= 30.0 return "Overweight"

if bmi > 30 return "Obese"

def bmi(weight, height):
    bmi = weight / height ** 2
    if bmi <= 18.5:
        return 'Underweight'
    elif bmi <= 25:
        return 'Normal'
    elif bmi <= 30:
        return 'Overweight'
    elif bmi > 30:
        return 'Obese'
    else:
        return None


Solve in Python:
Write function describeList which returns "empty" if the list is empty or "singleton" if it contains only one element or "longer"" if more.

def describeList(list):
  if not list: return 'empty'
  if len(list) == 1: return 'singleton'
  if len(list) > 1: return 'longer'


Solve in Python:
Write function heron which calculates the area of a triangle with sides a, b, and c.

Heron's formula: sqrt (s \* (s - a) \* (s - b) \* (s - c)), where s = (a + b + c) / 2.
Output should have 2 digits precision.

import math
def heron(a,b,c):
    s=(a+b+c)/2
    return round(math.sqrt(s*(s-a)*(s-b)*(s - c)),2)


Solve in Python:
Write function isPalindrome that checks if a given string (case insensitive) is a palindrome.

```racket
In Racket, the function is called palindrome?

(palindrome? "nope") ; returns #f
(palindrome? "Yay")  ; returns #t
```

def is_palindrome(s):
    s = s.lower()
    return s == s[::-1]


Solve in Python:
Write function toAcronym which takes a string and make an acronym of it.

Rule of making acronym in this kata:

1. split string to words by space char
2. take every first letter from word in given string
3. uppercase it
4. join them toghether

Eg:

Code wars -> C, w -> C W -> CW

def to_acronym(i):
    return''.join(w[0]for w in i.split()).upper()


Solve in Python:
Write the following function:

```python
def area_of_polygon_inside_circle(circle_radius, number_of_sides):
```

It should calculate the area of a regular polygon of `numberOfSides`, `number-of-sides`, or `number_of_sides` sides inside a circle of radius `circleRadius`, `circle-radius`, or `circle_radius` which passes through all the vertices of the polygon (such circle is called [**circumscribed circle** or **circumcircle**](https://en.wikipedia.org/wiki/Circumscribed_circle)). The answer should be a number rounded to 3 decimal places.

Input :: Output Examples

```python
area_of_polygon_inside_circle(3, 3) # returns 11.691

area_of_polygon_inside_circle(5.8, 7) # returns 92.053

area_of_polygon_inside_circle(4, 5) # returns 38.042
```

def area_of_polygon_inside_circle(r,n):
    import math
    a=(360/(2*n))*(0.017453292519943295)
    b=2*r*math.sin(a)
    c=r*math.cos(a)
    return round((1/2)*(b)*(c)*(n),3)


Solve in Python:
Write the function `resistor_parallel` that receive an undefined number of resistances parallel resistors and return the total resistance.

You can assume that there will be no 0 as parameter.
Also there will be at least 2 arguments.

Formula:
`total = 1 / (1/r1 + 1/r2 + .. + 1/rn)`

Examples:
`resistor_parallel(20, 20)` will return `10.0`
`resistor_parallel(20, 20, 40)` will return `8.0`

def resistor_parallel(*resistors):
    return 1.0 / sum(map(lambda x:1.0/x, resistors))


Solve in Python:
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.

[Image]

There are $n$ cities and $n-1$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $1$ to $n$, and the city $1$ is the capital of the kingdom. So, the kingdom has a tree structure.

As the queen, Linova plans to choose exactly $k$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.

A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).

Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.

In order to be a queen loved by people, Linova wants to choose $k$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?

-----Input-----

The first line contains two integers $n$ and $k$ ($2\le n\le 2 \cdot 10^5$, $1\le k< n$)  — the number of cities and industry cities respectively.

Each of the next $n-1$ lines contains two integers $u$ and $v$ ($1\le u,v\le n$), denoting there is a road connecting city $u$ and city $v$.

It is guaranteed that from any city, you can reach any other city by the roads.

-----Output-----

Print the only line containing a single integer  — the maximum possible sum of happinesses of all envoys.

-----Examples-----
Input
7 4
1 2
1 3
1 4
3 5
3 6
4 7

Output
7
Input
4 1
1 2
1 3
2 4

Output
2
Input
8 5
7 5
1 7
6 1
3 7
8 3
2 1
4 5

Output
9

-----Note-----

[Image]

In the first example, Linova can choose cities $2$, $5$, $6$, $7$ to develop industry, then the happiness of the envoy from city $2$ is...

import sys
input = sys.stdin.readline

n, k = list(map(int, input().split()))

begin = [-1] * n
end = [-1] * n
hurt = [-1] * n

adj = [[] for i in range(n)]
for _ in range(n-1):
    u ,v = list(map(int, input().split()))
    adj[u-1].append(v-1)
    adj[v-1].append(u-1)

hurt[0] = 1
begin[0] = 0
stack = [0]
curr = 1
while stack:
    nex = stack[-1]
    if adj[nex]:
        v = adj[nex].pop()
        if begin[v] == -1:
            begin[v] = curr
            curr += 1
            stack.append(v)
            hurt[v] = len(stack)
    else:
        end[nex] = curr
        stack.pop()

desc = [end[i] - begin[i]-hurt[i] for i in range(n)]
desc.sort(reverse = True)
out = 0
for i in range(n - k):
    out += desc[i]
print(out)


Solve in Python:
Xorgon is an extremely delicious treat formed by the sequence $S$ of binary integers $s_1, s_2,..,s_N$. A really interesting property found in a Xorgon is that the xor of all elements in any contiguous subsequence of length $K$ in $S$ will result in $1$.
Chef has been asked to prepare a Xorgon. However, he has at his disposal a binary sequence $X$ containing the binary integers $x_1, x_2, ...x_N$. To prepare a Xorgon, the chef may flip the value of as many binary digits in $X$ as required.(i.e. turn a $1$ to a $0$ and $0$ to a $1$). Unfortunately, flipping a digit takes a lot of time and the chef has to serve many orders. Can you help the chef calculate the minimum number of flips required to cook a Xorgon from the given $X$?

-----Input:-----
- The first line will contain two space-separated integers $N, K$.
- Next line contains N space-separated integers $x_1, x_2, ...,x_N$.

-----Output:-----
Output in a single line minimum number of flips required to turn $X$ into a Xorgon.

-----Constraints-----
- $1 \leq K \leq N \leq 3*10^6$
- $0 \leq x_i \leq 1$

-----Sample Input:-----
7 5
1 0 0 1 1 1 1

-----Sample Output:-----
1

-----EXPLANATION:-----
Flip the last bit from 1 to 0 to obtain a Xorgon.

# cook your dish here
from sys import stdin,stdout

a0=0
a1=1
n,k=stdin.readline().strip().split(' ')
n,k=int(n),int(k)

arr=list(map(int,stdin.readline().strip().split(' ')))

def solve(n,k,arr):
 sol=[]

 l=0;u=k;

 while l!=u:
   sol.append(arr[l:min(len(arr),u)])
   l=min(l+k,len(arr))
   u=min(u+k,len(arr))

 tiwari=[]
 for i in range(k):
   titi=0
   gao=0
   for j in range(len(sol)):
    if len(sol[j])>i:
     if sol[j][i]==0:
      titi+=1
     else:
      gao+=1
   tiwari.append((titi,gao))

 minflip=(-1,-1)
 ans=0
 ctr=0
 for i in tiwari:
   if i[0]<i[1]:
    ans+=i[0]
    ctr+=(1*a1+a0*a1)*a1
    if i[1]<minflip[0] or minflip[0]==-1:
     minflip=(i[1],i[0])
   else:
    ans+=i[1]
    if i[0]<minflip[0] or minflip[0]==-1:
     minflip=(i[0],i[1])
 #print(ans,ctr)
 #print(tiwari)
 #print(minflip)
 if ctr%2==0:
   ans+=minflip[0]
   ans-=minflip[1]

 stdout.write(str(ans)+"\n")

solve(n,k,arr)


Solve in Python:
Yaroslav is playing a game called "Time". The game has a timer showing the lifespan he's got left. As soon as the timer shows 0, Yaroslav's character dies and the game ends. Also, the game has n clock stations, station number i is at point (x_{i}, y_{i}) of the plane. As the player visits station number i, he increases the current time on his timer by a_{i}. The stations are for one-time use only, so if the player visits some station another time, the time on his timer won't grow.

A player spends d·dist time units to move between stations, where dist is the distance the player has covered and d is some constant. The distance between stations i and j is determined as |x_{i} - x_{j}| + |y_{i} - y_{j}|.

Initially, the player is at station number 1, and the player has strictly more than zero and strictly less than one units of time. At station number 1 one unit of money can increase the time on the timer by one time unit (you can buy only integer number of time units).

Now Yaroslav is wondering, how much money he needs to get to station n. Help Yaroslav. Consider the time to buy and to increase the timer value negligibly small.

-----Input-----

The first line contains integers n and d (3 ≤ n ≤ 100, 10^3 ≤ d ≤ 10^5) — the number of stations and the constant from the statement.

The second line contains n - 2 integers: a_2, a_3, ..., a_{n} - 1 (1 ≤ a_{i} ≤ 10^3). The next n lines contain the coordinates of the stations. The i-th of them contains two integers x_{i}, y_{i} (-100 ≤ x_{i}, y_{i} ≤ 100).

It is guaranteed that no two stations are located at the same point.

-----Output-----

In a single line print an integer — the answer to the problem.

-----Examples-----
Input
3 1000
1000
0 0
0 1
0 3

Output
2000

Input
3 1000
1000
1 0
1 1
1 2

Output
1000

f = lambda: list(map(int, input().split()))
n, d = f()
a = [0] + f() + [0]
p = [f() for i in range(n)]
r = list(range(n))
s = [[d * (abs(p[i][0] - p[j][0]) + abs(p[i][1] - p[j][1])) - a[j] * (i != j) for j in r] for i in r]
for k in r: s = [[min(s[i][j], s[i][k] + s[k][j]) for i in r] for j in r]
print(s[-1][0])


Solve in Python:
Yash likes playing with numbers. He has a challenge for you. Yash gives
you a number that he made by multiplying two numbers. He claims that the
possible sum of the two numbers he multiplied is as minimum as possible. He
challenges you to find that minimum sum.

Formally, for a given value of N, you are required to find the minimum sum of two distinct numbers x and y such that x, y > 0 and xy = N.

-----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.

Each testcase contains single integer N.

-----Output:-----
For each testcase, output minimum x + y such that x*y = N and x,y >0.

-----Constraints :-----
$1 \leq T \leq 100$
$1 < N \leq 10^{12}$

-----Sample Input:-----
1

852140

-----Sample Output:-----
1929

# cook your dish here
def isPrime(n) :

    # Corner cases
    if (n <= 1) :
        return False
    if (n <= 3) :
        return True

    # This is checked so that we can skip
    # middle five numbers in below loop
    if (n % 2 == 0 or n % 3 == 0) :
        return False

    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6

    return True
t=int(input())
for i in range(0,t):
    n=int(input())
    if n==1:
        print("2")
        continue
    if isPrime(n):
        print(n+1)
        continue
    if n%2==0:
        k=n//2
        min=2+k
    else:
        min=n+1
    for j in range(2,(n//2)+1):
        if n%j==0:
            k=n//j
            if k!=j:
                l=j+k
                if l<min:
                    min=l
    print(min)


Solve in Python:
Yeah, we failed to make up a New Year legend for this problem.

A permutation of length $n$ is an array of $n$ integers such that every integer from $1$ to $n$ appears in it exactly once.

An element $y$ of permutation $p$ is reachable from element $x$ if $x = y$, or $p_x = y$, or $p_{p_x} = y$, and so on.

The decomposition of a permutation $p$ is defined as follows: firstly, we have a permutation $p$, all elements of which are not marked, and an empty list $l$. Then we do the following: while there is at least one not marked element in $p$, we find the leftmost such element, list all elements that are reachable from it in the order they appear in $p$, mark all of these elements, then cyclically shift the list of those elements so that the maximum appears at the first position, and add this list as an element of $l$. After all elements are marked, $l$ is the result of this decomposition.

For example, if we want to build a decomposition of $p = [5, 4, 2, 3, 1, 7, 8, 6]$, we do the following:  initially $p = [5, 4, 2, 3, 1, 7, 8, 6]$ (bold elements are marked), $l = []$;  the leftmost unmarked element is $5$; $5$ and $1$ are reachable from it, so the list we want to shift is $[5, 1]$; there is no need to shift it, since maximum is already the first element;  $p = [\textbf{5}, 4, 2, 3, \textbf{1}, 7, 8, 6]$, $l = [[5, 1]]$;  the leftmost unmarked element is $4$, the list of reachable elements is $[4, 2, 3]$; the maximum is already the first element, so there's no need to shift it;  $p = [\textbf{5}, \textbf{4}, \textbf{2}, \textbf{3}, \textbf{1}, 7, 8, 6]$, $l = [[5, 1], [4, 2, 3]]$;  the leftmost unmarked element is $7$, the list of reachable elements is $[7, 8, 6]$; we have to shift it, so it becomes $[8, 6, 7]$;  $p = [\textbf{5}, \textbf{4}, \textbf{2}, \textbf{3}, \textbf{1}, \textbf{7}, \textbf{8}, \textbf{6}]$, $l = [[5, 1], [4, 2, 3], [8, 6, 7]]$;  all elements are marked, so $[[5, 1], [4, 2, 3], [8, 6, 7]]$ is the result.

The New Year transformation of a permutation is defined as follows: we build...

from math import factorial as fact

N = 55
c = [1]
for i in range(N):
	c.append(fact(i))
dp = [0] * N
dp[0] = 1
for i in range(1, N):
	for j in range(i):
		dp[i] += dp[j] * c[i - j - 1]

def get_kth_cycle(n, k):
	if n == 1:
		return [1]
	ans = [-1] * n
	ans[0] = n - 1
	fin = [i for i in range(n)]
	fin[0] = n - 1
	init = [i for i in range(n)]
	init[n - 1] = 0
	used = [False] * n
	used[n - 1] = True
	for i in range(1, n - 1):
		j = 0
		cur = fact(n - i - 2)
		while True:
			while used[j] or (i < n - 1 and j == init[i]):
				j += 1
			if k > cur:
				k -= cur
				j += 1
			else:
				fin[init[i]] = fin[j]
				init[fin[j]] = init[i]
				ans[i] = j
				used[j] = True
				break
	ans[-1] = init[-1]
	return [x + 1 for x in ans]

def f(n, k):
	if n == 0:
		assert k == 1
		return []
	cl = 1
	while c[cl - 1] * dp[n - cl] < k:
		k -= c[cl - 1] * dp[n - cl]
		cl += 1
	rest = f(n - cl, (k - 1) % dp[n - cl] + 1)
	rest = [x + cl for x in rest]
	k = (k - 1) // dp[n - cl] + 1
	return get_kth_cycle(cl, k) + rest

def solve():
	n, k = map(int, input().split())
	if k > dp[n]:
		print(-1)
		return
	print(*f(n, k))

def main():
	t = int(input())
	while t > 0:
		t -= 1
		solve()

main()


Solve in Python:
Yesterday, Chef found $K$ empty boxes in the cooler and decided to fill them with apples. He ordered $N$ apples, where $N$ is a multiple of $K$. Now, he just needs to hire someone who will distribute the apples into the boxes with professional passion.
Only two candidates passed all the interviews for the box filling job. In one minute, each candidate can put $K$ apples into boxes, but they do it in different ways: the first candidate puts exactly one apple in each box, while the second one chooses a random box with the smallest number of apples and puts $K$ apples in it.
Chef is wondering if the final distribution of apples can even depend on which candidate he hires. Can you answer that question?
Note: The boxes are distinguishable (labeled), while the apples are not. Therefore, two distributions of apples are different if there is a box such that the number of apples in it when the first candidate finishes working can be different from the number of apples in it when the second candidate finishes working.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains two space-separated integers $N$ and $K$.

-----Output-----
For each test case, print a single line containing the string "YES" if the final distributions of apples can be different or "NO" if they will be the same (without quotes).

-----Constraints-----
- $1 \le T \le 250$
- $1 \le N, K \le 10^{18}$
- $N$ is divisible by $K$

-----Subtasks-----
Subtask #1 (30 points): $1 \le N, K \le 10^5$
Subtask #2 (70 points): original constraints

-----Example Input-----
3
5 1
4 2
10 10

-----Example Output-----
NO
NO
YES

-----Explanation-----
Example case 1: No matter who is hired, all apples will be in the only box at the end.
Example case 2: At the end, there will be two apples in each box.
Example case 3: If we hire the first candidate, there will be one apple in each box, but if we hire the second one,...

# cook your dish here
t=int(input())
for i in range(t,0,-1):
 x,y=map(int,input().split())
 k=x//y

 if k%y==0:
  print("NO")
 else:
  print("YES")


Solve in Python:
You and your $n - 1$ friends have found an array of integers $a_1, a_2, \dots, a_n$. You have decided to share it in the following way: All $n$ of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.

You are standing in the $m$-th position in the line. Before the process starts, you may choose up to $k$ different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.

Suppose that you're doing your choices optimally. What is the greatest integer $x$ such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to $x$?

Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.

-----Input-----

The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 1000$)  — the number of test cases. The description of the test cases follows.

The first line of each test case contains three space-separated integers $n$, $m$ and $k$ ($1 \le m \le n \le 3500$, $0 \le k \le n - 1$)  — the number of elements in the array, your position in line and the number of people whose choices you can fix.

The second line of each test case contains $n$ positive integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$)  — elements of the array.

It is guaranteed that the sum of $n$ over all test cases does not exceed $3500$.

-----Output-----

For each test case, print the largest integer $x$ such...

import sys
readline = sys.stdin.readline

class Segtree:
    def __init__(self, A, intv, initialize = True, segf = max):
        self.N = len(A)
        self.N0 = 2**(self.N-1).bit_length()
        self.intv = intv
        self.segf = segf
        if initialize:
            self.data = [intv]*self.N0 + A + [intv]*(self.N0 - self.N)
            for i in range(self.N0-1, 0, -1):
                self.data[i] = self.segf(self.data[2*i], self.data[2*i+1])
        else:
            self.data = [intv]*(2*self.N0)

    def update(self, k, x):
        k += self.N0
        self.data[k] = x
        while k > 0 :
            k = k >> 1
            self.data[k] = self.segf(self.data[2*k], self.data[2*k+1])

    def query(self, l, r):
        L, R = l+self.N0, r+self.N0
        s = self.intv
        while L < R:
            if R & 1:
                R -= 1
                s = self.segf(s, self.data[R])
            if L & 1:
                s = self.segf(s, self.data[L])
                L += 1
            L >>= 1
            R >>= 1
        return s

    def binsearch(self, l, r, check, reverse = False):
        L, R = l+self.N0, r+self.N0
        SL, SR = [], []
        while L < R:
            if R & 1:
                R -= 1
                SR.append(R)
            if L & 1:
                SL.append(L)
                L += 1
            L >>= 1
            R >>= 1

        if reverse:
            for idx in (SR + SL[::-1]):
                if check(self.data[idx]):
                    break
            else:
                return -1
            while idx < self.N0:
                if check(self.data[2*idx+1]):
                    idx = 2*idx + 1
                else:
                    idx = 2*idx
            return idx - self.N0
        else:
            for idx in (SL + SR[::-1]):
                if check(self.data[idx]):
                    break
            else:
                return -1
            while idx < self.N0:
                if check(self.data[2*idx]):
                    idx =...


Solve in Python:
You and your best friend Stripes have just landed your first high school jobs! You'll be delivering newspapers to your neighbourhood on weekends. For your services you'll be charging a set price depending on the quantity of the newspaper bundles.

The cost of deliveries is:

- $3.85 for 40 newspapers
- $1.93 for 20
- $0.97 for 10
- $0.49 for 5
- $0.10 for 1

Stripes is taking care of the footwork doing door-to-door drops and your job is to take care of the finances. What you'll be doing is providing the cheapest possible quotes for your services.

Write a function that's passed an integer representing the amount of newspapers and returns the cheapest price. The returned number must be rounded to two decimal places.

![Paperboy](http://mametesters.org/file_download.php?file_id=1016&type=bug)

def cheapest_quote(n):
    rates = [(40, 3.85), (20, 1.93), (10, 0.97), (5, 0.49), (1, 0.1)]
    total = 0
    for bundle, price in rates:
        total += n//bundle * price
        n %= bundle
    return round(total, 2)


Solve in Python:
You and your friend are playing the game Mortal Kombat XI. You are trying to pass a challenge tower. There are $n$ bosses in this tower, numbered from $1$ to $n$. The type of the $i$-th boss is $a_i$. If the $i$-th boss is easy then its type is $a_i = 0$, otherwise this boss is hard and its type is $a_i = 1$.

During one session, either you or your friend can kill one or two bosses (neither you nor your friend can skip the session, so the minimum number of bosses killed during one session is at least one). After your friend session, your session begins, then again your friend session begins, your session begins, and so on. The first session is your friend's session.

Your friend needs to get good because he can't actually kill hard bosses. To kill them, he uses skip points. One skip point can be used to kill one hard boss.

Your task is to find the minimum number of skip points your friend needs to use so you and your friend kill all $n$ bosses in the given order.

For example: suppose $n = 8$, $a = [1, 0, 1, 1, 0, 1, 1, 1]$. Then the best course of action is the following:

  your friend kills two first bosses, using one skip point for the first boss;  you kill the third and the fourth bosses;  your friend kills the fifth boss;  you kill the sixth and the seventh bosses;  your friend kills the last boss, using one skip point, so the tower is completed using two skip points.

You have to answer $t$ independent test cases.

-----Input-----

The first line of the input contains one integer $t$ ($1 \le t \le 2 \cdot 10^4$) — the number of test cases. Then $t$ test cases follow.

The first line of the test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of bosses. The second line of the test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 1$), where $a_i$ is the type of the $i$-th boss.

It is guaranteed that the sum of $n$ does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$).

-----Output-----

For each test case, print the answer: the minimum number of skip...

INF = 10**6

t = int(input())
for _ in range(t):
    n = int(input())
    a = list(map(int, input().split()))

    out = [0] * (n + 1)

    for i in range(1, n + 1):
        best = INF
        if i >= 2:
            best = min(best, a[i-2] + out[i-2])
        if i >= 3:
            best = min(best, a[i-3] + out[i-3])
        if i >= 4:
            best = min(best, a[i-4] + a[i-3] + out[i-4])
        out[i] = best

    fin = out[n]
    for i in range(1,4):
        if i <= n:
            fin = min(fin, out[n-i] + a[n-i])
    print(fin)


Solve in Python:
You and your friends have been battling it out with your Rock 'Em, Sock 'Em robots, but things have gotten a little boring. You've each decided to add some amazing new features to your robot and automate them to battle to the death.

Each robot will be represented by an object. You will be given two robot objects, and an object of battle tactics and how much damage they produce. Each robot will have a name, hit points, speed, and then a list of battle tacitcs they are to perform in order. Whichever robot has the best speed, will attack first with one battle tactic.

Your job is to decide who wins.

Example:
```python
 robot_1 = {
  "name": "Rocky",
  "health": 100,
  "speed": 20,
  "tactics": ["punch", "punch", "laser", "missile"]
 }
 robot_2 = {
   "name": "Missile Bob",
   "health": 100,
   "speed": 21,
   "tactics": ["missile", "missile", "missile", "missile"]
 }
 tactics = {
   "punch": 20,
   "laser": 30,
   "missile": 35
 }

 fight(robot_1, robot_2, tactics) -> "Missile Bob has won the fight."
```

robot2 uses the first tactic, "missile" because he has the most speed. This reduces robot1's health by 35. Now robot1 uses a punch, and so on.

**Rules**

- A robot with the most speed attacks first. If they are tied, the first robot passed in attacks first.
- Robots alternate turns attacking. Tactics are used in order.
- A fight is over when a robot has 0 or less health or both robots have run out of tactics.
- A robot who has no tactics left does no more damage, but the other robot may use the rest of his tactics.
- If both robots run out of tactics, whoever has the most health wins. Return the message "{Name} has won the fight."
- If both robots run out of tactics and are tied for health, the fight is a draw. Return "The fight was a draw."

**To Java warriors**

`Robot` class is immutable.

Check out my other 80's Kids Katas:

80's Kids #1: How Many Licks Does It Take
80's Kids #2: Help Alf Find His Spaceship
80's Kids #3: Punky Brewster's Socks
80's Kids #4: Legends of the Hidden Temple
80's Kids #5:...

def fight(robot_1, robot_2, tactics):
    attack, defend = (robot_1, robot_2) if robot_1['speed'] >= robot_2['speed'] else (robot_2, robot_1)

    while attack['health'] > 0:
        if attack['tactics']:
            defend['health'] -= tactics[attack['tactics'].pop()]
        elif not defend['tactics']:
            break
        attack, defend = defend, attack

    if attack['health'] == defend['health']:
        return "The fight was a draw."
    return "{} has won the fight.".format((defend if attack['health'] < defend['health'] else attack)['name'])


Solve in Python:
You are Dastan, the great Prince of Persia!
After searching long for the mysterious 'Sands of Time', you have finally arrived at the gates of the city that hosts the ancient temple of the gods. However, the gate is locked and it can only be opened with a secret code, which you need to obtain by solving the following puzzle:
There is a table in front of you, with $N$ coins placed in a row and numbered $1$ through $N$ from left to right. For each coin, you know whether it is initially showing heads or tails. You have to perform exactly $K$ operations. In one operation, you should remove the rightmost coin present on the table, and if this coin was showing heads right before it was removed, then you should also flip all the remaining coins. (If a coin was showing heads, then after it is flipped, it is showing tails, and vice versa.)
The code needed to enter the temple is the number of coins which, after these $K$ operations are performed, have not been removed and are showing heads. Can you find this number? The fate of Persia lies in your hands…

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains two space-separated integers $N$ and $K$.
- The second line contains $N$ space-separated characters. For each valid $i$, the $i$-th of these characters is 'H' if the $i$-th coin is initially showing heads or 'T' if it is showing tails.

-----Output-----
For each test case, print a single line containing one integer ― the number of coins that are showing heads after $K$ operations.

-----Constraints-----
- $1 \le T \le 200$
- $1 \le K < N \le 100$

-----Subtasks-----
Subtask #1 (100 points): original constraints

-----Example Input-----
3
5 3
H T T H T
7 4
H H T T T H H
6 1
T H T H T T

-----Example Output-----
1
2
2

for k in range(int(input())):
 n,k=list(map(int,input().split()))
 l=list(map(str,input().split()))
 while k>0:
  if l[-1]=="T":
   l.pop()
  else:
   for i in range(0,len(l)-1):
    if l[i]=="H":
     l[i]="T"
    else:
     l[i]="H"
   l.pop()

  k=k-1
 print(l.count("H"))


Solve in Python:
You are a *khm*mad*khm* scientist and you decided to play with electron distribution among atom's shells.
You know that basic idea of electron distribution is that electrons should fill a shell untill it's holding the maximum number of electrons.

  ---
Rules:
  - Maximum number of electrons in a shell is distributed with a rule of 2n^2 (n being position of a shell).
  - For example, maximum number of electrons in 3rd shield is 2*3^2 = 18.
  - Electrons should fill the lowest level shell first.
  - If the electrons have completely filled the lowest level shell, the other unoccupied electrons will fill the higher level shell and so on.
  ---

```
Ex.:    atomicNumber(1); should return [1]
        atomicNumber(10); should return [2, 8]
        atomicNumber(11); should return [2, 8, 1]
        atomicNumber(47); should return [2, 8, 18, 19]
```

def atomic_number(n):
    L = []
    i = 1
    while n > 0:
        a = min(2*i**2, n)
        L.append(a)
        n -= a
        i += 1
    return L


Solve in Python:
You are a biologist working on the amino acid  composition of proteins. Every protein consists of a long chain of 20 different amino acids with different properties.
Currently, you are collecting data on the percentage, various amino acids make up a protein you are working on. As manually counting the occurences of amino acids takes too long (especially when counting more than one amino acid), you decide to write a program for this task:

Write a function that takes two arguments,
 1. A (snippet of a) protein sequence
 2. A list of amino acid residue codes

and returns the rounded percentage of the protein that the given amino acids make up.
If no amino acid list is given, return the percentage of hydrophobic amino acid residues ["A", "I", "L", "M", "F", "W", "Y", "V"].

def aa_percentage(protein, residue="AILMFWYV"):
    return round(100 * sum(protein.count(aa) for aa in set(residue)) / len(protein))


Solve in Python:
You are a king and you are at war. If the enemy breaks through your frontline you lose.
Enemy can break the line only if the sum of morale of any $K$ continuous soldiers is strictly less than $M$. So, you being a motivational orator decides to boost their morale by giving a speech. On hearing it morale of a soldier multiplies by $X$ which depends on you and your speech (i.e. $X$ can be any positive value) but atmost only $K$ continuous speakers can hear your speech.
N soldiers are standing on the frontline with $A[i]$ morale.
Determine the minimum number of speeches you need to give.

-----Input:-----
The first line contains three space seperated integers $N,K,M$.
The next line contains $N$ space integers, ith of which denotes the morale of $ith$ soldier.

-----Output:-----
Output the minimum number of speeches required. In case if it is impossible to achieve, print $-1$.

-----Constraints:-----
$1 \leq N,M \leq 10^5$
$1 \leq k \leq N$
$0 \leq Ai \leq 10^5$

-----Sample Input:-----
6 2 5
1 1 1 1 1 1

-----Sample Output:-----
2

-----Explanation:-----
We multiply 2nd ,3rd  and 5th,6th by 5. Resulting array will be 1 5 5 1 5 5.

nkm = list(map(int, input().split(' ')))
n = nkm[0]
k = nkm[1]
m = nkm[2]
li = list(map(int, input().split(' ')))
i = k-1
j = k-1
t = 1
c = 0
while(i<n):

	if(li[i]!=0):
		c+=1
		j=k-1
		i= i + 2*k - 1
	else:
		i-=1
		j-=1
		if(j<0):
			t=0
			break

if(t==1):
	print(c)
else:
	print("-1")


Solve in Python:
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

Example 1:
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.

Example 2:
Input: nums = [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
             Total amount you can rob = 2 + 9 + 1 = 12.

Constraints:

0 <= nums.length <= 100
0 <= nums[i] <= 400

class Solution:
    def rob(self, nums: List[int]) -> int:
        prevMax=0
        currMax=0

        for num in nums:
            temp=currMax
            currMax=max(prevMax+num, currMax)
            prevMax=temp

        return currMax


Solve in Python:
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

Example 1:

Input: [2,3,2]
Output: 3
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2),
             because they are adjacent houses.

Example 2:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.

class Solution:
     def rob(self, nums):
         """
         :type nums: List[int]
         :rtype: int
         """
         if not nums:
             return 0
         mark = [0 for i in range(len(nums))]
         result = list(mark)
         if len(nums) == 1:
             return nums[0]
         if len(nums) == 2:
             return max(nums[0], nums[1])

         mark[0] = 1
         result[0] = nums[0]
         if nums[0] > nums[1]:
             mark [1] = 1
             result[1] = nums[0]
         else:
             result[1] = nums[1]

         for i in range(2, len(nums)):
             result[i] = max(nums[i]+result[i-2], result[i-1])
             if nums[i]+result[i-2] > result[i-1]:
                 mark[i] = mark[i-2]
             else:
                 mark[i] = mark[i-1]

         if mark[0] == 1 and mark[-1] == 1:
             return max(self.solve(nums[1:]),self.solve(nums[:-1]))
         return result[-1]

     def solve(self, nums):
         if not nums:
             return 0
         if len(nums) == 1:
             return nums[0]
         if len(nums) == 2:
             return max(nums[0], nums[1])
         result = [0 for i in range(len(nums))]
         result[0] = nums[0]
         result[1] = max(nums[0], nums[1])
         for i in range(2, len(nums)):
             result[i] = max(nums[i]+result[i-2], result[i-1])
         return result[-1]


Solve in Python:
You are a skier (marked below by the `X`). You have made it to the Olympics! Well done.

```
\_\_\_X\_
\*\*\*\*\*\
\*\*\*\*\*\*\
\*\*\*\*\*\*\*\
\*\*\*\*\*\*\*\*\
\*\*\*\*\*\*\*\*\*\\.\_\_\_\_/
```

Your job in this kata is to calculate the maximum speed you will achieve during your downhill run. The speed is dictated by the height of the mountain. Each element of the array is a layer of the mountain as indicated by the diagram above (and further below). So for this example the mountain has a height of 5 (5 rows of stars). `Speed` is `mountain height * 1.5`.

The jump length is calculated by `(mountain height * speed * 9) / 10`. Jump length should be rounded to 2 decimal places.

You must return the length of the resulting jump as a string in the following format:

* when less than 10 m: `"X metres: He's crap!"`
* between 10 and 25 m: `"X metres: He's ok!"`
* between 25 and 50 m: `"X metres: He's flying!"`
* when more than 50 m: `"X metres: Gold!!"`

So in the example case above, the right answer would be `"33.75 metres: He's flying!"`

Sadly, it takes a lot of time to make arrays look like mountains, so the tests wont all look so nice. To give an example, the above mountain would look as follows in most cases:

```
[*****, ******, *******, ********, *********]
```
Not as much fun, eh?

*p.s. if you think "metre" is incorrect, please [read this](https://en.wikipedia.org/wiki/Metre#Spelling)*

def ski_jump(mountain):
    distance = len(mountain)**2 * 1.35
    if distance <= 10:
        return f"{distance:.2f} metres: He's crap!"
    if distance <= 25:
        return f"{distance:.2f} metres: He's ok!"
    if distance <= 50:
        return f"{distance:.2f} metres: He's flying!"
    if distance > 50:
        return f"{distance:.2f} metres: Gold!!"


Solve in Python:
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a $r \times c$ grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.

Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say $a$, passes by another country $b$, they change the dominant religion of country $b$ to the dominant religion of country $a$.

In particular, a single use of your power is this:   You choose a horizontal $1 \times x$ subgrid or a vertical $x \times 1$ subgrid. That value of $x$ is up to you;  You choose a direction $d$. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST;  You choose the number $s$ of steps;  You command each country in the subgrid to send a missionary group that will travel $s$ steps towards direction $d$. In each step, they will visit (and in effect convert the dominant religion of) all $s$ countries they pass through, as detailed above.  The parameters $x$, $d$, $s$ must be chosen in such a way that any of the missionary groups won't leave the grid.

The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a $1 \times 4$ subgrid, the direction NORTH, and $s = 2$ steps.  [Image]

You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your...

import sys
input = sys.stdin.readline

MOD = 10**9 + 7
t = int(input())

for _ in range(t):
    r, c = list(map(int, input().split()))
    s = [list(input()) for i in range(r)]
    cnt_a = 0
    flag_kado = False
    flag_hen = False
    flag_hen2 = False
    if s[0][0] == "A" or s[0][c-1] == "A" or s[r-1][0] == "A" or s[r-1][c-1] == "A":
        flag_kado = True

    for i in range(r):
        tmp = 0
        for j in range(c):
            if s[i][j] == "A":
                if i == 0 or j == 0 or i == r-1 or j == c-1:
                    flag_hen2 = True
                tmp += 1
        cnt_a += tmp
        if tmp == c and (i == 0 or i == r-1):
            flag_hen = True
        elif tmp == c:
            flag_kado = True

    for i in range(c):
        tmp = 0
        for j in range(r):
            if s[j][i] == "A":
                tmp += 1
        if tmp == r and (i == 0 or i == c-1):
            flag_hen = True
        elif tmp == r:
            flag_kado = True

    if cnt_a == c*r:
        print(0)
    elif flag_hen:
        print(1)
    elif flag_kado:
        print(2)
    elif flag_hen2:
        print(3)
    elif cnt_a != 0:
        print(4)
    else:
        print("MORTAL")


Solve in Python:
You are an evil sorcerer at a round table with $N$ sorcerers (including yourself). You can cast $M$ spells which have distinct powers $p_1, p_2, \ldots, p_M$.
You may perform the following operation any number of times (possibly zero):
- Assign a living sorcerer to each positive integer cyclically to your left starting from yourself ― the closest living sorcerer to your left is assigned to $1$, the next living sorcerer to the left is assigned to $2$ and so on. Note that each living sorcerer (including yourself) is assigned to an infinite number of integers.
- Choose a spell $j$ (possibly a spell you have chosen before) and kill the living sorcerer assigned to $p_j$. You may not cast a spell to kill yourself.

What is the maximum number of sorcerers you can kill using zero or more operations?

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains two space-separated integers $N$ and $M$.
- The second line contains $M$ space-separated integers $p_1, p_2, \ldots, p_M$.

-----Output-----
For each test case, print a single line containing one integer ― the maximum number of sorcerers you can kill.

-----Constraints-----
- $1 \le T \le 1,000$
- $1 \le N \le 10^9$
- $1 \le M \le 3 \cdot 10^5$
- $1 \le p_i \le 10^9$ for each valid $i$
- $p_1, p_2, \ldots, p_N$ are pairwise distinct
- the sum of $M$ over all test cases does not exceed $3 \cdot 10^5$

-----Example Input-----
5
4 1
5
6 2
2 4
1 4
7 16 8 29
1000000000 1
998244353
1 1
20201220

-----Example Output-----
3
4
0
1755647
0

-----Explanation-----
Example case 1: The initial state is shown in the figure from the statement. We can first use spell $1$ and kill the $5$-th sorcerer to our left, i.e. sorcerer $2$. Now there are $3$ living sorcerers and the state is as shown in the following figure:

We can use spell $1$ again and kill the current $5$-th living sorcerer to our left, i.e. sorcerer $4$. Now there are $2$ living...

# cook your dish here
import math

def gcd(a,b):
 if b == 0:
  return a
 return gcd(b,a%b)

for _ in range(int(input())):
 n,m=list(map(int,input().split(" ")))
 p=list(map(int,input().split(" ")))
 g=p[0]
 for i in range(1,m):
  g = gcd(g,p[i])

 if g>n:
  maxEl=1
  for i in range(2,int(math.sqrt(g)+1)):
   if g%i == 0:
    if i<=n:
     maxEl = max(maxEl,i)
    if g//i<=n:
     maxEl = max(maxEl,g//i)
  print(n - maxEl)
 else:
  print(n - g)


Solve in Python:
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!

from string import ascii_lowercase as lowers, digits

rotlow = f"{lowers[13:]}{lowers[:13]}"
rotdig = f"{digits[5:]}{digits[:5]}"
table = str.maketrans(
    f"{lowers}{lowers.upper()}{digits}",
    f"{rotlow}{rotlow.upper()}{rotdig}",
)

def ROT135(input):
    return input.translate(table)


Solve in Python:
You are at the top left cell $(1, 1)$ of an $n \times m$ labyrinth. Your goal is to get to the bottom right cell $(n, m)$. You can only move right or down, one cell per step. Moving right from a cell $(x, y)$ takes you to the cell $(x, y + 1)$, while moving down takes you to the cell $(x + 1, y)$.

Some cells of the labyrinth contain rocks. When you move to a cell with rock, the rock is pushed to the next cell in the direction you're moving. If the next cell contains a rock, it gets pushed further, and so on.

The labyrinth is surrounded by impenetrable walls, thus any move that would put you or any rock outside of the labyrinth is illegal.

Count the number of different legal paths you can take from the start to the goal modulo $10^9 + 7$. Two paths are considered different if there is at least one cell that is visited in one path, but not visited in the other.

-----Input-----

The first line contains two integers $n, m$ — dimensions of the labyrinth ($1 \leq n, m \leq 2000$).

Next $n$ lines describe the labyrinth. Each of these lines contains $m$ characters. The $j$-th character of the $i$-th of these lines is equal to "R" if the cell $(i, j)$ contains a rock, or "." if the cell $(i, j)$ is empty.

It is guaranteed that the starting cell $(1, 1)$ is empty.

-----Output-----

Print a single integer — the number of different legal paths from $(1, 1)$ to $(n, m)$ modulo $10^9 + 7$.

-----Examples-----
Input
1 1
.

Output
1

Input
2 3
...
..R

Output
0

Input
4 4
...R
.RR.
.RR.
R...

Output
4

-----Note-----

In the first sample case we can't (and don't have to) move, hence the only path consists of a single cell $(1, 1)$.

In the second sample case the goal is blocked and is unreachable.

Illustrations for the third sample case can be found here: https://assets.codeforces.com/rounds/1225/index.html

def getSum(dp, pos, s, e, type_):
    if e < s:
        return 0

    if type_=='D':
        if e==m-1:
            return dp[pos][s]
        return dp[pos][s]-dp[pos][e+1]
    else:
        if e==n-1:
            return dp[s][pos]
        return dp[s][pos]-dp[e+1][pos]

mod  = 10**9+7
n, m = map(int, input().split())
a    = [list(list(map(lambda x: 1 if x=='R' else 0, input()))) for _ in range(n)]

SD  = [[0]*m for _ in range(n)]
SN  = [[0]*m for _ in range(n)]
dpD = [[0]*m for _ in range(n)]
dpN = [[0]*m for _ in range(n)]

for i in range(n-1, -1, -1):
    for j in range(m-1, -1, -1):
        if i == n-1:
            SD[i][j]=a[i][j]
        else:
            SD[i][j]=SD[i+1][j]+a[i][j]

        if j == m-1:
            SN[i][j]=a[i][j]
        else:
            SN[i][j]=SN[i][j+1]+a[i][j]

for j in range(m-1,-1,-1):
    if a[n-1][j]==1:
        break
    dpD[n-1][j]=1
    dpN[n-1][j]=1

for i in range(n-1,-1,-1):
    if a[i][m-1]==1:
        break
    dpD[i][m-1]=1
    dpN[i][m-1]=1

for j in range(m-2, -1, -1):
    if i==n-1:
        break
    dpD[n-1][j]+=dpD[n-1][j+1]

for i in range(n-2,-1,-1):
    if j==m-1:
        break
    dpN[i][m-1]+=dpN[i+1][m-1]

for i in range(n-2,-1,-1):
    for j in range(m-2,-1,-1):
        s, e = j, m-SN[i][j]-1
        #print(i, j, s, e, 'N')
        dpN[i][j]  = getSum(dpD, i+1, s, e, 'D')
        dpN[i][j]  = (dpN[i][j] + dpN[i+1][j]) % mod

        s, e = i, n-SD[i][j]-1
        #print(i, j, s, e, 'D')
        dpD[i][j]  = getSum(dpN, j+1, s, e, 'N')

    if i != 0:
        for j in range(m-2,-1,-1):
            dpD[i][j] = (dpD[i][j] + dpD[i][j+1]) % mod

print(dpD[0][0] % mod)


Solve in Python:
You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Note: Given n will be a positive integer.

Example 1:

Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:

Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

class Solution:
     def climbStairs(self, n):
         """
         :type n: int
         :rtype: int
         """
         a = 1
         b = 2
         if n < 2:
             return 1
         for i in range(n-2):
             a,b = b, a+b

         return b


Solve in Python:
You are currently in the United States of America. The main currency here is known as the United States Dollar (USD). You are planning to travel to another country for vacation, so you make it today's goal to convert your USD (all bills, no cents) into the appropriate currency. This will help you be more prepared for when you arrive in the country you will be vacationing in.

Given an integer (`usd`) representing the amount of dollars you have and a string (`currency`) representing the name of the currency used in another country, it is your task to determine the amount of foreign currency you will receive when you exchange your United States Dollars.

However, there is one minor issue to deal with first. The screens and monitors at the Exchange are messed up. Some conversion rates are correctly presented, but other conversion rates are incorrectly presented. For some countries, they are temporarily displaying the standard conversion rate in the form of a number's binary representation!

You make some observations. If a country's currency begins with a vowel, then the conversion rate is unaffected by the technical difficulties. If a country's currency begins with a consonant, then the conversion rate has been tampered with.

Normally, the display would show 1 USD converting to 111 Japanese Yen. Instead, the display is showing 1 USD converts to 1101111 Japanese Yen. You take it upon yourself to sort this out. By doing so, your 250 USD rightfully becomes 27750 Japanese Yen.

`
function(250, "Japanese Yen") => "You now have 27750 of Japanese Yen."
`

Normally, the display would show 1 USD converting to 21 Czech Koruna. Instead, the display is showing 1 USD converts to 10101 Czech Koruna. You take it upon yourself to sort this out. By doing so, your 325 USD rightfully becomes 6825 Czech Koruna.

`
function(325, "Czech Koruna") => "You now have 6825 of Czech Koruna."
`

Using your understanding of converting currencies in conjunction with the preloaded conversion-rates table, properly convert your dollars into...

def convert_my_dollars(usd, currency):
    di={"Armenian Dram":478, "Bangladeshi Taka":1010010, "Croatian Kuna":110, "Czech Koruna":10101, "Dominican Peso":110000, "Egyptian Pound":18, "Guatemalan Quetzal":111, "Haitian Gourde":1000000, "Indian Rupee":63, "Japanese Yen":1101111, "Kenyan Shilling":1100110, "Nicaraguan Cordoba":11111, "Norwegian Krone":1000, "Philippine Piso":110010, "Romanian Leu":100, "Samoan Tala":11, "South Korean Won":10000100011, "Thai Baht":100000, "Uzbekistani Som":10000, "Venezuelan Bolivar":1010, "Vietnamese Dong":101100000101101}
    if currency[0] in ("A","E","I",'O','U'):
        return f'You now have {di[currency]*usd} of {currency}.'
    else:
        return f'You now have {int(str(di[currency]),2)*usd} of {currency}.'


Solve in Python:
You are driving a vehicle that has capacity empty seats initially available for passengers.  The vehicle only drives east (ie. it cannot turn around and drive west.)
Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off.  The locations are given as the number of kilometers due east from your vehicle's initial location.
Return true if and only if it is possible to pick up and drop off all passengers for all the given trips.

Example 1:
Input: trips = [[2,1,5],[3,3,7]], capacity = 4
Output: false

Example 2:
Input: trips = [[2,1,5],[3,3,7]], capacity = 5
Output: true

Example 3:
Input: trips = [[2,1,5],[3,5,7]], capacity = 3
Output: true

Example 4:
Input: trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11
Output: true

Constraints:

trips.length <= 1000
trips[i].length == 3
1 <= trips[i][0] <= 100
0 <= trips[i][1] < trips[i][2] <= 1000
1 <= capacity <= 100000

class Solution:
    def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
        d=[0 for i in range(1001)]
        for i in trips:
            for j in range(i[1], i[2]):
                d[j]+=i[0]
        # print(d)
        for i in range(1001):
            if d[i]>capacity:
                return False
        return True


Solve in Python:
You are fed up with your messy room, so you decided to clean it up.

Your room is a bracket sequence $s=s_{1}s_{2}\dots s_{n}$ of length $n$. Each character of this string is either an opening bracket '(' or a closing bracket ')'.

In one operation you can choose any consecutive substring of $s$ and reverse it. In other words, you can choose any substring $s[l \dots r]=s_l, s_{l+1}, \dots, s_r$ and change the order of elements in it into $s_r, s_{r-1}, \dots, s_{l}$.

For example, if you will decide to reverse substring $s[2 \dots 4]$ of string $s=$"((()))" it will be equal to $s=$"()(())".

A regular (aka balanced) bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences "()()", "(())" are regular (the resulting expressions are: "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.

A prefix of a string $s$ is a substring that starts at position $1$. For example, for $s=$"(())()" there are $6$ prefixes: "(", "((", "(()", "(())", "(())(" and "(())()".

In your opinion, a neat and clean room $s$ is a bracket sequence that:

  the whole string $s$ is a regular bracket sequence;  and there are exactly $k$ prefixes of this sequence which are regular (including whole $s$ itself).

For example, if $k = 2$, then "(())()" is a neat and clean room.

You want to use at most $n$ operations to make your room neat and clean. Operations are applied one after another sequentially.

It is guaranteed that the answer exists. Note that you do not need to minimize the number of operations: find any way to achieve the desired configuration in $n$ or less operations.

-----Input-----

The first line contains integer number $t$ ($1 \le t \le 100$) — the number of test cases in the input. Then $t$ test cases follow.

The first line of a test case contains two integers $n$ and $k$ ($1 \le k \le \frac{n}{2}, 2 \le n \le 2000$, $n$ is even) — length of $s$ and required number of...

t = int(input())
for z in range(t):
    n, k = map(int, input().split())
    arr = list(input())
    need = '()' * (k - 1) + '(' * ((n - (k - 1) * 2) // 2) + ')' * ((n - (k - 1) * 2) // 2)
    #print(need)
    li = 0
    ri = n - 1
    ln = 0
    rn = n - 1
    ret = []
    rev = 0
    while li < n:
        if arr[li] != need[li]:
            ri = li + 1
            while arr[ri] != need[li]:
                ri += 1
            ret.append([li, ri])
            arr = arr[:li] + list(reversed(arr[li:ri+1])) + arr[ri+1:]
        li += 1
    #print(*arr, sep='')

    print(len(ret))
    for x in ret:
        print(x[0] + 1, x[1] + 1)


Solve in Python:
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:  Write parity(a) to the end of a. For example, $1010 \rightarrow 10100$.  Remove the first character of a. For example, $1001 \rightarrow 001$. You cannot perform this operation if a is empty.

You can use as many operations as you want. The problem is, is it possible to turn a into b?

The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.

-----Input-----

The first line contains the string a and the second line contains the string b (1 ≤ |a|, |b| ≤ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.

-----Output-----

Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.

-----Examples-----
Input
01011
0110

Output
YES

Input
0011
1110

Output
NO

-----Note-----

In the first sample, the steps are as follows: 01011 → 1011 → 011 → 0110

a=input()
b=input()

acount=a.count('1')
bcount=b.count('1')

if (acount % 2 == 1):
	acount += 1

if (acount >= bcount):
	print('YES')
else:
	print('NO')


Solve in Python:
You are given $N$ gears numbered $1$ through $N$. For each valid $i$, gear $i$ has $A_i$ teeth. In the beginning, no gear is connected to any other. Your task is to process $M$ queries and simulate the gears' mechanism. There are three types of queries:
- Type 1: Change the number of teeth of gear $X$ to $C$.
- Type 2: Connect two gears $X$ and $Y$.
- Type 3: Find the speed of rotation of gear $Y$ if gear $X$ rotates with speed $V$.
It is known that if gear $i$ is directly connected to gear $j$ and gear $i$ rotates with speed $V$, then gear $j$ will rotate with speed $-V A_i / A_j$, where the sign of rotation speed denotes the direction of rotation (so minus here denotes rotation in the opposite direction). You may also notice that gears can be blocked in some cases. This happens when some gear would have to rotate in different directions. If a gear is connected to any blocked gear, it is also blocked. For example, if three gears are connected to each other, this configuration can not rotate at all, and if we connect a fourth gear to these three, it will also be blocked and not rotate.

-----Input-----
- The first line of the input contains two space-separated integers $N$ and $M$.
- The second line contains $N$ space-separated integers $A_1, A_2, \dots, A_N$.
- The following $M$ lines describe queries. Each of these lines begins with an integer $T$ denoting the type of the current query.
- If $T = 1$, it is followed by a space and two space-separated integers $X$ and $C$.
- If $T = 2$, it is followed by a space and two space-separated integers $X$ and $Y$.
- If $T = 3$, it is followed by a space and three space-separated integers $X$, $Y$ and $V$.

-----Output-----
For each query of type 3, print a single line containing two integers separated by a slash '/' — the numerator and denominator of the rotation speed of the given gear expressed as an irreducible fraction (even if this speed is an integer), or $0$ if the gear does not rotate at all.

-----Constraints-----
- $1 \le N \le 10^5$
- $1 \le M \le 2\cdot...

class Dsu:
    def __init__(self, v, s):
        self.par = s
        self.v = v
        self.dr = [1] * v
        self.zero = [False] * v
        self.speed = []
        for i in range(v):
            self.speed.append([])
            self.speed[i].append(i)

    def find(self, i):
    #     if parent[i] == -1:
    #         return i
    #     else: return self.find_parent(parent, parent[i])
        if i != self.par[i][0]:
            org = self.par[i][0]
            self.par[i][0] = self.find(self.par[i][0])
            if self.zero[i] or self.zero[self.par[i][0]] or self.zero[org]:
                self.zero[i] = self.zero[self.par[i][0]] = self.zero[org] = True
            if org != self.par[i][0]:
                self.speed[self.par[i][0]].append(i)
        return self.par[i][0]

    def union(self, x, y):
        # def union(self, parent, x, y):
        #     x_set = self.find_parent(parent, x)
        #     y_set = self.find_parent(parent, y)
        #     parent[x_set] = y_set
        self.rx = self.find(x)
        self.ry = self.find(y)
        self.sign = -self.dr[x] * self.dr[y]
        if self.rx != self.ry:
            if (self.par[self.rx][1]<self.par[self.ry][1]):
                mx=self.ry
                mn=self.rx
            if (self.par[self.rx][1]>self.par[self.ry][1]):
                mx=self.rx
                mn=self.ry
            if self.par[self.rx][1] != self.par[self.ry][1]:
                self.par[mn][0] = mx
                if self.zero[mn] or self.zero[mx] or self.zero[x] or self.zero[y]:
                    self.zero[mn] = self.zero[mx] = self.zero[x] = self.zero[y] = True
                else:
                    for i in range(len(self.speed[mn])):
                        self.dr[self.speed[mn][i]] *= self.sign
                        org = self.par[self.speed[mn][i]][0]
                        if org != mx:
                            self.par[self.speed[mn][i]][0] = mx
                            self.speed[mx].append(self.speed[mn][i])
               ...


Solve in Python:
You are given $N$ integers in an array: $A[1], A[2], \ldots, A[N]$. You also have another integer $L$.
Consider a sequence of indices ($i_1, i_2, \ldots, i_k$). Note that a particular index can occur multiple times in the sequence, and there is no order in which these indices have to occur. ($i_1, i_2, \ldots, i_k$) is a sequence of size $k$. It is said to be an $Interesting$ sequence, if $A[i_1] \ge A[i_2] \ge \ldots \ge A[i_k]$.
The $Cost$ of an Interesting sequence ($i_1, i_2, \ldots, i_k$), is defined to be the minimum absolute difference between any two adjacent indices. In other words, the Cost is $min \{ |i_2 - i_1|, |i_3 - i_2|, \ldots, |i_k - i_{k-1}| \}$.
Your job is to consider the Costs of all the Interesting sequences of size $L$ associated with the given array, and output the maximum Cost. Note that you can show that there is always at least one Interesting sequence for the given constraints.

-----Input-----
- The first line contains a single integer, $T$, which is the number of testcases. The description of each testcase follows.
- The first line of each testcase contains two space separated integers: $N$ and $L$.
- The second line of each testcase contains $N$ space separated integers: $A[1], A[2], \ldots, A[N]$.

-----Output-----
- For each testcase, output the answer in a new line.

-----Constraints-----
- $1 \leq T \leq 3$
- $1 \leq A[i] \leq 10^9$
- $2 \leq L \leq 10^9$

-----Subtasks-----
- Subtask 1: 7 points
- It is guaranteed that $A[1] > A[2] > \ldots > A[N]$
- Note that the above condition implies that all elements are distinct.
- $1 \leq N \leq 500$
- Subtask 2: 7 points
- It is guaranteed that $A[1] \ge A[2] \ge \ldots \ge A[N]$
- $1 \leq N \leq 500$
- Subtask 3: 14 points
- It is guaranteed that all elements are distinct.
- $1 \leq N \leq 500$
- Subtask 4: 14 points
- $1 \leq N \leq 500$
- Subtask 5: 25 points
- It is guaranteed that all elements are distinct.
- $1 \leq N \leq 3000$
- Subtask 6: 33 points
- $1 \leq N \leq 3000$

-----Sample Input-----
1
6 3
2 4 1 12 3...

# cook your dish here
# from queue import PriorityQueue
# import bisect
def insort(l, v):
    s = 0
    e = len(l)
    while True:
        mid = (s+e)//2
        if s == e or mid > len(l):
            break
        if l[mid][0] < v[0]:
            s = mid+1
        elif l[mid][0] > v[0]:
            e = mid
        else:
            break
    l.insert(mid, v)

for _ in range(int(input())):
    n,l = map(int, input().split())
    a_l = list(map(int, input().split()))

    dic = {}
    dif = 0
    for i,v in enumerate(a_l, start=1):
        if v not in dic:
            dic[v] = [i, i]
        else:
            dic[v][0] = min(dic[v][0], i)
            dic[v][1] = max(dic[v][1], i)
            dif = max(dif, dic[v][1]-dic[v][0])

    ans = dif
    if l <= len(set(a_l)):
        i_l = [[v,i] for i,v in enumerate(a_l, start=1)]
        i_l.sort(reverse=True)

        dp = [[-1 for _ in range(l)] for _ in range(n)]
        pq_l = [[] for _ in range(l)]
        for i in range(1,n):
            il = 1
            dif_l = []
            for j in range(i):
                dif = abs(i_l[i][1]-i_l[j][1])
                dif_l.append(dif)
                dp[i][il] = max(dp[i][il], dif)

            for il in range(2,min(l,i+1)):
                for prev_max, ind in reversed(pq_l[il-1]):
                    if ind == i:
                        continue
                    if prev_max < dp[i][il]:
                        break
                    else:
                        dp[i][il] = max(dp[i][il], min(dif_l[ind], prev_max))
                insort(pq_l[il], [dp[i][il], i])
                # tmp = [v[0] for v in pq_l[il]]
                # ind = bisect.bisect_right(tmp, dp[i][il])
                # pq_l[il].insert(ind, [dp[i][il], i])

            il = 1
            insort(pq_l[il], [dp[i][il], i])
            # tmp = [v[0] for v in pq_l[il]]
            # ind = bisect.bisect_right(tmp, dp[i][il])
            # pq_l[il].insert(ind, [dp[i][il], i])

 ...


Solve in Python:
You are given $n$ arrays that can have different sizes. You also have a table with $w$ columns and $n$ rows. The $i$-th array is placed horizontally in the $i$-th row. You can slide each array within its row as long as it occupies several consecutive cells and lies completely inside the table.

You need to find the maximum sum of the integers in the $j$-th column for each $j$ from $1$ to $w$ independently.

 [Image] Optimal placements for columns $1$, $2$ and $3$ are shown on the pictures from left to right.

Note that you can exclude any array out of a column provided it remains in the window. In this case its value is considered to be zero.

-----Input-----

The first line contains two integers $n$ ($1 \le n \le 10^{6}$) and $w$ ($1 \le w \le 10^{6}$) — the number of arrays and the width of the table.

Each of the next $n$ lines consists of an integer $l_{i}$ ($1 \le l_{i} \le w$), the length of the $i$-th array, followed by $l_{i}$ integers $a_{i1}, a_{i2}, \ldots, a_{il_i}$ ($-10^{9} \le a_{ij} \le 10^{9}$) — the elements of the array.

The total length of the arrays does no exceed $10^{6}$.

-----Output-----

Print $w$ integers, the $i$-th of them should be the maximum sum for column $i$.

-----Examples-----
Input
3 3
3 2 4 8
2 2 5
2 6 3

Output
10 15 16

Input
2 2
2 7 8
1 -8

Output
7 8

-----Note-----

Illustration for the first example is in the statement.

import sys
input = sys.stdin.readline
from collections import deque
n,w=[int(i) for i in input().rstrip('\n').split()]
arr=[]
tem=[]
for i in range(n):
    t=[int(i) for i in input().rstrip('\n').split()]
    tem.append(t[0])
    arr.append(t[1:])
l=[0 for i in range(w)]

wi=[0 for i in range(w+1)]
for j in range(n):
    st=deque()
    c=w-tem[j]
    for i in range(tem[j]):
        while st and st[0]<i-c:st.popleft()
        while st and arr[j][st[-1]]<arr[j][i]:st.pop()
        st.append(i)
        if arr[j][st[0]]>0 or (i>=c and i<w-c):
            l[i]+=arr[j][st[0]]
    ind=tem[j]
    while st and arr[j][st[0]]>0:
        wi[ind]+=arr[j][st[0]]
        wi[w-(tem[j]-st[0])+1]+=-arr[j][st[0]]
        ind=w-(tem[j]-st[0])+1
        st.popleft()

curr=0
for i in range(w):
    curr+=wi[i]
    l[i]+=curr
print(" ".join(str(e) for e in l))


Solve in Python:
You are given $n$ intervals on the $X$ axis. Each interval $i$ is specified by its ends $[L_i, R_i]$. You want to color each interval either blue or yellow. After coloring all the intervals, the $X$ axis will will have $4$ colors:
- White, the part of $X$ axis contained in no interval
- Blue, the part of $X$ axis contained in atleast one blue colored interval and no yellow colored interval.
- Yellow, the part of $X$ axis contained in atleast one yellow colored interval and no blue colored interval.
- Green, the part of $X$ axis contained in at least one blue colored interval and at least one yellow colored interval.
You want to color the intervals so that the total length of the part colored green is maximized. If there are multiple ways to color which maximize the green part, you can output any of them.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- The first line of each testcase contains $n$, the number of intervals.
- The $i^{\text{th}}$ of the next $n$ lines contains two integers $L_i$ and $R_i$ describing the $i^{\text{th}}$ interval.

-----Output:-----
For each testcase, output a single string on a new line, whose $i^{\text{th}}$ character is $0$ if you color the $i^{\text{th}}$ interval blue, and $1$ if you color it yellow.

-----Constraints-----
- $ 1 \leq T \leq 10^5 $
- $ 1 \leq n \leq 10^5 $
- The sum of $n$ over all testcases doesn't exceed $10^5$.
- $ 1 \leq L_i \leq R_i \leq 10^9 $ for al $ 1 \leq i \leq n$.

-----Sample Input:-----
1
3
3 7
2 5
6 9

-----Sample Output:-----
100

-----Explanation:-----
The intervals are $[3, 7]$, $[2, 5]$, $[6, 9]$. It is optimal to color them in yellow, blue and blue respectively. In this coloring:
- $[2, 3) \cup (7, 9]$ is colored blue.
- $(5, 6)$ is colored yellow.
- $[3, 5] \cup [6, 7]$ is colored green, with a total length of $(5 - 3) + (7 - 6) = 3$.
- Rest of the $X$ axis is colored white.
Please note that colors at the endpoints of the intervals don't matter when computing the lengths, and we can ignore...

# cook your dish here
def f (arr: list):
 arr.sort()
 # print(arr)
 pl, pr, pc = float('-inf'), float('-inf'), 0
 col = [0 for x in range(len(arr))]
 for i in arr:
  nl, nr = i[0], i[1]
  if nl > pr:
   i.append(0)
   pl, pr, pc = nl, nr, 0
  else:
   nc = 0 if pc == 1 else 1
   i.append(nc)
   pc = nc if nr > pr else pc
   pr = max(pr, nr)
  col[i[2]] = str(i[3])
 return "".join(col)

T = int(input())
for t in range(T):
 n = int(input())
 arr = []
 for i in range(n):
  l, r = [int(x) for x in input().split()]
  arr.append([l,r,i])
 print(f(arr))


Solve in Python:
You are given $n$ points on the plane. The polygon formed from all the $n$ points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from $1$ to $n$, in clockwise order.

We define the distance between two points $p_1 = (x_1, y_1)$ and $p_2 = (x_2, y_2)$ as their Manhattan distance: $$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|.$$

Furthermore, we define the perimeter of a polygon, as the sum of Manhattan distances between all adjacent pairs of points on it; if the points on the polygon are ordered as $p_1, p_2, \ldots, p_k$ $(k \geq 3)$, then the perimeter of the polygon is $d(p_1, p_2) + d(p_2, p_3) + \ldots + d(p_k, p_1)$.

For some parameter $k$, let's consider all the polygons that can be formed from the given set of points, having any $k$ vertices, such that the polygon is not self-intersecting. For each such polygon, let's consider its perimeter. Over all such perimeters, we define $f(k)$ to be the maximal perimeter.

Please note, when checking whether a polygon is self-intersecting, that the edges of a polygon are still drawn as straight lines. For instance, in the following pictures:

 [Image]

In the middle polygon, the order of points ($p_1, p_3, p_2, p_4$) is not valid, since it is a self-intersecting polygon. The right polygon (whose edges resemble the Manhattan distance) has the same order and is not self-intersecting, but we consider edges as straight lines. The correct way to draw this polygon is ($p_1, p_2, p_3, p_4$), which is the left polygon.

Your task is to compute $f(3), f(4), \ldots, f(n)$. In other words, find the maximum possible perimeter for each possible number of points (i.e. $3$ to $n$).

-----Input-----

The first line contains a single integer $n$ ($3 \leq n \leq 3\cdot 10^5$) — the number of points.

Each of the next $n$ lines contains two integers $x_i$ and $y_i$ ($-10^8 \leq x_i, y_i \leq 10^8$) — the coordinates of point $p_i$.

The set of points is guaranteed to be...

import sys
input = sys.stdin.readline
out = sys.stdout

n = int(input())
x = []
y = []
for i in range(n):
    xi, yi = map(int, input().split())
    x.append(xi)
    y.append(yi)
min_x = min(x)
max_x = max(x)
min_y = min(y)
max_y = max(y)
answer = 0
for i in range(n):
    dx = max(max_x - x[i], x[i] - min_x)
    dy = max(max_y - y[i], y[i] - min_y)
    answer = max(answer, dx + dy)
out.write(str(2*answer) + ' ')
for i in range(4, n + 1):
    out.write(str(2*(max_x - min_x + max_y - min_y)) + ' ')


Solve in Python:
You are given $n$ strings $a_1, a_2, \ldots, a_n$: all of them have the same length $m$. The strings consist of lowercase English letters.

Find any string $s$ of length $m$ such that each of the given $n$ strings differs from $s$ in at most one position. Formally, for each given string $a_i$, there is no more than one position $j$ such that $a_i[j] \ne s[j]$.

Note that the desired string $s$ may be equal to one of the given strings $a_i$, or it may differ from all the given strings.

For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.

-----Input-----

The first line contains an integer $t$ ($1 \le t \le 100$) — the number of test cases. Then $t$ test cases follow.

Each test case starts with a line containing two positive integers $n$ ($1 \le n \le 10$) and $m$ ($1 \le m \le 10$) — the number of strings and their length.

Then follow $n$ strings $a_i$, one per line. Each of them has length $m$ and consists of lowercase English letters.

-----Output-----

Print $t$ answers to the test cases. Each answer (if it exists) is a string of length $m$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).

-----Example-----
Input
5
2 4
abac
zbab
2 4
aaaa
bbbb
3 3
baa
aaa
aab
2 2
ab
bb
3 1
a
b
c

Output
abab
-1
aaa
ab
z

-----Note-----

The first test case was explained in the statement.

In the second test case, the answer does not exist.

import sys
input = sys.stdin.readline

t=int(input())
for tests in range(t):
    n,m=list(map(int,input().split()))
    A=[input().strip() for i in range(n)]

    X=A[0]
    flag=0

    for i in range(m):
        for j in range(26):
            Y=X[:i]+chr(97+j)+X[i+1:]

            for k in range(n):
                score=0
                for l in range(m):
                    if Y[l]!=A[k][l]:
                        score+=1
                if score<=1:
                    True
                else:
                    break
            else:
                print(Y)
                flag=1
                break
        if flag:
            break
    if flag==0:
        print(-1)


Solve in Python:
You are given 2 numbers is `n` and `k`. You need to find the number of integers between 1 and n (inclusive) that contains exactly `k` non-zero digit.

Example1

`
almost_everywhere_zero(100, 1) return 19`

by following condition we have 19 numbers that have k = 1 digits( not count zero )
` [1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100]`

Example2

`
almost_everywhere_zero(11, 2) return 1`

we have only `11` that has 2 digits(ten not count because zero is not count)
` 11`

constrains

`1≤n<pow(10,100)`

`1≤k≤100`

def fact(n):
    if n == 1 or n == 0:
        return 1
    else:
        return n * fact(n-1)

def C(n,k):
    if n < k:
        return 0
    return fact(n)//(fact(k)*fact(n-k))

def almost_everywhere_zero(n,k):
    if n == 0 and k > 0:
        return 0
    if k == 0:
        return 1
    ntoString = str(n)
    digits = len(ntoString)
    first_digit = int(ntoString[0])
    tight = 0 if len(ntoString) < 2 else int(ntoString[1:])
    # print(n,k,tight,first_digit,digits)
    return (first_digit-1)*(9**(k-1))*C(digits-1,k-1) + almost_everywhere_zero(tight, k-1) + (9**k)*C(digits-1, k)