Solve in Python:
Many websites use weighted averages of various polls to make projections for elections. They’re weighted based on a variety of factors, such as historical accuracy of the polling firm, sample size, as well as date(s). The weights, in this kata, are already calculated for you. All you need to do is convert a set of polls with weights, into a fixed projection for the result.

#### Task:

Your job is to convert an array of candidates (variable name `candidates`) and an array of polls (variable name `polls`), each poll with two parts, a result and a weight, into a guess of the result, with each value rounded to one decimal place, through use of a weighted average. Weights can be zero! Don't worry about the sum not totalling 100. The final result should be a hash in Ruby and Crystal, dictionary in Python, or object in JS in the format shown below:

```python
{
  "": "",
  "": "",
  ...
}

For your convenience, a function named round1 has been defined for you. You can
use it to round to the nearest tenth correctly (due to the inaccuracy of round
and floats in general).
```

_The input should not be modified._

#### Calculation for projections:

```
[(poll1 * weight1) + (poll2 * weight2) + ...] / (weight1 + weight2 + ...)
```

#### An example:

```python
candidates = ['A', 'B', 'C']

poll1res = [20, 30, 50]
poll1wt = 1
poll1 = [poll1res, poll1wt]

poll2res = [40, 40, 20]
poll2wt = 0.5
poll2 = [poll2res, poll2wt]

poll3res = [50, 40, 10]
poll3wt = 2
poll3 = [poll3res, poll3wt]

polls = [poll1, poll2, poll3]

predict(candidates, polls)
#=> {
     'A': 40,
     'B': 37.1,
     'C': 22.9
    }

# because...

candidate 'A' weighted average
  = ((20 * 1) + (40 * 0.5) + (50 * 2)) / (1 + 0.5 + 2)
  = (20 + 20 + 100) / 3.5
  = 140 / 3.5
  = 40

candidate 'B' weighted average
  = ((30 * 1) + (40 * 0.5) + (40 * 2)) / (1 + 0.5 + 2)
  = (30 + 20 + 80) / 3.5
  = 130 / 3.5
  = 37.142857...
  ≈ 37.1 (round to nearest tenth)

candidate 'C' weighted average
  = ((50 * 1) + (20 * 0.5) + (10 * 2)) / (1 + 0.5 + 2)
  = (50 + 10 + 20) /...

from operator import itemgetter
from numpy import average

def predict(candidates, polls):
    votes = zip(*map(itemgetter(0), polls))
    weights = list(map(itemgetter(1), polls))
    return {x:round1(average(next(votes), weights=weights)) for x in candidates}


Solve in Python:
Many years ago, Roman numbers were defined by only `4` digits: `I, V, X, L`, which represented `1, 5, 10, 50`. These were the only digits used. The value of a sequence was simply the sum of digits in it. For instance:
```
IV = VI = 6
IX = XI = 11
XXL = LXX = XLX = 70
```
It is easy to see that this system is ambiguous, and some numbers could be written in many different ways. Your goal is to determine how many distinct integers could be represented by exactly `n` Roman digits grouped together. For instance:
```Perl
solve(1) = 4, because groups of 1 are [I, V, X, L].
solve(2) = 10, because the groups of 2 are [II, VI, VV, XI, XV, XX, IL, VL, XL, LL] corresponding to [2,6,10,11,15,20,51,55,60,100].
solve(3) = 20, because groups of 3 start with [III, IIV, IVV, ...etc]
```

`n <= 10E7`

More examples in test cases. Good luck!


Solve in Python:
Mark loves eating chocolates and also likes to be fit. Given the calorie count for every chocolate he eats, find what he has to do to burn the calories.
The name of the chocolates along with its calorie count are given as follows:
Calories per one whole bar:
Dairy milk (D)
238
Twix (T)
244
Milky Bar (M)
138
Bounty (B)
279
Crunchie (C)
186
The exercises preferred by him and the calories burnt are as follows:
Calories burnt per km:
Running
50
Cycling
5
Walking
0.5
Find the number of kilometers he has to run, cycle or walk to burn all of the calories.
Priority given to the exercises is as follows:
Running > Cycling > Walking

-----Input:-----
- It is a one line string consisting of the names(initial letter) of all the chocolates he has eaten.

-----Output:-----
Print three lines. First line representing how much he ran(in km), second line representing how much he cycled(in km), third line representing how much he walked(in km).

-----Constraints-----
- 1 <= length of input string <= 10.

-----Sample Input:-----
DDTM

-----Sample Output:-----
17
1
6

-----EXPLANATION:-----
Calorie intake = 238 + 238 + 244 + 138 = 858
( 17km x 50 ) + ( 1km x 5 ) + ( 6km x 0.5 ) = 858.

# cook your dish here

d = { 'D': 238, 'T': 244, 'M': 138, 'B': 279, 'C': 186 }

s = list(input())
totalCal = 0

for i in range(len(s)):
    if s[i] == 'D':
        totalCal += d['D']
    if s[i] == 'T':
        totalCal += d['T']
    if s[i] == 'M':
        totalCal += d['M']
    if s[i] == 'B':
        totalCal += d['B']
    if s[i] == 'C':
        totalCal += d['C']

R = totalCal // 50
Rm = totalCal % 50
C = Rm // 5
Cm = Rm % 5
x = totalCal - (R * 50 + C * 5)
# print(totalCal - R * 50 + C * 5)
W = int(x * 4 * 0.5)
# print(R * 50 + C * 5 + W * 0.5)
print(R)
print(C)
print(W)


Solve in Python:
Martha — as a professional problemsetter — proposed a problem for a world-class contest. This is the problem statement:

Tomorrow is Nadia's birthday, and Bardia (her brother) is assigned to make the balloons ready!

There are n balloons (initially empty) that are tied to a straight line on certain positions x_1, x_2, ..., x_{n}. Bardia inflates the balloons from left to right. As a result, i-th balloon gets bigger and bigger until its radius reaches the pressure endurance p_{i} or it touches another previously-inflated balloon. [Image]

While Bardia was busy with the balloons, he wondered "What will be the sum of radius of balloons after all of the balloons are inflated?". Being a nerdy type of guy, he is now thinking about the problem instead of preparing his sister's birthday. Calculate the answer to Bardia's problem so that Nadia's birthday won't be balloon-less.

Artha — Martha's student — claimed his solution got accepted. Martha (being his teacher for a long time!) knew he couldn't have solved the problem for real and thus thinks there is something wrong with the testcases. Artha isn't anyhow logical, which means there is no way for Martha to explain the wrong point in his algorithm. So, the only way is to find a testcase to prove him wrong!

Artha's pseudo-code is shown below: [Image]

You should output a small testcase for the problem such that Artha's algorithm is incorrect. The algorithm's output is considered correct if it differs from the correct value by no more than 1.

-----Input-----

Please pay attention! No input will be given to your program for this problem. So you do not have to read from the input anything.

-----Output-----

You should output the generated small testcase (which Artha's solution doesn't get it right). It should be in the following format:  First line must contain the only number n (1 ≤ n ≤ 500).  The i-th of the next n lines should contain the description of the i-th balloon — two space-separated integers x_{i}, p_{i} (1 ≤ p_{i} ≤ 10^6, 0 ≤ x_1 < x_2 < ... < x_{n} ≤...


Solve in Python:
Mary wrote a recipe book and is about to publish it, but because of a new European law, she needs to update and include all measures in grams.

Given all the measures in tablespoon (`tbsp`) and in teaspoon (`tsp`), considering `1 tbsp = 15g` and `1 tsp = 5g`, append to the end of the measurement the biggest equivalent integer (rounding up).

## Examples

```
"2 tbsp of butter"    -->  "2 tbsp (30g) of butter"

"1/2 tbsp of oregano" -->  "1/2 tbsp (8g) of oregano"

"1/2 tsp of salt"     -->  "1/2 tbsp (3g) of salt"

"Add to the mixing bowl and coat well with 1 tbsp of olive oil & 1/2 tbsp of dried dill" -->
"Add to the mixing bowl and coat well with 1 tbsp (15g) of olive oil & 1/2 tbsp (8g) of dried dill"
```

import re
from math import ceil

P_RECIPE = re.compile(r'([\d/]+) (tb?sp)')

def convert_recipe(recipe): return P_RECIPE.sub(update, recipe)

def update(m):
    toGrams = ceil(eval(m.group(1)) * (15 if m.group(2)=='tbsp' else 5))
    return "{} {} ({}g)".format(m.group(1), m.group(2), toGrams)


Solve in Python:
Mash 2 arrays together so that the returning array has alternating elements of the 2 arrays . Both arrays will always be the same length.

eg. [1,2,3] + ['a','b','c'] =  [1, 'a', 2, 'b', 3, 'c']

def array_mash(a, b):
    return [x for xs in zip(a, b) for x in xs]


Solve in Python:
Masha and Grisha like studying sets of positive integers.

One day Grisha has written a set A containing n different integers a_{i} on a blackboard. Now he asks Masha to create a set B containing n different integers b_{j} such that all n^2 integers that can be obtained by summing up a_{i} and b_{j} for all possible pairs of i and j are different.

Both Masha and Grisha don't like big numbers, so all numbers in A are from 1 to 10^6, and all numbers in B must also be in the same range.

Help Masha to create the set B that satisfies Grisha's requirement.

-----Input-----

Input data contains multiple test cases. The first line contains an integer t — the number of test cases (1 ≤ t ≤ 100).

Each test case is described in the following way: the first line of the description contains one integer n — the number of elements in A (1 ≤ n ≤ 100).

The second line contains n integers a_{i} — the elements of A (1 ≤ a_{i} ≤ 10^6).

-----Output-----

For each test first print the answer:   NO, if Masha's task is impossible to solve, there is no way to create the required set B.  YES, if there is the way to create the required set. In this case the second line must contain n different positive integers b_{j} — elements of B (1 ≤ b_{j} ≤ 10^6). If there are several possible sets, output any of them.

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

Output
YES
1 2 3
YES
1
YES
1 2

'''
from random import randint

visited = [-1] * (2 * 10 ** 6 + 1)
t = int(input())
for i in range(t):
    n, A = int(input()), list(map(int, input().split()))
    A.sort()
    res = [1] * n
    v = 1
    cnt = 0
    while cnt < n:
        #v = randint(1, 10**6)
        if all(visited[a + v] != i for a in A):
            for a in A:
                visited[a + v] = i
            res[cnt] = v
            cnt += 1
        v += 1
    print("YES\n" + ' '.join(map(str,res)))
'''

t = int(input())

def check(arr,v,dic):
    for i in arr:
        if dic[i+v] == 1:
            return True
    return False

def check2(arr,v,dic):
    ok = False
    for i in arr:
        if dic[i+v] == 1:
            ok = True
            break
    return ok

def check3(arr,v,dic):
    return any(dic[a + v] == 1 for a in arr)

dic = [0]*2000005

for _ in range(t):
    n = int(input())
    arr = list(map(int,input().split()))
    arr.sort()
    brr = [1]*n
    cnt = 0
    i = 1
    flag = True
    tmp = {}
    while cnt < n:
        '''
        while check(arr,i,dic):
            i += 1
        brr[cnt] = i

        for v in arr:
            #if i+v>2e6:
            #    break
            dic[i+v] = 1
            tmp[i+v] = 1
        cnt += 1
        '''
        #while any(dic[a + i] != 0 for a in arr):
        #    i += 1

        #while check3(arr, i, dic):
        #    i += 1

        ok = True
        for a in arr:
            if dic[a + i] == 1:
                ok = False
                break

        if not ok:
            i += 1
            continue

        for a in arr:
            dic[a + i] = 1
            tmp[a + i] = 1
        brr[cnt] = i
        cnt += 1
        i += 1
    if flag:
        print("YES")
        print(" ".join(map(str,brr)))
    else:
        print("NO")
    for k in list(tmp.keys()):
        dic[k] = 0


Solve in Python:
Master Oogway has forseen that a panda named Po will be the dragon warrior, and the master of Chi. But he did not tell anyone about the spell that would make him the master of Chi, and has left Po confused. Now Po has to defeat Kai, who is the super villian, the strongest of them all. Po needs to master Chi, and he finds a spell which unlocks his powerful Chi. But the spell is rather strange. It asks Po to calculate the factorial of a number! Po is very good at mathematics, and thinks that this is very easy. So he leaves the spell, thinking it's a hoax. But little does he know that this can give him the ultimate power of Chi. Help Po by solving the spell and proving that it's not a hoax.

-----Input-----
First line of input contains an integer T denoting the number of test cases.
The next T lines contain an integer N.

-----Output-----
For each test case, print a single line containing the solution to the spell which is equal to factorial of N, i.e. N!. Since the output could be large, output it modulo 1589540031(Grand Master Oogway's current age).

-----Constraints-----
- 1 ≤ T ≤ 100000
- 1 ≤ N ≤ 100000

-----Example-----
Input:
4
1
2
3
4

Output:
1
2
6
24

T=int(input())
a=[]
a.append(1)
for j in range(10**5+1):
 a.append(a[j]*(j+1)%1589540031)
for i in range(T):
 N=int(input())
 print(a[N])


Solve in Python:
Master Shifu is training Po to become The Dragon Warrior and as a final assignment he must obtain maximum deliciousness from dumplings. There are  $N$ plates of dumplings in front of him with deliciousness $A_1, A_2, \ldots, A_N$, Po can choose any number of continuous plates of  dumplings. The total deliciousness is the sum of deliciousness of all the  chosen dumplings.
What is the minimum number of plates he must choose so that total deliciousness is maximum possible?
Note: Po must choose atleast one plate.

-----Input:-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.

-----Output:-----
For each test case, print a single line containing one integer.

-----Constraints-----
- $1 \le T \le 10$
- $1 \le N \le 2 \cdot 10^5$
- $0 \le A_i \le 10^9$

-----Sample Input:-----
2
4
1 2 3 4
5
3 2 0 3 0

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

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

while t>0:
    n = input()
    ls = input()
    ls=ls.split()
    st=""
    for i in ls:
        if i=="0":
            st+=" "
        else:
            st+="x"

    if len(st.strip())==0:
        print(1)
    else:
        print(len(st.strip()))
    t-=1


Solve in Python:
Math geeks and computer nerds love to anthropomorphize numbers and assign emotions and personalities to them. Thus there is defined the concept of a "happy" number. A happy number is defined as an integer in which the following sequence ends with the number 1.

* Start with the number itself.
* Calculate the sum of the square of each individual digit.
* If the sum is equal to 1, then the number is happy. If the sum is not equal to 1, then repeat steps 1 and 2. A number is considered unhappy once the same number occurs multiple times in a sequence because this means there is a loop and it will never reach 1.

For example, the number 7 is a "happy" number:

7^(2) = 49 --> 4^(2) + 9^(2) = 97 --> 9^(2) + 7^(2) = 130 --> 1^(2) + 3^(2) + 0^(2) = 10 --> 1^(2) + 0^(2) = 1

Once the sequence reaches the number 1, it will stay there forever since 1^(2) = 1

On the other hand, the number 6 is not a happy number as the sequence that is generated is the following: 6, 36, 45, 41, 17, 50, 25, 29, 85, 89, 145, 42, 20, 4, 16, 37, 58, 89

Once the same number occurs twice in the sequence, the sequence is
guaranteed to go on infinitely, never hitting the number 1, since it repeat
this cycle.

Your task is to write a program which will print a list of all happy numbers between 1 and x (both inclusive), where:
```python
2 <= x <= 5000
```

___

Disclaimer: This Kata is an adaptation of a HW assignment I had for McGill University's COMP 208 (Computers in Engineering) class.

___

If you're up for a challenge, you may want to try a [performance version of this kata](https://www.codewars.com/kata/happy-numbers-performance-edition) by FArekkusu.

def happy_numbers(n):
    HappyNumbers = []
    for i in range(n+1):
        AlreadyGoneThrough = []
        a = i
        while a != 1 and a not in AlreadyGoneThrough:
            b = 0
            AlreadyGoneThrough.append(a)

            for digit in str(a):
                b = b + int(digit)**2

            a = b

        if a in AlreadyGoneThrough:
            pass

        elif a == 1:
            HappyNumbers.append(i)
    return HappyNumbers


Solve in Python:
Math hasn't always been your best subject, and these programming symbols always trip you up!

I mean, does `**` mean *"Times, Times"* or *"To the power of"*?

Luckily, you can create the function `expression_out()` to write out the expressions for you!

The operators you'll need to use are:

```python
{ '+':   'Plus ',
  '-':   'Minus ',
  '*':   'Times ',
  '/':   'Divided By ',
  '**':  'To The Power Of ',
  '=':   'Equals ',
  '!=':  'Does Not Equal ' }
```

These values will be stored in the preloaded dictionary `OPERATORS` just as shown above.

But keep in mind: INVALID operators will also be tested, to which you should return `"That's not an operator!"`

And all of the numbers will be `1` to`10`!
Isn't that nice!

Here's a few examples to clarify:

```python
expression_out("4 ** 9") == "Four To The Power Of Nine"
expression_out("10 - 5") == "Ten Minus Five"
expression_out("2 = 2")  == "Two Equals Two"
```

Good luck!

op = {'+': 'Plus ','-': 'Minus ','*': 'Times ', '/': 'Divided By ', '**': 'To The Power Of ', '=': 'Equals ', '!=': 'Does Not Equal '}
num = {'1': 'One', '2': 'Two', '3': 'Three', '4': 'Four', '5': 'Five', '6': 'Six', '7':'Seven', '8': 'Eight', '9': 'Nine', '10': 'Ten'}

def expression_out(e):
    a, b, c = e.split()
    try    : return num[a]+' '+op[b]+num[c]
    except : return 'That\'s not an operator!'


Solve in Python:
Mathison and Chef are playing a new teleportation game. This game is played on a $R \times C$ board where each cell $(i, j)$ contains some value $V_{i, j}$. The purpose of this game is to collect a number of values by teleporting from one cell to another. A teleportation can be performed using a tel-pair.
A player is given $N$ tel-pairs. Each tel-pair can be used at most once and a player can use them in any order they like. Suppose a player is at cell $(a, b)$ and the tel-pair is $(dx, dy)$. Then, the player can reach in one teleportation any cell $(c, d)$ from $(a, b)$ such that $|a − c| = dx$ and $|b − d| = dy$.
It is Mathison’s turn next in the game to make a sequence of moves. He would like to know what is the highest value of a path of length at most $N+1$ that starts in $(Sx, Sy)$ and uses some (possibly none) of the tel-pairs given. The length of a path is equal to the number of cells in the path. The value of a path is equal to the sum of $V_{i, j}$ over all cells in the path.

-----Input-----
- The first line contains a single integer, $T$, the number of tests.
- Each test starts with three integers, $R$, $C$, and $N$, representing the number of rows, columns, and tel-pairs.
- The next line contains two integers, $Sx$, and $Sy$, representing the coordinates of the starting cell.
- The next two lines will contain the description of the tel-pairs, each containing $N$ space separated integers. The first will contain the $x$-component of each tel-pair, the second one will contain the y-component of each tel-pair.
- Finally, there will be $R$ lines, each containing $C$ space-separated integers, the description of the board.

-----Output-----
The output file will contain $T$ lines. Each line will contain the answer (i.e. the highest value of a path) to the corresponding test.

-----Constraints and notes-----
- $1 \leq T \leq 100$
- $1 \leq R, C \leq 1000$
- $1 \leq N \leq 9$
- $0 \leq Sx < R$
- $0 \leq Sy < C$
- $0 \leq dx \leq R$
- $0 \leq dy \leq C$
- $1 \leq V_{i, j} \leq 10^6$
- You are allowed to...

# cook your dish here
from collections import namedtuple

CurrentPosition = namedtuple('current_position', 'points, cell, pairs')

T = int(input())
for _ in range(T):
    R, C, N = map(int, input().split())
    Sx, Sy = map(int, input().split())
    tx = map(int, input().split())
    ty = map(int, input().split())
    tel_pairs = list(zip(tx, ty))
    board = []
    for _ in range(R):
        board += [[int(c) for c in input().split()]]

    def explore(p):
        next_pos = []
        for i, (dx, dy) in enumerate(p.pairs):
            sx, sy = p.cell
            new_pairs = p.pairs[:i]+p.pairs[i+1:]
            # case (+, +)
            px, py = sx + dx, sy + dy
            if px < R and py < C:
                next_pos += [CurrentPosition(p.points+board[px][py], (px, py), new_pairs)]
            # case (+, -)
            px, py = sx + dx, sy - dy
            if px < R and 0 <= py:
                next_pos += [CurrentPosition(p.points+board[px][py], (px, py), new_pairs)]
            # case (-, +)
            px, py = sx - dx, sy + dy
            if 0 <= px and py < C:
                next_pos += [CurrentPosition(p.points+board[px][py], (px, py), new_pairs)]
            # case (-, -)
            px, py = sx - dx, sy - dy
            if 0 <= px and 0 <= py:
                next_pos += [CurrentPosition(p.points+board[px][py], (px, py), new_pairs)]
        return next_pos

    pos = [CurrentPosition(board[Sx][Sy], (Sx, Sy), tel_pairs)]
    result = board[Sx][Sy]
    while pos:
        p = pos.pop(0)
        if p.pairs:
            pos += explore(p)
        else:
            result = max(result, p.points)

    print(result)


Solve in Python:
Mathison recently inherited an ancient papyrus that contained some text. Unfortunately, the text was not a
pangram. Now, Mathison has a particular liking for holoalphabetic strings and the text bothers him. The good news is that Mathison can buy letters from the local store in order to turn his text into a pangram.

However, each letter has a price and Mathison is not very rich. Can you help Mathison find the cheapest way to obtain a pangram?

-----Input-----
The first line of the input file will contain one integer, T, representing the number of tests.
Each test will be formed from two lines. The first one contains 26 space-separated integers, representing the prices of all letters.
The second will contain Mathison's initial text (a string of N lowercase letters).

-----Output-----
The output file will contain T lines, one for each test. Each line will contain the answer for the corresponding test.

-----Constraints and notes-----
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 50,000
- All prices are natural numbers between 1 and 1,000,000 (i.e. 106).
- A pangram is a string that contains every letter of the Latin alphabet at least once.
- All purchased letters are added to the end of the string.

-----Subtaks-----
Subtask #1 (30 points):

- N = 1

Subtask #2 (70 points):

- Original constraints

-----Example-----
Input:
2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
abcdefghijklmopqrstuvwz
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
thequickbrownfoxjumpsoverthelazydog

Output:
63
0

-----Explanation-----
First test
There are three letters missing from the original string: n (price 14), x (price 24), and y (price 25).
Therefore the answer is 14 + 24 + 25 = 63.

Second test
No letter is missing so there is no point in buying something. The answer is 0.

# cook your dish here
for i in range(int(input())):
 a=list(map(int,input().split()))
 x=input()
 t=0
 for i in range(97,123):
  if chr(i) not in x:
   t+=a[i-97]
 print(t)


Solve in Python:
Maxim always goes to the supermarket on Sundays. Today the supermarket has a special offer of discount systems.

There are m types of discounts. We assume that the discounts are indexed from 1 to m. To use the discount number i, the customer takes a special basket, where he puts exactly q_{i} items he buys. Under the terms of the discount system, in addition to the items in the cart the customer can receive at most two items from the supermarket for free. The number of the "free items" (0, 1 or 2) to give is selected by the customer. The only condition imposed on the selected "free items" is as follows: each of them mustn't be more expensive than the cheapest item out of the q_{i} items in the cart.

Maxim now needs to buy n items in the shop. Count the minimum sum of money that Maxim needs to buy them, if he use the discount system optimally well.

Please assume that the supermarket has enough carts for any actions. Maxim can use the same discount multiple times. Of course, Maxim can buy items without any discounts.

-----Input-----

The first line contains integer m (1 ≤ m ≤ 10^5) — the number of discount types. The second line contains m integers: q_1, q_2, ..., q_{m} (1 ≤ q_{i} ≤ 10^5).

The third line contains integer n (1 ≤ n ≤ 10^5) — the number of items Maxim needs. The fourth line contains n integers: a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^4) — the items' prices.

The numbers in the lines are separated by single spaces.

-----Output-----

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

-----Examples-----
Input
1
2
4
50 50 100 100

Output
200

Input
2
2 3
5
50 50 50 50 50

Output
150

Input
1
1
7
1 1 1 1 1 1 1

Output
3

-----Note-----

In the first sample Maxim needs to buy two items that cost 100 and get a discount for two free items that cost 50. In that case, Maxim is going to pay 200.

In the second sample the best strategy for Maxim is to buy 3 items and get 2 items for free using the discount. In that case, Maxim is going to pay 150.

input()
k = min(map(int, input().split()))
n = int(input())
p = sorted(map(int, input().split()), reverse = True) + [0] * k
print(sum(sum(p[i: i + k]) for i in range(0, n, k + 2)))


Solve in Python:
Maya writes weekly articles to a well known magazine, but she is missing one word each time she is about to send the article to the editor. The article is not complete without this word. Maya has a friend, Dan, and he is very good with words, but he doesn't like to just give them away. He texts Maya a number and she needs to find out the hidden word.
The words can contain only the letter: "a", "b", "d", "e", "i", "l", "m", "n", "o", and "t".

Luckily, Maya has the key:

"a" - 6
"b" - 1
"d" - 7
"e" - 4
"i" - 3
"l" - 2
"m" - 9
"n" - 8
"o" - 0
"t" - 5

You can help Maya by writing a function that will take a number between 100 and 999999 and return a string with the word.

The input is always a number, contains only the numbers in the key.
The output should be always a string with one word, all lowercase.

Maya won't forget to thank you at the end of her article :)


Solve in Python:
Meanwhile, Candace and Stacy are busy planning to attend the concert of the famous Love Händel. Jeremy will also be attending the event. Therefore, Candace plans to offer the best possible gift to Jeremy.
Candace has $N$ strings, each of length $M$. Each character of each string can either be a lowercase English letter or the character '#'. She denotes the substring of $i$-$th$ string starting from the $l$-$th$ character and ending with the $r$-$th$ character as $S_{i}[l, r]$. She has to choose a list $a$ of $N - 1$ numbers such that
- $1 \leq a_1 \leq a_2 \leq a_3 \leq ... \leq a_{N-1} \leq  M$.
- The final gift string is obtained by appending the substrings $S_{1}[1, a_{1}]$, $S_{2}[a_{1}, a_{2}]$, $S_{3}[a_{2}, a_{3}]$, .., $S_{N-1}[a_{N-2}, a_{N-1}]$, $S_{N}[a_{N-1}, M]$.
- Candace considers the gift to be the most beautiful one if the final gift string is the lexicographically smallest possible string and it doesn't contain the '#' character.
Let $P$ = $S_{1}[1, a_{1}]$ + $S_{2}[a_{1}, a_{2}]$ + $S_{3}[a_{2}, a_{3}]$ + .., + $S_{N-1}[a_{N-2}, a_{N-1}]$ + $S_{N}[a_{N-1}, M]$, then $P$ should be the lexicographically smallest string  possible and it should not contain '#' character, where '+' denotes concatenation of two substrings.
Help Candace find the best possible gift string quickly as she does not want Jeremy to wait for her. Also, it is guaranteed that at least one such valid string exists.

-----Input-----
- The first line contains a single integer $T$ denoting the number of testcases.
- The first line of each test case contains $2$ space separated integers denoting the values of $N$ and $M$ respectively.
- $N$ lines follow. Each line contains a string $S_i$ of length $M$ as described above.

-----Output-----
For every test case, print a line containing lexicographically lowest possible gift string.

-----Constraints-----
- $1 \leq T \leq 10^4$
- $1 \leq N, M \leq 10^6$
- $|S_i| = M$
- All $S_i$ will contain either a lower English letter ('a' to 'z' ) or the character '#' (ASCII $35$).
- Sum of...

# import all important libraries and inbuilt functions

from fractions import Fraction
import numpy as np
import sys,bisect,copyreg,copy,statistics,os
from math import *
from collections import Counter,defaultdict,deque,OrderedDict
from itertools import combinations,permutations,accumulate
from numpy.linalg import matrix_power as mp
from bisect import bisect_left,bisect_right,bisect,insort,insort_left,insort_right
from statistics import mode
from functools import reduce,cmp_to_key
from io import BytesIO, IOBase
from scipy.spatial import ConvexHull
from heapq import *
from decimal import *
from queue import Queue,PriorityQueue
from re import sub,subn

# end of library import

# map system version faults
if sys.version_info[0] < 3:
    from builtins import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

# template of many functions used in competitive programming can add more later
# based on need we will use this commonly.

# bfs in a graph
def bfs(adj,v): # a schema of bfs
    visited=[False]*(v+1);q=deque()
    while q:pass

# definition of vertex of a graph
def graph(vertex): return [[] for i in range(vertex+1)]

def powermodulo(x, y, p) :
    res = 1;x = x % p
    if (x == 0) : return 0
    while (y > 0) :
        if ((y & 1) == 1) :   res = (res * x) % p
        y = y >> 1
        x = (x * x) % p
    return res

def lcm(a,b): return (a*b)//gcd(a,b)

# most common list in a array of lists
def most_frequent(List):return Counter(List).most_common(1)[0][0]

# element with highest frequency
def most_common(List):return(mode(List))

#In number theory, the Chinese remainder theorem states that
#if one knows the remainders of the Euclidean division of an integer n by
#several integers, then one can determine uniquely the remainder of the
#division of n by the product of these integers, under the condition
#that the divisors are pairwise coprime.
def chinese_remainder(a, p):
    prod = reduce(op.mul, p, 1);x = [prod // pi for pi in p]
    return...


Solve in Python:
Meanwhile, the kingdom of K is getting ready for the marriage of the King's daughter. However, in order not to lose face in front of the relatives, the King should first finish reforms in his kingdom. As the King can not wait for his daughter's marriage, reforms must be finished as soon as possible.

The kingdom currently consists of n cities. Cities are connected by n - 1 bidirectional road, such that one can get from any city to any other city. As the King had to save a lot, there is only one path between any two cities.

What is the point of the reform? The key ministries of the state should be relocated to distinct cities (we call such cities important). However, due to the fact that there is a high risk of an attack by barbarians it must be done carefully. The King has made several plans, each of which is described by a set of important cities, and now wonders what is the best plan.

Barbarians can capture some of the cities that are not important (the important ones will have enough protection for sure), after that the captured city becomes impassable. In particular, an interesting feature of the plan is the minimum number of cities that the barbarians need to capture in order to make all the important cities isolated, that is, from all important cities it would be impossible to reach any other important city.

Help the King to calculate this characteristic for each of his plan.

-----Input-----

The first line of the input contains integer n (1 ≤ n ≤ 100 000) — the number of cities in the kingdom.

Each of the next n - 1 lines contains two distinct integers u_{i}, v_{i} (1 ≤ u_{i}, v_{i} ≤ n) — the indices of the cities connected by the i-th road. It is guaranteed that you can get from any city to any other one moving only along the existing roads.

The next line contains a single integer q (1 ≤ q ≤ 100 000) — the number of King's plans.

Each of the next q lines looks as follows: first goes number k_{i} — the number of important cities in the King's plan, (1 ≤ k_{i} ≤ n), then follow exactly k_{i}...

import sys
from collections import deque
def solve():
    sys.setrecursionlimit(10**6)
    readline = sys.stdin.readline
    writelines = sys.stdout.writelines
    N = int(readline())
    G = [[] for i in range(N)]
    for i in range(N-1):
        u, v = map(int, readline().split())
        G[u-1].append(v-1)
        G[v-1].append(u-1)

    # Euler tour technique
    S = []
    FS = [0]*N; LS = [0]*N
    depth = [0]*N
    stk = [-1, 0]
    it = [0]*N
    while len(stk) > 1:
        v = stk[-1]
        i = it[v]
        if i == 0:
            FS[v] = len(S)
            depth[v] = len(stk)
        if i < len(G[v]) and G[v][i] == stk[-2]:
            it[v] += 1
            i += 1
        if i == len(G[v]):
            LS[v] = len(S)
            stk.pop()
        else:
            stk.append(G[v][i])
            it[v] += 1
        S.append(v)

    L = len(S)
    lg = [0]*(L+1)
    # Sparse Table
    for i in range(2, L+1):
        lg[i] = lg[i >> 1] + 1
    st = [[L]*(L - (1 << i) + 1) for i in range(lg[L]+1)]
    st[0][:] = S
    b = 1
    for i in range(lg[L]):
        st0 = st[i]
        st1 = st[i+1]
        for j in range(L - (b<<1) + 1):
            st1[j] = (st0[j] if depth[st0[j]] <= depth[st0[j+b]] else st0[j+b])
        b <<= 1

    INF = 10**18
    ans = []
    Q = int(readline())
    G0 = [[]]*N
    P = [0]*N
    deg = [0]*N
    KS = [0]*N
    A = [0]*N
    B = [0]*N
    for t in range(Q):
        k, *vs = map(int, readline().split())
        for i in range(k):
            vs[i] -= 1
            KS[vs[i]] = 1
        vs.sort(key=FS.__getitem__)
        for i in range(k-1):
            x = FS[vs[i]]; y = FS[vs[i+1]]
            l = lg[y - x + 1]
            w = st[l][x] if depth[st[l][x]] <= depth[st[l][y - (1 << l) + 1]] else st[l][y - (1 << l) + 1]
            vs.append(w)
        vs.sort(key=FS.__getitem__)
        stk = []
        prv = -1
        for v in vs:
            if v == prv:
                continue
            while stk and LS[stk[-1]] < FS[v]:
                stk.pop()
            if...


Solve in Python:
Meliodas and Ban are fighting over chocolates. Meliodas has $X$ chocolates, while Ban has $Y$. Whoever has lesser number of chocolates eats as many chocolates as he has from the other's collection. This eatfest war continues till either they have the same number of chocolates, or atleast one of them is left with no chocolates.

Can you help Elizabeth predict the total no of chocolates they'll be left with at the end of their war?

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, which contains two integers $X, Y$, the no of chocolates Meliodas and Ban have, respectively.

-----Output:-----
For each testcase, output in a single line the no of chocolates that remain after Ban and Meliodas stop fighting.

-----Constraints-----
- $1 \leq T \leq 100000$
- $0 \leq X,Y \leq 10^9$

-----Sample Input:-----
3

5 3

10 10

4 8

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

20

8

-----EXPLANATION:-----
Denoting Meliodas as $M$, Ban as $B$.
Testcase 1:
$M$=5, $B$=3

Ban eates 3 chocolates of Meliodas.
$M$=2, $B$=3

Meliodas eats 2 chocolates of Ban.
$M$=2, $B$=1

Ban eates 1 chocolate of Meliodas.
$M$=1, $B$=1

Since they have the same no of candies, they stop quarreling.

Total candies left: 2
Testcase 2:
$M$=10, $B$=10

Since both of them had the same candies to begin with, there was no point in fighting.

Total candies left: 20
Testcase 3:
$M$=4, $B$=8

Meliodas eats 4 chocolates of Ban.
$M$=4, $B$=4

Since they have the same no of candies, they stop quarreling.

Total candies left: 8

# cook your dish here
import math
for i in range(int(input())):
 n,m=map(int,input().split())
 if n==m or n==0 or m==0:
  print(n+m)
 else:
  a=math.gcd(n,m)
  print(2*a)


Solve in Python:
Mia is working as a waitress at a breakfast diner. She can take up only one shift from 6 shifts a day i.e. from 10 am to 4 pm. She needs to save 300$ after completion of the month. She works only for $D$ days in the month. She estimates that she gets her highest tip in the first shift and the tip starts decreasing by 2% every hour as the day prolongs. She gets a minimum wage of $X$ $ for every shift. And her highest tip in the first shift is $Y$ $. Determine whether Mia will be able to save 300$ from her wages and tips after working $D$ days of the month. If she can, print YES, else print NO.

-----Constraints-----
- 8 <= D <=30
- 7 <= X <=30
- 4 <= Y <= 20

-----Input:-----
- First line has three parameters $D$, $X$ and $Y$ i.e. number of days worked, minimum wage and highest tip.
- Second line contains D integers indicating her shifts every $i$-th day she has worked.

-----Output:-----
- Print YES, if Mia has saved 300$, NO otherwise.

-----Sample Input:-----
9 17 5
1 3 2 4 5 6 1 2 2

-----Sample Output:-----
NO

-----Explanation:-----
No. of days Mia worked (D) is 9, so minimum wage she earns (X) is 17 dollars. Highest tip at first hour (Y) = 5 dollars, 1st day she took 1st shift and 2nd day she took 3rd shift and so on. Upon calculation we will find that Mia was not able to save 300 dollars.

d, x, y = list(map(int,input().split()))
l = list(map(int,input().split()))

k = [y]

for i in range(6):
    k.append(k[-1]*0.98)

s = x*d

for i in l:
    s += k[i-1]

if s >= 300:
    print("YES")
else:
    print("NO")


Solve in Python:
Mike and Joe are fratboys that love beer and games that involve drinking. They play the following game: Mike chugs one beer, then Joe chugs 2 beers, then Mike chugs 3 beers, then Joe chugs 4 beers, and so on. Once someone can't drink what he is supposed to drink, he loses.

Mike can chug at most A beers in total (otherwise he would pass out), while Joe can chug at most B beers in total. Who will win the game?

Write the function ```game(A,B)``` that returns the winner, ```"Mike"``` or ```"Joe"``` accordingly, for any given integer values of A and B.

Note: If either Mike or Joe cannot drink at least 1 beer, return the string  ```"Non-drinkers can't play"```.

def game(a, b):
    if a*b==0:
        return "Non-drinkers can't play"
    m,j=0,0
    i=1
    while(True):
        if i%2==1:
            m+=i
            if m>a:
                return "Joe"
        else:
            j+=i
            if j>b:
                return "Mike"
        i+=1


Solve in Python:
Mike is the president of country What-The-Fatherland. There are n bears living in this country besides Mike. All of them are standing in a line and they are numbered from 1 to n from left to right. i-th bear is exactly a_{i} feet high.

 [Image]

A group of bears is a non-empty contiguous segment of the line. The size of a group is the number of bears in that group. The strength of a group is the minimum height of the bear in that group.

Mike is a curious to know for each x such that 1 ≤ x ≤ n the maximum strength among all groups of size x.

-----Input-----

The first line of input contains integer n (1 ≤ n ≤ 2 × 10^5), the number of bears.

The second line contains n integers separated by space, a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9), heights of bears.

-----Output-----

Print n integers in one line. For each x from 1 to n, print the maximum strength among all groups of size x.

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

Output
6 4 4 3 3 2 2 1 1 1

n=int(input())
a=[int(o) for o in input().split()]
l=[-1]*n
r=[(n)]*n
stack=[]
for i in range(n):
  #  print(stack)
    while stack and a[stack[-1]]>=a[i]:
        stack.pop()
    if stack:
        l[i]=stack[-1]
    stack.append(i)
stack=[]
for i in range(n-1,-1,-1):
   # print(stack)
    while stack and a[stack[-1]]>=a[i]:
        stack.pop()
    if stack:
        r[i]=stack[-1]
    stack.append(i)
answers=[min(a)]*n
#print(l)
#print(r)

for i in range(n):
  #  print(r,l)
    lw=r[i]-l[i]-2
    #print(lw)

    answers[lw]=max(answers[lw],a[i])

ans=min(a)
answers[0]=max(a)
for i in range(n-1,-1,-1):
    ans=max(ans,answers[i])
    answers[i]=ans
print(*answers)


Solve in Python:
Mikhail walks on a Cartesian plane. He starts at the point $(0, 0)$, and in one move he can go to any of eight adjacent points. For example, if Mikhail is currently at the point $(0, 0)$, he can go to any of the following points in one move:   $(1, 0)$;  $(1, 1)$;  $(0, 1)$;  $(-1, 1)$;  $(-1, 0)$;  $(-1, -1)$;  $(0, -1)$;  $(1, -1)$.

If Mikhail goes from the point $(x1, y1)$ to the point $(x2, y2)$ in one move, and $x1 \ne x2$ and $y1 \ne y2$, then such a move is called a diagonal move.

Mikhail has $q$ queries. For the $i$-th query Mikhail's target is to go to the point $(n_i, m_i)$ from the point $(0, 0)$ in exactly $k_i$ moves. Among all possible movements he want to choose one with the maximum number of diagonal moves. Your task is to find the maximum number of diagonal moves or find that it is impossible to go from the point $(0, 0)$ to the point $(n_i, m_i)$ in $k_i$ moves.

Note that Mikhail can visit any point any number of times (even the destination point!).

-----Input-----

The first line of the input contains one integer $q$ ($1 \le q \le 10^4$) — the number of queries.

Then $q$ lines follow. The $i$-th of these $q$ lines contains three integers $n_i$, $m_i$ and $k_i$ ($1 \le n_i, m_i, k_i \le 10^{18}$) — $x$-coordinate of the destination point of the query, $y$-coordinate of the destination point of the query and the number of moves in the query, correspondingly.

-----Output-----

Print $q$ integers. The $i$-th integer should be equal to -1 if Mikhail cannot go from the point $(0, 0)$ to the point $(n_i, m_i)$ in exactly $k_i$ moves described above. Otherwise the $i$-th integer should be equal to the the maximum number of diagonal moves among all possible movements.

-----Example-----
Input
3
2 2 3
4 3 7
10 1 9

Output
1
6
-1

-----Note-----

One of the possible answers to the first test case: $(0, 0) \to (1, 0) \to (1, 1) \to (2, 2)$.

One of the possible answers to the second test case: $(0, 0) \to (0, 1) \to (1, 2) \to (0, 3) \to (1, 4) \to (2, 3) \to (3, 2) \to (4, 3)$.

In the...

q=int(input())
for i in range(q):
    n, m, k = map(int, input().split())
    ans=max(n,m)
    diff=k-ans
    if diff<0:
        print(-1)
    else:
        if (n%2==0 and m%2==0) or (n%2!=0 and m%2!=0):
            if diff%2==0:
                ans+=diff
            else:
                ans+=diff-2
        else:
            ans+=diff-1
        print(ans)


Solve in Python:
Minion Chef likes to eat bananas a lot. There are N piles of bananas in front of Chef; for each i (1 ≤ i ≤ N), the i-th pile contains Ai bananas.
Chef's mother wants her to eat the bananas and be healthy. She has gone to the office right now and will come back in H hours. Chef would like to make sure that she can finish eating all bananas by that time.
Suppose Chef has an eating speed of K bananas per hour. Each hour, she will choose some pile of bananas. If this pile contains at least K bananas, then she will eat K bananas from it. Otherwise, she will simply eat the whole pile (and won't eat any more bananas during this hour).
Chef likes to eat slowly, but still wants to finish eating all the bananas on time. Therefore, she would like to choose the minimum K such that she is able to eat all the bananas in H hours. Help Chef find that value of K.

-----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 H denoting the number of piles and the number of hours after which Chef's mom will come home.
- The second line contains N space-separated integers A1, A2, ..., AN.

-----Output-----
For each test case, print a single line containing one integer — the minimum possible value of K.

-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 105
- N ≤ H ≤ 109
- 1 ≤ Ai ≤ 109 for each valid i

-----Subtasks-----
Subtask #1 (30 points):
- 1 ≤ N ≤ 100
- Ai ≤ 103 for each valid i

Subtask #2 (70 points): original constraints

-----Example-----
Input:

3
3 3
1 2 3
3 4
1 2 3
4 5
4 3 2 7

Output:

3
2
4

-----Explanation-----
Example case 1: With a speed of K = 3 bananas per hour, Chef can finish eating all the bananas in 3 hours. It's the minimum possible speed with which she can eat all the bananas in 3 hours. With a speed of 2 bananas per hour, she would take at least 4 hours and with a speed of 1 banana per hour, she would take at least 6 hours.

import math
for i in range(int(input())):
 n,k=list(map(int,input().split()))
 a=list(map(int,input().split()))
 m=math.ceil(sum(a)/k)
 if k==n:
  print(max(a))
 else:
  for i in range(m,max(a)+1):
   s=0
   for j in a:
    s+=math.ceil(j/i)
   if s<=k:
    print(i)
    break


Solve in Python:
Mishka wants to buy some food in the nearby shop. Initially, he has $s$ burles on his card.

Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number $1 \le x \le s$, buy food that costs exactly $x$ burles and obtain $\lfloor\frac{x}{10}\rfloor$ burles as a cashback (in other words, Mishka spends $x$ burles and obtains $\lfloor\frac{x}{10}\rfloor$ back). The operation $\lfloor\frac{a}{b}\rfloor$ means $a$ divided by $b$ rounded down.

It is guaranteed that you can always buy some food that costs $x$ for any possible value of $x$.

Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.

For example, if Mishka has $s=19$ burles then the maximum number of burles he can spend is $21$. Firstly, he can spend $x=10$ burles, obtain $1$ burle as a cashback. Now he has $s=10$ burles, so can spend $x=10$ burles, obtain $1$ burle as a cashback and spend it too.

You have to answer $t$ independent test cases.

-----Input-----

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

The next $t$ lines describe test cases. Each test case is given on a separate line and consists of one integer $s$ ($1 \le s \le 10^9$) — the number of burles Mishka initially has.

-----Output-----

For each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.

-----Example-----
Input
6
1
10
19
9876
12345
1000000000

Output
1
11
21
10973
13716
1111111111

for _ in range(int(input())):
    s = int(input())
    k = s
    while s >= 10:
        num = s // 10
        s += s // 10
        s -= num * 10
        k += num
    print(k)


Solve in Python:
Mitya has a rooted tree with $n$ vertices indexed from $1$ to $n$, where the root has index $1$. Each vertex $v$ initially had an integer number $a_v \ge 0$ written on it. For every vertex $v$ Mitya has computed $s_v$: the sum of all values written on the vertices on the path from vertex $v$ to the root, as well as $h_v$ — the depth of vertex $v$, which denotes the number of vertices on the path from vertex $v$ to the root. Clearly, $s_1=a_1$ and $h_1=1$.

Then Mitya erased all numbers $a_v$, and by accident he also erased all values $s_v$ for vertices with even depth (vertices with even $h_v$). Your task is to restore the values $a_v$ for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values $a_v$ for all vertices in the tree.

-----Input-----

The first line contains one integer $n$ — the number of vertices in the tree ($2 \le n \le 10^5$). The following line contains integers $p_2$, $p_3$, ... $p_n$, where $p_i$ stands for the parent of vertex with index $i$ in the tree ($1 \le p_i < i$). The last line contains integer values $s_1$, $s_2$, ..., $s_n$ ($-1 \le s_v \le 10^9$), where erased values are replaced by $-1$.

-----Output-----

Output one integer — the minimum total sum of all values $a_v$ in the original tree, or $-1$ if such tree does not exist.

-----Examples-----
Input
5
1 1 1 1
1 -1 -1 -1 -1

Output
1

Input
5
1 2 3 1
1 -1 2 -1 -1

Output
2

Input
3
1 2
2 -1 1

Output
-1

from collections import defaultdict, deque

n = int(input())
adj = [[] for _ in range(n)]
v = [0] * n
l = list(map(int, input().split()))
for i, f in enumerate(l):
    adj[f - 1].append(i + 1)

s = list(map(int, input().split()))

Q = deque([(0, s[0], s[0])])
ans = 0
flag = False
possible = True
while Q and possible:
    # print(Q)
    flag = not flag
    for _ in range(len(Q)):
        cur, v, curs = Q.popleft()
        if v < 0:
            possible = False
            ans = -1
            break
        ans += v
        if flag:
            for i in adj[cur]:
                if len(adj[i]) <= 1:
                    Q.append((i, 0, curs))
                else:
                    temp = min([s[k] for k in adj[i]])
                    Q.append((i, temp - curs, temp))
        else:
            for i in adj[cur]:
                Q.append((i, s[i] - curs, s[i]))
print(ans)


Solve in Python:
Mobile Display Keystrokes

Do you remember the old mobile display keyboards? Do you also remember how inconvenient it was to write on it?
Well, here you have to calculate how much keystrokes you have to do for a specific word.

This is the layout:

Return the amount of keystrokes of input str (! only letters, digits and special characters in lowercase included in layout without whitespaces !)

e.g:

mobileKeyboard("123") => 3 (1+1+1)
mobileKeyboard("abc") => 9 (2+3+4)
mobileKeyboard("codewars") => 26 (4+4+2+3+2+2+4+5)


Solve in Python:
Modify the `kebabize` function so that it converts a camel case string into a kebab case.

Notes:
  - the returned string should only contain lowercase letters

def kebabize(string):
  return ''.join(c if c.islower() else f'-{c.lower()}' for c in [c for c in string if c.isalpha()]).strip('-')


Solve in Python:
Modify the spacify function so that it returns the given string with spaces inserted between each character.

```python
spacify("hello world") # returns "h e l l o   w o r l d"
```

def spacify(string):
    return " ".join(string)


Solve in Python:
Mohit's girlfriend is playing a game with Nicky. The description of the game is as follows:
- Initially on a table Player 1 will put N gem-stones.
- Players will play alternatively, turn by turn.
- At each move a player can take at most M gem-stones (at least 1 gem-stone must be taken) from the available gem-stones on the table.(Each gem-stone has same cost.)
- Each players gem-stone are gathered in player's side.
- The player that empties the table purchases food from it (using all his gem-stones; one gem-stone can buy one unit of food), and the other one puts all his gem-stones back on to the table. Again the game continues with the "loser" player starting.
- The game continues until all the gem-stones are used to buy food.
- The main objective of the game is to consume maximum units of food.

	Mohit's girlfriend is weak in mathematics and prediction so she asks help from Mohit, in return she shall kiss Mohit. Mohit task is to predict the maximum units of food her girlfriend can eat, if, she starts first. Being the best friend of Mohit, help him in predicting the answer.

-----Input-----
- Single line contains two space separated integers N and M.

-----Output-----
- The maximum units of food Mohit's girlfriend can eat.

-----Constraints and Subtasks-----
- 1 <= M <= N <= 100
Subtask 1: 10 points
- 1 <= M <= N <= 5
Subtask 2: 20 points
- 1 <= M <= N <= 10
Subtask 3: 30 points
- 1 <= M <= N <= 50
Subtask 3: 40 points
- Original Constraints.

-----Example-----
Input:
4 2

Output:
2

read = lambda: list(map(int, input().split()))
read_s = lambda: list(map(str, input().split()))

n, m = read()
ans = 0
while n > 0:
 if n > m:
  ans += m
  n -= 2*m
 else:
  ans += 1
  n -= 2
print(ans)


Solve in Python:
Mohit(Ex GenSec ) is the most active member of the roasting club who loves giving tasks to other members. One day he observed that none of the members were paying attention to the online classes, so he decided to have some fun and overcome the boring lectures. He wrote N numbers on the virtual board (where the first number is 1, the last one is N and the ith number being i).
Then he asked M questions to every other member of the club. In each question, a number K was given by Mohit and the members had to give a single integer as an answer which will be the sum of all numbers present on the whiteboard.
There are some conditions that every member has to follow while answering.
- If K is already present on the whiteboard then swap the first and last number.
- Otherwise, replace the last number with K.

-----Input:-----
- First-line will consist of space-separated integers N and M. The board will contain the list of numbers from 1 to N and M is the number of questions that Mohit will ask.
- Next M lines contain the number Ki, which will be provided by Mohit and (1<=i<=M).

-----Output:-----
For each question, report the sum of all integers present

-----Constraints-----
- $1 \leq N,M \leq 1000000$
- $2 \leq K \leq 10^9$

-----Sample Input:-----
5 4
7
12
10
1

-----Sample Output:-----
17
22
20
20

# cook your dish here

n,m=tuple(map(int,input().split()))
if(n>2):
 arr=[1,n]
elif(n==1):
 arr=[1]
elif(n==2):
 arr=[1,2]

for i in range(m):
 k=int(input())
 if(n==1):
  if(k!=arr[0]):
   arr[0]=k
  print(arr[0])
 elif(n==2):
  if(k==arr[0] or k==arr[1]):
   temp=arr[0]
   arr[0]=arr[1]
   arr[1]=temp
  else:
   arr[1]=k

  print(arr[0]+arr[1])

 else:
  ans=int(n*(n+1)/2)-1-n
  if(k==arr[0] or k==arr[1]):
   temp=arr[0]
   arr[0]=arr[1]
   arr[1]=temp
  elif(k>1 and k<n):
   temp=arr[0]
   arr[0]=arr[1]
   arr[1]=temp
  else:
   arr[1]=k
  ans+=arr[0]+arr[1]
  print(ans)


Solve in Python:
Momiji has got a rooted tree, consisting of n nodes. The tree nodes are numbered by integers from 1 to n. The root has number 1. Momiji decided to play a game on this tree.

The game consists of several steps. On each step, Momiji chooses one of the remaining tree nodes (let's denote it by v) and removes all the subtree nodes with the root in node v from the tree. Node v gets deleted as well. The game finishes when the tree has no nodes left. In other words, the game finishes after the step that chooses the node number 1.

Each time Momiji chooses a new node uniformly among all the remaining nodes. Your task is to find the expectation of the number of steps in the described game.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^5) — the number of nodes in the tree. The next n - 1 lines contain the tree edges. The i-th line contains integers a_{i}, b_{i} (1 ≤ a_{i}, b_{i} ≤ n; a_{i} ≠ b_{i}) — the numbers of the nodes that are connected by the i-th edge.

It is guaranteed that the given graph is a tree.

-----Output-----

Print a single real number — the expectation of the number of steps in the described game.

The answer will be considered correct if the absolute or relative error doesn't exceed 10^{ - 6}.

-----Examples-----
Input
2
1 2

Output
1.50000000000000000000

Input
3
1 2
1 3

Output
2.00000000000000000000

-----Note-----

In the first sample, there are two cases. One is directly remove the root and another is remove the root after one step. Thus the expected steps are: 1 × (1 / 2) + 2 × (1 / 2) = 1.5

In the second sample, things get more complex. There are two cases that reduce to the first sample, and one case cleaned at once. Thus the expected steps are: 1 × (1 / 3) + (1 + 1.5) × (2 / 3) = (1 / 3) + (5 / 3) = 2

# https://codeforces.com/problemset/problem/280/C
from collections import defaultdict, deque
import sys

nodes = int(sys.stdin.readline())
edges = defaultdict(list)
for line in sys.stdin:
    a, b = line.split()
    a = int(a)
    b = int(b)
    edges[a].append(b)
    edges[b].append(a)
bfs = deque([(1, 1)])
depths = {}
while bfs:
    nid, depth = bfs.popleft()
    if nid in depths:
        continue
    depths[nid] = depth
    for n2 in edges[nid]:
        bfs.append((n2, depth + 1))
print(sum(1.0 / d for d in sorted(depths.values(), reverse=True)))


Solve in Python:
Monisha likes to paint. She has painted $N$ paintings (numbered $1$ through $N$) and wants to choose some subset of these paintings for an exhibition. For each valid $i$, the $i$-th painting has beauty $b_i$ and the probability that it will be displayed at the exhibition is $p_i$. Each painting is chosen or excluded from the exhibition independently randomly.
The beauty of the resulting exhibition is the bitwise XOR of the beauties of all displayed paintings. If no paintings are displayed, the XOR is $0$.
Monisha wants to find out how beautiful her exhibition is going to be. Help her compute the expected value of the beauty of the exhibition.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- The second line contains $N$ space-separated integers $b_1, b_2, \ldots, b_N$.
- The third line contains $N$ space-separated real numbers $p_1, p_2, \ldots, p_N$. Each of these numbers is given with at most five digits after the decimal point.

-----Output-----
For each test case, print a single line containing one real number — the expected beauty of the exhibition. Your answer will be considered correct if its absolute or relative error does not exceed $10^{-6}$.

-----Constraints-----
- $1 \le N \le 10^5$
- $0 \le b_i \le 10^9$ for each valid $i$
- $0 \le p_i \le 1$ for each valid $i$
- the sum of $N$ over all test cases does not exceed $4 \cdot 10^5$

-----Example Input-----
2
3
5 6 2
1.0 0.0 0.5
4
2 2 2 2
0.5 0.5 0.5 0.5

-----Example Output-----
6.000000000000000
1.000000000000000

-----Explanation-----
Example case 1: The first painting must be displayed at the exhibition, the second one must be excluded. If the third painting is displayed (with probability $0.5$), the beauty is $5 \oplus 2 = 7$; if it is excluded (with probability $0.5$), the beauty is $5$. The expected beauty is $0.5 \cdot 5 + 0.5 \cdot 7 = 6$.
Example case 2: If there is an...

# cook your dish here
t=int(input())
while t:
 x=0
 n=int(input())
 b=list(map(int,input().strip().split()))
 p=list(map(float,input().strip().split()))
 for i in range(30):
  pb=0.0
  for j in range(n):
   if b[j]&(1<<i):
    pb=pb*(1-p[j])+(1-pb)*p[j]
  x+=(1<<i)*pb
 print(x)
 t-=1


Solve in Python:
Monocarp had a tree which consisted of $n$ vertices and was rooted at vertex $1$. He decided to study BFS (Breadth-first search), so he ran BFS on his tree, starting from the root. BFS can be described by the following pseudocode:a = [] # the order in which vertices were processed

q = Queue()

q.put(1) # place the root at the end of the queue

while not q.empty():

    k = q.pop() # retrieve the first vertex from the queue

    a.append(k) # append k to the end of the sequence in which vertices were visited

    for y in g[k]: # g[k] is the list of all children of vertex k, sorted in ascending order

        q.put(y)

Monocarp was fascinated by BFS so much that, in the end, he lost his tree. Fortunately, he still has a sequence of vertices, in which order vertices were visited by the BFS algorithm (the array a from the pseudocode). Monocarp knows that each vertex was visited exactly once (since they were put and taken from the queue exactly once). Also, he knows that all children of each vertex were viewed in ascending order.

Monocarp knows that there are many trees (in the general case) with the same visiting order $a$, so he doesn't hope to restore his tree. Monocarp is okay with any tree that has minimum height.

The height of a tree is the maximum depth of the tree's vertices, and the depth of a vertex is the number of edges in the path from the root to it. For example, the depth of vertex $1$ is $0$, since it's the root, and the depth of all root's children are $1$.

Help Monocarp to find any tree with given visiting order $a$ and minimum height.

-----Input-----

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

The first line of each test case contains a single integer $n$ ($2 \le n \le 2 \cdot 10^5$) — the number of vertices in the tree.

The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$; $a_i \neq a_j$; $a_1 = 1$) — the order in which the vertices were visited by the BFS algorithm.

It's guaranteed that...

for _ in range(int(input())):
  N = int(input())
  A = [int(x) for x in input().split()]
  last = i = j = 1
  ans = nxt = cur = 0
  while j < N:
    while j < N-1 and A[j+1] > A[j]:
      j += 1
    if cur == 0:
      ans += 1
    nxt += j - i + 1
    j += 1
    i = j
    cur += 1
    if cur == last:
      last = nxt
      nxt = cur = 0

  print(ans)


Solve in Python:
Most football fans love it for the goals and excitement. Well, this Kata doesn't.
You are to handle the referee's little notebook and count the players who were sent off for fouls and misbehavior.

The rules:
Two teams, named "A" and "B" have 11 players each; players on each team are numbered from 1 to 11.
Any player may be sent off the field by being given a red card.
A player can also receive a yellow warning card, which is fine, but if he receives another yellow card, he is sent off immediately (no need for a red card in that case).
If one of the teams has less than 7 players remaining, the game is stopped immediately by the referee, and the team with less than 7 players loses.

A `card` is a string with the team's letter ('A' or 'B'), player's number, and card's color ('Y' or 'R') - all concatenated and capitalized.
e.g the card `'B7Y'` means player #7 from team B received a yellow card.

The task: Given a list of cards (could be empty), return the number of remaining players on each team at the end of the game (as a tuple of 2 integers, team "A" first).
If the game was terminated by the referee for insufficient number of players, you are to stop the game immediately, and ignore any further possible cards.

Note for the random tests: If a player that has already been sent off receives another card - ignore it.

def men_still_standing(cards):
    A = {str(i):0 for i in range(1,12)}
    B = A.copy()
    for card in cards:
        if (11-sum(1 for i in A.values() if i >= 2)) <= 6 or (11-sum(1 for i in B.values() if i >= 2)) <= 6: break
        if card[-1] == 'Y': eval(card[0])[card[1:-1]] += 1
        elif card[-1]=="R": eval(card[0])[card[1:-1]] += 2
    return (max(11-sum(1 for i in A.values() if i >= 2), 6), max(11-sum(1 for i in B.values() if i >= 2),6))


Solve in Python:
Most languages have a `split` function that lets you turn a string like `“hello world”` into an array like`[“hello”, “world”]`. But what if we don't want to lose the separator? Something like `[“hello”, “ world”]`.

#### Task:

Your job is to implement a function, (`split_without_loss` in Ruby/Crystal, and `splitWithoutLoss` in JavaScript/CoffeeScript), that takes two arguments, `str` (`s` in Python), and `split_p`, and returns the string, split by `split_p`, but with the separator intact. There will be one '|' marker in `split_p`. `str` or `s` will never have a '|' in it. All the text before the marker is moved to the first string of the split, while all the text that is after it is moved to the second one. **Empty strings must be removed from the output, and the input should NOT be modified.**

When tests such as `(str = "aaaa", split_p = "|aa")` are entered, do not split the string on overlapping regions. For this example, return `["aa", "aa"]`, not `["aa", "aa", "aa"]`.

#### Examples (see example test cases for more):

```python
split_without_loss("hello world!", " |") #=> ["hello ", "world!"]
split_without_loss("hello world!", "o|rl") #=> ["hello wo", "rld!"]
split_without_loss("hello world!", "h|ello world!") #=> ["h", "ello world!"]
split_without_loss("hello world! hello world!", " |")
                  #=> ["hello ", "world! ", "hello ", "world!"]
split_without_loss("hello world! hello world!", "o|rl")
                  #=> ["hello wo", "rld! hello wo", "rld!"]
split_without_loss("hello  hello  hello", " | ")
                  #=> ["hello ", " hello ", " hello"]
split_without_loss(" hello world", " |")
                  #=> [" ", "hello ", "world"]
split_without_loss("  hello hello hello", " |")
                  #=> [" ", " ", "hello ", "hello ", "hello"]
split_without_loss("  hello hello hello  ", " |")
                  #=> [" ", " ", "hello ", "hello ", "hello ", " "]
split_without_loss("  hello hello hello", "| ")
                  #=> [" ", " hello", " hello", " hello"]
```

Also check out my...

def split_without_loss(s,c):
    return [x for x in s.replace(c.replace('|',''),c).split('|') if x]


Solve in Python:
Most of this problem is by the original author of [the harder kata](https://www.codewars.com/kata/556206664efbe6376700005c), I just made it simpler.

I read a book recently, titled "Things to Make and Do in the Fourth Dimension" by comedian and mathematician Matt Parker ( [Youtube](https://www.youtube.com/user/standupmaths) ), and in the first chapter of the book Matt talks about problems he likes to solve in his head to take his mind off the fact that he is in his dentist's chair, we've all been there!

The problem he talks about relates to polydivisible numbers, and I thought a kata should be written on the subject as it's quite interesting. (Well it's interesting to me, so there!)

### Polydivisib... huh what?

So what are they?

A polydivisible number is divisible in an unusual way. The first digit is cleanly divisible by `1`, the first two digits are cleanly divisible by `2`, the first three by `3`, and so on.

### Examples

Let's take the number `1232` as an example.
```
1     / 1 = 1     // Works
12    / 2 = 6     // Works
123   / 3 = 41    // Works
1232  / 4 = 308   // Works
```
`1232` is a polydivisible number.

However, let's take the number `123220` and see what happens.
```
 1      /1 = 1    // Works
 12     /2 = 6    // Works
 123    /3 = 41   // Works
 1232   /4 = 308  // Works
 12322  /5 = 2464.4         // Doesn't work
 123220 /6 = 220536.333...  // Doesn't work
```
`123220` is not polydivisible.

### Your job: check if a number is polydivisible or not.

Return `true` if it is, and `false` if it isn't.

Note: All inputs will be valid numbers between `0` and `2^53-1 (9,007,199,254,740,991)` (inclusive).
Note: All single digit numbers (including `0`) are trivially polydivisible.
Note: Except for `0`, no numbers will start with `0`.

from itertools import accumulate

def polydivisible(x):
    return all(
        int(''.join(s)) % i == 0
        for i, s in enumerate(accumulate(str(x)), 1)
    )


Solve in Python:
Most problems on CodeChef highlight chef's love for food and cooking but little is known about his love for racing sports. He is an avid Formula 1 fan. He went to watch this year's Indian Grand Prix at New Delhi. He noticed that one segment of the circuit was a long straight road. It was impossible for a car to overtake other cars on this segment. Therefore, a car had to lower down its speed if there was a slower car in front of it. While watching the race, Chef started to wonder how many cars were moving at their maximum speed.
Formally, you're given the maximum speed of N cars in the order they entered the long straight segment of the circuit. Each car prefers to move at its maximum speed. If that's not possible because of the front car being slow, it might have to lower its speed. It still moves at the fastest possible speed while avoiding any collisions. For the purpose of this problem, you can assume that the straight segment is infinitely long.
Count the number of cars which were moving at their maximum speed on the straight segment.

-----Input-----
The first line of the input contains a single integer T denoting the number of test cases to follow. Description of each test case contains 2 lines. The first of these lines contain a single integer N, the number of cars. The second line contains N space separated integers, denoting the maximum speed of the cars in the order they entered the long straight segment.

-----Output-----
For each test case, output a single line containing the number of cars which were moving at their maximum speed on the segment.

-----Example-----
Input:
3
1
10
3
8 3 6
5
4 5 1 2 3

Output:
1
2
2

-----Constraints-----

1 ≤ T ≤ 100

1 ≤ N ≤ 10,000

All speeds are distinct positive integers that fit in a 32 bit signed integer.

Each input file will not be larger than 4 MB (4,000,000,000 bytes) in size.

WARNING! The input files are very large. Use faster I/O.

for _ in range(int(input())):
 n=int(input())
 l=list(map(int,input().split()))
 count=1
 if len(l)==1:
  print(1)
  continue
 for i in range(1,len(l)):
  if l[i]<l[i-1]:
   count+=1
  elif l[i-1]<l[i]:
   l[i]=l[i-1]
 print(count)


Solve in Python:
Mothers arranged a dance party for the children in school. At that party, there are only mothers and their children. All are having great fun on the dance floor when suddenly all the lights went out. It's a dark night and no one can see each other. But you were flying nearby and you can see in the dark and have ability to teleport people anywhere you want.

Legend:
-Uppercase letters stands for mothers, lowercase stand for their children, i.e. "A" mother's children are "aaaa".
-Function input: String contains only letters, uppercase letters are unique.
Task:
Place all people in alphabetical order where Mothers are followed by their children, i.e. "aAbaBb" => "AaaBbb".

def find_children(s):
    return ''.join( sorted(sorted(s), key=str.lower) )


Solve in Python:
Motivation
---------

When compressing sequences of symbols, it is useful to have many equal symbols follow each other, because then they can be encoded with a run length encoding. For example, RLE encoding of `"aaaabbbbbbbbbbbcccccc"` would give something like `4a 11b 6c`.

(Look [here](http://www.codewars.com/kata/run-length-encoding/) for learning more about the run-length-encoding.)

Of course, RLE is interesting only if the string contains many identical consecutive characters. But what bout human readable text? Here comes the Burrows-Wheeler-Transformation.

Transformation
-------------
There even exists a transformation, which brings equal symbols closer together, it is called the **Burrows-Wheeler-Transformation**. The forward transformation works as follows: Let's say we have a sequence with length n, first write every shift of that string into a *n x n* matrix:
```
Input: "bananabar"

b a n a n a b a r
r b a n a n a b a
a r b a n a n a b
b a r b a n a n a
a b a r b a n a n
n a b a r b a n a
a n a b a r b a n
n a n a b a r b a
a n a n a b a r b
```
Then we sort that matrix by its rows. The output of the transformation then is the **last column** and the **row index** in which the original string is in:
```
               .-.
a b a r b a n a n
a n a b a r b a n
a n a n a b a r b
a r b a n a n a b
b a n a n a b a r <- 4
b a r b a n a n a
n a b a r b a n a
n a n a b a r b a
r b a n a n a b a
               '-'

Output: ("nnbbraaaa", 4)
```

```if:java
To handle the two kinds of output data, we will use the preloaded class `BWT`, whose contract is the following:

    public class BWT {

        public String s;
        public int n;

        public BWT(String s, int n)

        @Override public String  toString()
        @Override public boolean equals(Object o)
        @Override public int     hashCode()
    }

```

Of course we want to restore the original input, therefore you get the following hints:

1. The output contains the last matrix column.
2. The first column can be...

def encode(s):
    lst = sorted( s[i or len(s):] + s[:i or len(s)] for i in reversed(range(len(s))) )
    return ''.join(ss[-1] for ss in lst), s and lst.index(s) or 0

def decode(s, n):
    out, lst = [], sorted((c,i) for i,c in enumerate(s))
    for _ in range(len(s)):
        c,n = lst[n]
        out.append(c)
    return ''.join(out)


Solve in Python:
Motu and Patlu are playing with a Magical Ball. Patlu find some interesting pattern in the motion of the ball that ball always bounce back from the ground after travelling a linear distance whose value is some power of $2$. Patlu gave Motu total distance $D$ travelled by the ball and ask him to calculate the minimum number of bounces that the ball makes before coming to rest.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, single integers $D$.
- Note : Power of $2$ must be a non-negative integer.

-----Output:-----
For each testcase, output in a single line answer, the minimum number of bounces the ball makes before coming to rest.

-----Constraints-----
- $1 \leq T \leq 10^5$
- $1$ $\leq$ $M$< $10$^18

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

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

-----EXPLANATION:-----

# def b(n):
#     str=""
#     if n>1:
#         b(n//2)
#     print(n%2,end="")
t=int(input())
for i in range(t):
    n=int(input())
    # b(n)
    binary=bin(n)
    setBits=[ones for ones in binary[2:] if ones=='1']
    print(len(setBits)-1)


Solve in Python:
Motu and Patlu are racing against each other on a circular track of radius $R$. Initially they are at the same point on the track and will run in same direction .The coach ordered them to run $X$ rounds of the circular field. Patlu wants to know how many times they will meet after the race starts and  before any of them finishes $X$ rounds. But he is busy in warm up so he wants you to calculate this. You are given speed of both Motu and Patlu ($A$ and $B$).

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, four integers $X, R, A, B$.

-----Output:-----
For each testcase, output in a single line answer the number of times whey will meet before any of them completes $X$ rounds.

-----Constraints-----
- $1 \leq T \leq 1000$
- $1 \leq R \leq 10^9$
- $1 \leq X \leq 10^9$
- $1 \leq A \leq 10^9$
- $1 \leq B \leq 10^9$
- Speed of both are different

-----Sample Input:-----
2
3 10 2 5
2 20 5 10

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

from math import pi, ceil

T = int(input())
for t in range(T):
 X,R,A,B = map(int,input().split())
 turn = 2 * pi * R
 D = turn * X
 time = D/max(A,B)
 d = time * min(A,B)
 delta = D - d
 print(ceil(delta / turn) - 1)


Solve in Python:
Motu and Tomu are very good friends who are always looking for new games to play against each other and ways to win these games. One day, they decided to play a new type of game with the following rules:
- The game is played on a sequence $A_0, A_1, \dots, A_{N-1}$.
- The players alternate turns; Motu plays first, since he's earlier in lexicographical order.
- Each player has a score. The initial scores of both players are $0$.
- On his turn, the current player has to pick the element of $A$ with the lowest index, add its value to his score and delete that element from the sequence $A$.
- At the end of the game (when $A$ is empty), Tomu wins if he has strictly greater score than Motu. Otherwise, Motu wins the game.
In other words, Motu starts by selecting $A_0$, adding it to his score and then deleting it; then, Tomu selects $A_1$, adds its value to his score and deletes it, and so on.
Motu and Tomu already chose a sequence $A$ for this game. However, since Tomu plays second, he is given a different advantage: before the game, he is allowed to perform at most $K$ swaps in $A$; afterwards, the two friends are going to play the game on this modified sequence.
Now, Tomu wants you to determine if it is possible to perform up to $K$ swaps in such a way that he can win this game.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains two space-separated integers $N$ and $K$ denoting the number of elements in the sequence and the maximum number of swaps Tomu can perform.
- The second line contains $N$ space-separated integers $A_0, A_1, \dots, A_{N-1}$.

-----Output-----
For each test case, print a single line containing the string "YES" if Tomu can win the game or "NO" otherwise (without quotes).

-----Constraints-----
- $1 \le T \le 100$
- $1 \le N \le 10,000$
- $0 \le K \le 10,000$
- $1 \le A_i \le 10,000$ for each valid $i$

-----Subtasks-----
Subtask #1 (20 points): $1...

T = int(input())
for _ in range(T):
 n, k = list(map(int, input().split()))
 seq = list(map(int, input().split()))
 motu, tomu = [], []
 for i in range(n):
  if i%2 == 0:
   motu.append(seq[i])
  else:
   tomu.append((seq[i]))
 motu.sort(reverse=True)
 tomu.sort()
 for i in range(len(motu)):
  if len(tomu)-1<i:
   break
  if k==0:
   break
  if tomu[i]<motu[i]:
   tomu[i], motu[i] = motu[i], tomu[i]
   k-=1
 # for i in range(k):
 #     if motu[i] > tomu[i]:
 #         motu[i], tomu[i] = tomu[i], motu[i]
 if sum(tomu) > sum(motu):
  print("YES")
 else:
  print("NO")


Solve in Python:
Motu wants to learn Cricket from a coach, but firstly coach wants to test his IQ level, so he gave Motu $1$ $Red$ $ball$ and $1$ $Black$ $ball$ , and asked him to buy other $x – 1$ red balls and other $y – 1$ black balls from the market. But he put some conditions on buying balls, that if he has $R$ red and $B$ black balls then he can either buy $B$ red balls or $R$ black balls in one operation. He can perform this operation as many times as he want. But as Motu is not so good in solving problems so he needs your help. So you have to tell him whether his coach’s task possible or not.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, two integers $x , y$.

-----Output:-----
For each testcase, print $YES$, if it is possible to complete coach task, else print $NO$(without quotes) in a separate line.

-----Constraints-----
- $1 \leq T \leq 100000$
- $1 \leq x, y \leq$ 10^18

-----Sample Input:-----
2
1 2
2 3

-----Sample Output:-----
YES
YES

def hcf(x, y):
   while(y):
       x, y = y, x % y
   return x

def __starting_point():
    for _ in range(int(input())):
        x,y=list(map(int,input().split()))
        if hcf(x,y)==1:
            print("YES")
        else:
            print("NO")

__starting_point()


Solve in Python:
Move every letter in the provided string forward 10 letters through the alphabet.

If it goes past 'z', start again at 'a'.

Input will be a string with length > 0.

def move_ten(st):
    alphabet = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
    output = ""
    for letter in st:
        index = alphabet.index(letter)
        letter = alphabet[index+10]
        output += letter
    return output


Solve in Python:
Move the first letter of each word to the end of it, then add "ay" to the end of the word. Leave punctuation marks untouched.

## Examples

```python
pig_it('Pig latin is cool') # igPay atinlay siay oolcay
pig_it('Hello world !')     # elloHay orldway !
```
```C++
pig_it("Pig latin is cool");   // igPay atinlay siay oolcay
pig_it("Hello world !");       // elloHay orldway
```
```Java
PigLatin.pigIt('Pig latin is cool'); // igPay atinlay siay oolcay
PigLatin.pigIt('Hello world !');     // elloHay orldway !
```

def pig_it(text):
    return ' '.join([x[1:]+x[0]+'ay' if x.isalpha() else x for x in text.split()])


Solve in Python:
Mr Leicester's cheese factory is the pride of the East Midlands, but he's feeling a little blue. It's the time of the year when **the taxman is coming round to take a slice of his cheddar** - and the final thing he has to work out is how much money he's spending on his staff. Poor Mr Leicester can barely sleep he's so stressed. Can you help?

- Mr Leicester **employs 4 staff**, who together make **10 wheels of cheese every 6 minutes**.
- Worker pay is calculated on **how many wheels of cheese they produce in a day**.
- Mr Leicester pays his staff according to the UK living wage, which is currently **£8.75p an hour**. There are **100 pence (p) to the UK pound (£)**.

The input for function payCheese will be provided as an array of five integers, one for each amount of cheese wheels produced each day.

When the workforce don't work a nice integer number of minutes - much to the chagrin of the company accountant - Mr Leicester very generously **rounds up to the nearest hour** at the end of the week (*not the end of each day*). Which means if the workers make 574 wheels on each day of the week, they're each paid 29 hours for the week (28.699 hours rounded up) and not 30 (6 hours a day rounded up * 5).

The return value should be a string (with the £ included) of the **total £ of staff wages for that week.**

def pay_cheese(arr):
    return 'L{}'.format(-sum(arr)//100*-35)


Solve in Python:
Mr. Das is a teacher teaching for several years in a school. He is not computer savvy. Due to lockdown, now he has to take classes online. Recently he took an online exam for students of different classes. Now, he will call parents of all the students who scored lower than average marks for the class. He has requested you to give the name $X$, parent's phone number $P$, and marks obtained $M$ to him.

-----Input:-----
- First line contains $T$ no. of test cases
- for every test case, first line contains an integer $N$, no. of students of his class
- Next $N$ lines contain $X$, $P$ , and $M$ separated by space

-----Output:-----
For every test case, find details of the students who scored below average, then print $X, P, M$  separated by space on a new line as per the increasing order of their marks. In case there are multiple students with the same marks, print them as per the order of their occurrence in the input

-----Constraints-----
- $1 \leq T \leq 20$
- X contains characters between a-z and A-Z  with a maximum length of 20
- $1 \leq N \leq 100$
- P is 10 digits
- $0 \leq M \leq 100$

-----Sample Input:-----
2
3
Rahul 1345964789 47
Rupendra 1457856987 58
Priya 1478569820 45
2
Tanuja 4310779415 97
Akash 3689781245 43

-----Sample Output:-----
Priya 1478569820 45
Rahul 1345964789 47
Akash 3689781245 43

-----EXPLANATION:-----
In #1, Priya and Rahul's number was lower than average.
In #2, Akash's number was lower than average

# cook your dish here
t=int(input())
for _ in range(t):
 n=int(input())
 l=[]
 avg=0
 for i in range(n):
  x,p,m=input().split(" ")
  p=int(p)
  m=int(m)
  avg+=m
  l.append([x,p,m])
 avg=avg//n
 ret=[]
 for i in range(n):
  if l[i][2]<=avg:
   ret.append([l[i][0],l[i][1],l[i][2]])
 ret.sort()
 for i in range(len(ret)):
  print(ret[i][0],ret[i][1],ret[i][2])


Solve in Python:
Mr. E Ven only likes even length words.
Please create a translator so that he doesn't have to hear those pesky odd length words.
For some reason he also hates punctuation, he likes his sentences to flow.

Your translator should take in a string and output it with all odd length words having an extra letter (the last letter in the word). It should also remove all punctuation (.,?!) as well as any underscores (_).

"How did we end up here? We go?"
translated becomes->
"Howw didd we endd up here We go"

def evenator(s):
    words = [ dupiword(evenatorword(s)) for s in s.split(" ") ]
    return " ".join(words).strip()

def dupiword(s):
    return s+s[len(s)-1] if len(s)%2 else s

def evenatorword(w):
    return "".join([ x if x.isalnum() else '' for x in w]).replace("  ", " ")


Solve in Python:
Mr. Khalkhoul, an amazing teacher, likes to answer questions sent by his students via e-mail, but he often doesn't have the time to answer all of them. In this kata you will help him by making a program that finds
some of the answers.

You are given a `question` which is a string containing the question and some `information` which is a list of strings representing potential answers.

Your task is to find among `information` the UNIQUE string that has the highest number of words in common with `question`. We shall consider words to be separated by a single space.

You can assume that:

* all strings given contain at least one word and have no leading or trailing spaces,
* words are composed with alphanumeric characters only

You must also consider the case in which you get no matching words (again, ignoring the case): in such a case return `None/nil/null`.

Mr. Khalkhoul is countin' on you :)

def answer(question, informations):
    question_words = set(question.lower().split())
    compare = lambda information: len(question_words & set(information.lower().split()))
    return max([""] + informations, key=compare) or None


Solve in Python:
Mr. Krabs loves money. He enters a bank and sees that there are n rooms arranged in a row. The only rooms with doors are the two rooms on either corner. Initially, all the rooms are locked (including the corner ones). To enter a room, it must be unlocked with a key.
Mr. Krabs is able to steal k keys from the sleeping night guard. Each key can be used to unlock only one room. To reach one of the inner rooms, he has to unlock an adjacent room first.
Eg: If there are 5 rooms labelled: 1 2 3 4 5
Only Rooms 1 and 5 can be accessed initially. To unlock room 2, either room 1 or room 3 must be unlocked. Similarly to unlock Room 4, he must unlock room 5 or room 3 first.
Each room has some money in it. The money present in room i is given by A[i]. Using the k keys, calculate what is the maximum possible amount of money obtainable.

-----Input:-----
- First line will contain n,  number of rooms.
- Second line will contain space separated integers, denoting A[i], money present in each room.
- Third line will contain an integer, k, the number of keys available.

-----Output:-----
Maximum money obtained.

-----Constraints-----
- 1 <= Number of Rooms <= 10^5
- 1 <= A[i] <= 10^4
- 1 <= k <= Number of Rooms

-----Subtasks-----
- 40 points : 1 <= Number of Rooms <= 100
- 60 points : Number of Rooms > 100

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

-----Sample Output:-----
12

-----Explanation:-----
For the first step, Mr. Krabs can only unlock the room at the left corner or the right corner. If he unlocks the room in the right corner, he obtains 1 dollar. He can then go on to unlock the second last room and gain 6 dollars, for a total of 7 dollars. Finally he can unlock the third last room and get 5 dollars, for a total of 12 dollars.
This is the maximum amount of money he can get with only 3 keys.

# cook your dish here
r = int(input())
#for i in range(nt):
arr = [int(i) for i in input().split()]
k = int(input())
maxi = 0
for x in range(k):
    k1 = x
    k2 = k - x
    s1 = sum(arr[:k1]) + (sum(arr[-k2:]) if k2 > 0 else 0)
    #s2 = sum(arr[:k2]) + (sum(arr[-k1:]) if k1 > 0 else 0)
    #summation = max(s1, s2)
    maxi = max(s1, maxi)

print(maxi)


Solve in Python:
Mr. Pr and Ms. Ad are at $a$ and $b$ respectively on an infinite number line. Mr. Pr wants to meet Ms. Ad.
Mr. Pr can choose to move  $c$ or $d$ units in 1 second. If Mr. Pr moves $c$ units then Ms. Ad will move $d$ units and vice versa. (Both of them always moved in positive x-direction)
You have to determine if Mr. Pr can meet with Ms. Ad after some integral amount of time, given that Mr. Pr chooses optimally. Note that meeting after a fractional amount of time does not count.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains four space separated integers, $a$, $b$, $c$, and $d$.

-----Output:-----
- For each test case, output a single line containing "YES" if Mr. Pr meets with Ms. Ad, otherwise "NO".

-----Constraints-----
- $1 \leq T \leq 10^5$
- $1 \leq a,b,c,d \leq 10^9$

-----Sample Input:-----
2
3 4 1 2
10 20 3 7

-----Sample Output:-----
YES
NO

-----Explanation:-----
In the first test case, Mr. Pr will move 2 units in the first second and Ms. Ad moves 1 unit simultaneously and they meet.
In the second test case, it is impossible to meet (fractional time is not allowed).

# cook your dish here
import math
test=int(input())
while(test>0):
    a,b,c,d=input().split()
    a=int(a)
    b=int(b)
    c=int(c)
    d=int(d)

    if d==c:
        if a==b:
            print("YES")
        else:
            print("NO")
    else:
        m=abs((a-b)/(c-d))
        if int(m)==m:
            if min(a,b)+(max(c,d)*m-1)==max(a,b)+(min(c,d)*m-1):
                print("YES")
            else:
                print("NO")

        else:
            m=math.ceil(m)
            if min(a,b)+(max(c,d)*m)==max(a,b)+(min(c,d)*m):
                print("YES")
            else:
                print("NO")
    test=test-1


Solve in Python:
Mr. Scrooge has a sum of money 'P' that he wants to invest. Before he does, he wants to know how many years 'Y' this sum 'P' has to be kept in the bank in order for it to amount to a desired sum of money 'D'.

The sum is kept for 'Y' years in the bank where interest 'I' is paid yearly. After paying taxes 'T' for the year the new sum is re-invested.

Note to Tax: not the invested principal is taxed, but only the year's accrued interest

Example:

      Let P be the Principal = 1000.00
      Let I be the Interest Rate = 0.05
      Let T be the Tax Rate = 0.18
      Let D be the Desired Sum = 1100.00

    After 1st Year -->
      P = 1041.00
    After 2nd Year -->
      P = 1083.86
    After 3rd Year -->
      P = 1128.30

Thus Mr. Scrooge has to wait for 3 years for the initial principal to amount to the desired sum.

Your task is to complete the method provided and return the number of years 'Y' as a whole in order for Mr. Scrooge to get the desired sum.

Assumption: Assume that Desired Principal 'D' is always greater than the initial principal. However it is best to take into consideration that if Desired Principal 'D' is equal to Principal 'P' this should return 0 Years.

from math import ceil, log

def calculate_years(p, i, t, d):
    x = float(d) / p
    base = 1 + (i * (1 - t))
    return ceil(log(x, base))

    #return ceil(log(float(d) / p, 1 + (i * (1 - t))))


Solve in Python:
Mr. Square is going on a holiday. He wants to bring 2 of his favorite squares with him, so he put them in his rectangle suitcase.

Write a function that, given the size of the squares and the suitcase, return whether the squares can fit inside the suitcase.
```Python
fit_in(a,b,m,n)
a,b are the sizes of the 2 squares
m,n are the sizes of the suitcase
```

# Example
```Python
fit_in(1,2,3,2) should return True
fit_in(1,2,2,1) should return False
fit_in(3,2,3,2) should return False
fit_in(1,2,1,2) should return False
```

def fit_in(a,b,m,n):
    # You may code here
    if (a+b)<=m :
        if  (max(a,b)<=n):
            return True
        else:
            return False
    elif max(a,b)<=m:
        if (a+b)<=n:
            return True
        else:
            return False
    else:
        return False


Solve in Python:
Mr. Wilson was planning to record his new Progressive Rock music album called "Digits. Cannot. Separate". Xenny and PowerShell, popular pseudo-number-theoreticists from the Land of Lazarus were called by him to devise a strategy to ensure the success of this new album. Xenny and Powershell took their Piano Lessons and arrived at the Studio in different Trains.
Mr. Wilson, creative as usual, had created one single, long music track S. The track consisted of N musical notes. The beauty of each musical note was represented by a decimal digit from 0 to 9.
Mr. Wilson told them that he wanted to create multiple musical tracks out of this long song. Since Xenny and Powershell were more into the number theory part of music, they didn’t know much about their real workings. Mr. Wilson told them that a separator could be placed between 2 digits. After placing separators, the digits between 2 separators would be the constituents of this new track and the number formed by joining them together would represent the Quality Value of that track. He also wanted them to make sure that no number formed had greater than M digits.
Mr. Wilson had Y separators with him. He wanted Xenny and PowerShell to use at least X of those separators, otherwise he would have to ask them to Drive Home.
Xenny and PowerShell knew straight away that they had to put place separators in such a way that the Greatest Common Divisor (GCD) of all the Quality Values would eventually determine the success of this new album. Hence, they had to find a strategy to maximize the GCD.
If you find the maximum GCD of all Quality Values that can be obtained after placing the separators, Xenny and PowerShell shall present you with a Porcupine Tree.
Note:
-
You can read about GCD here.

-
Greatest Common Divisor of 0 and 0 is defined as 0.

-----Input-----
The first line of input consists of a single integer T - the number of testcases.
Each test case is of the following format:
First line contains a single integer N - the length of the long musical track.
Second...

t = int(input())

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

dp = {}

def solve (p, k, g, s, m, x, y, n):
 if ((p, k, g) in dp): return dp[(p, k, g)];

 ans = 0

 if (p == n):
  if k >= x and k <= y:
   ans = g
  else:
   ans = 0
 else:
  for i in range (p, n):

   if (i - p + 1 > m): break

   temp = solve (i + 1, k + 1, gcd(g, int(s[p:i + 1])), s, m, x, y, n)
   if (temp > ans):
    ans = temp

 dp[(p, k, g)] = ans
 return ans

while t != 0:
 dp = {}
 t -= 1
 n = int(input())
 s = input()
 m, x, y = list(map (int, input().split()))
 x += 1
 y += 1

 print(solve (0, 0, 0, s, m, x, y, n))


Solve in Python:
Mr. Wire Less is not that good at implementing circuit in a breadboard. In his Digital Logic Design course, he has to implement several boolean functions using the breadboard. In a breadboard, inputs are given through the switches and outputs are taken through the LEDs. Each input switch can be either in ground state or in high state. So, if he wishes to implement a boolean function, f(x1, x2, .., xn) that takes n boolean values as input and returns m boolean values as output, he will use n switches and m LEDs.
Mr. Wire Less can quickly assemble the necessary ICs and wires, but the key problem is testing. While testing he has to check with all possible input combination, to make sure whether the output of LED corresponds to the expected output or not. This is taking too long for him, as most of the switches are jammed and difficult to toggle.
Mr. Wire Less is asking for help to minimize his time of testing. So, your task is to minimize the total number of switch-toggle throughout the testing.
For example, if Mr. Wire Less has to test a function f(x0, x1) of two variables, he may choose this switching-sequence for testing 00, 11, 10, 01. In this case, the total number of switch-toggle will be 2+1+2 = 5. But if he tests in this sequence 00, 10, 11, 01 total number of toggle will be 1+1+1 = 3.
Given n, you have to output the minimum number of toggle needed for complete testing. Though it seems impractical, he wants you to solve the problem for a very large value of n. But, then the toggle value can be quite big. So, he is completely okay with the toggle value modulo 8589934592 (233).

-----Input-----
The first line of the input contains a positive integer T(T ≤ 105), denoting the number of test-case. Each of the following T lines contains a single non-negative integer n(n ≤ 1020).

-----Output-----
For every test-case, output a single containing test-case number and the minimum number of switch-toggle modulo 8589934592 (233).

-----Sample-----
Input
2
1
2

Output
Case 1: 1
Case 2: 3


Solve in Python:
Mr. X has come up with a new string compression algorithm. Consider a string of length N which contains up to K distinct characters. The compression algorithm works as follows: Replace each maximal contiguous substring containing only one distinct character (repeated an arbitrary number of times) and replace it by 2 values: the character and the length of the substring.
For example, the string "aabbaaa" will be compressed to "a, 2, b, 2, a, 3". Thus the length of the compressed string is 6.

Since Mr. X is living in advanced times, the length of any integer is considered to be 1. For example, if a string is compressed to "a, 111, b, 13", then its length after compression is considered to be 4.

To test his algorithm, he needs to know the expected length of the compressed string for given N and K if the input string is randomly uniformly chosen from all possibilities. He wants to run this experiment multiple times for different N, K and needs your help.

-----Input-----
The first line of the input contains an integer T denoting the number of queries. The description of T test cases follows.
The first and only line of each test case contains two integers N and K denoting the number of letters in the input string and the maximum number of distinct characters that can be present in the string.

-----Output-----

For each test case, output a single line containing the expected length of the compressed string.
Your answer will be considered correct if the absolute error is less than 10-2

-----Constraints-----
- 1 ≤ T ≤ 105
- 1 ≤ N, K ≤ 109

-----Example-----
Input:
2
3 1
3 2
Output:
2.0
4.0

-----Explanation-----Example case 1:

There is only one string: aaa with compressed string = a, 3. Therefore length = 2
Example case 2

Input strings:

"aaa": "a, 3". Length = 2

"aab": "a, 2, b, 1". Length = 4

"aba": "a, 1, b, 1, a, 1". Length = 6

"abb": "a, 1, b, 2". Length = 4

"baa": "b, 1, a, 2". Length = 4

"bab": "b, 1, a, 1, b, 1". Length = 6

"bba": "b, 2, a, 1". Length = 4

"bbb": "b, 3". Length = 2

Expected...

for _ in range(int(input())):
    n,k = map(int,input().split())
    print(2*(n-1)*(k-1)/k + 2)