Solve in Python:
Bob has n heap(s) of gravel (initially there are exactly c piece(s) in each). He wants to do m operation(s) with that heaps, each maybe:

- adding pieces of gravel onto the heaps from u to v, exactly k pieces for each,
- or querying "how many pieces of gravel are there in the heap p now?".

-----Request-----
Help Bob do operations of the second type.

-----Input-----

- The first line contains the integers n,m,c, respectively.
- m following lines, each forms:

- S u v k to describe an operation of the first type.
- Q p to describe an operation of the second type.
(Each integer on a same line, or between the characters S, Q and the integers is separated by at least one space character)

-----Output-----
For each operation of the second type, output (on a single line) an integer answering to the respective query (follows the respective Input order).

-----Example-----Input:
7 5 0
Q 7
S 1 7 1
Q 3
S 1 3 1
Q 3
Output:
0
1
2

-----Limitations-----
- 0<n≤106
- 0<m≤250 000
- 0<u≤v≤n
- 0≤c,k≤109
- 0<p≤n

def bitadd(tree,index,value):
 index+=1
 while index<len(tree):
  tree[index]+=value
  index+=index&(-index)

def bitsum(tree,index):
 index+=1
 result=0
 while index:
  result+=tree[index]
  index-=index&(-index)
 return result

n,m,c=list(map(int,input().split()))
tree=[0 for _ in range(n+1)]
# for i in range(n):
#     bitadd(tree,i,c)
for _ in range(m):
 q=input().split()
 if q[0]=="Q":
  print(bitsum(tree,int(q[1])-1)+c)
 else:
  u=int(q[1])
  v=int(q[2])
  k=int(q[3])
  bitadd(tree,u-1,k)
  bitadd(tree,v,-k)


Solve in Python:
Bob is a lazy man.

He needs you to create a method that can determine how many ```letters``` and ```digits``` are in a given string.

Example:

"hel2!lo" --> 6

"wicked .. !" --> 6

"!?..A" --> 1

import re
def count_letters_and_digits(s):
    try:
        list = re.findall('[A-Za-z0-9]',s)
        return (len(list))
    except:
        return 0


Solve in Python:
Bob is a theoretical coder - he doesn't write code, but comes up with theories, formulas and algorithm ideas. You are his secretary, and he has tasked you with writing the code for his newest project - a method for making the short form of a word. Write a function ```shortForm```(C# ```ShortForm```, Python ```short_form```) that takes a string and returns it converted into short form using the rule: Remove all vowels, except for those that are the first or last letter. Do not count 'y' as a vowel, and ignore case. Also note, the string given will not have any spaces; only one word, and only Roman letters.

Example:
```
shortForm("assault");
short_form("assault")
ShortForm("assault");
// should return "asslt"
```

Also, FYI: I got all the words with no vowels from
https://en.wikipedia.org/wiki/English_words_without_vowels

from re import compile
from functools import partial

short_form = partial(compile(r"(?i)(?<!^)[aeiou](?!$)").sub, "")


Solve in Python:
Bob is playing with $6$-sided dice. A net of such standard cube is shown below.

[Image]

He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice.

For example, the number of visible pips on the tower below is $29$ — the number visible on the top is $1$, from the south $5$ and $3$, from the west $4$ and $2$, from the north $2$ and $4$ and from the east $3$ and $5$.

[Image]

The one at the bottom and the two sixes by which the dice are touching are not visible, so they are not counted towards total.

Bob also has $t$ favourite integers $x_i$, and for every such integer his goal is to build such a tower that the number of visible pips is exactly $x_i$. For each of Bob's favourite integers determine whether it is possible to build a tower that has exactly that many visible pips.

-----Input-----

The first line contains a single integer $t$ ($1 \leq t \leq 1000$) — the number of favourite integers of Bob.

The second line contains $t$ space-separated integers $x_i$ ($1 \leq x_i \leq 10^{18}$) — Bob's favourite integers.

-----Output-----

For each of Bob's favourite integers, output "YES" if it is possible to build the tower, or "NO" otherwise (quotes for clarity).

-----Example-----
Input
4
29 34 19 38

Output
YES
YES
YES
NO

-----Note-----

The first example is mentioned in the problem statement.

In the second example, one can build the tower by flipping the top dice from the previous tower.

In the third example, one can use a single die that has $5$ on top.

The fourth example is impossible.

n=int(input())
arr=list(map(int,input().split()))
for i in arr:
	if i<=14:
		print("NO")
	else:
		flg=False
		for j in range(1,7):
			if (i-j)%14==0:
				flg=True
		if flg:
			print("YES")
		else:
			print("NO")


Solve in Python:
Bob is preparing to pass IQ test. The most frequent task in this test is `to find out which one of the given numbers differs from the others`. Bob observed that one number usually differs from the others in **evenness**. Help Bob — to check his answers, he needs a program that among the given numbers finds one that is different in evenness, and return a position of this number.

`!` Keep in mind that your task is to help Bob solve a `real IQ test`, which means indexes of the elements start from `1 (not 0)`

##Examples :

```python
iq_test("2 4 7 8 10") => 3 // Third number is odd, while the rest of the numbers are even

iq_test("1 2 1 1") => 2 // Second number is even, while the rest of the numbers are odd
```

def iq_test(numbers):
  a=list(map(lambda x : int(x)%2,numbers.split(' ')))
  return 1+(a.index(0) if (a.count(0)) == 1 else a.index(1))


Solve in Python:
Bob just learned about bitwise operators. Since Alice is an expert, she decided to play a game, she will give a number $x$ to Bob and will ask some questions:
There will be 4 different kinds of queries:-
-
Alice gives an integer $i$ and Bob has to report the status of the $i^{th}$ bit in $x$, the answer is $"ON"$ if it is on else $"OFF"$.
-
Alice gives an integer $i$ and Bob has to turn on the $i^{th}$ bit in $x$.
-
Alice gives an integer $i$ and Bob has to turn off the $i^{th}$ bit in $x$.
-
Alice gives two integers $p$ and $q$ and in the binary representation of $x$ Bob has to swap the $p^{th}$ and the $q^{th}$ bits.
The value of $x$ changes after any update operation.
positions $i$, $p$, and $q$ are always counted from the right or from the least significant bit.
If anyone of $i$, $p$, or $q$ is greater than the number of bits in the binary representation of $x$, consider $0$ at that position.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- the first line of each test case contains two space-separated integers $x, Q$.
- $2Q$ lines follow.
- first line is an integer, the query type.
- for each query of type 1 to 3, there will be the integer $i$
- for the query of type 4, there will be two space-separated integers, the integers $p, q$

-----Output:-----
For the queries of the first kind, print $"ON"$ or $"OFF"$.

-----Constraints-----
- $1 \leq T \leq 10^3$
- $1 \leq x \leq 10^9$
- $1 \leq Q \leq 10^3$
- $1 \leq i,p,q \leq 30$

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

-----Sample Output:-----
ON

-----EXPLANATION:-----
the binary representation of 2 is 10
for query 1, we just have to update x to 11 (or 3 in decimal).
for the next query, x is now 3 or 11 in binary so the answer is ON.

def make_31(string):
    if len(string) < 31:
        string = (31- len(string)) * '0' + string

    return string

for _ in range(int(input())):
    x, Q = list(map(int, input().split()))
    b = make_31(bin(x)[2:])
    b = list(b.strip())
    for qqq in range(Q):
        query = int(input())
        if query == 1:
            p = int(input())
            print('ON' if b[31-p] == '1' else 'OFF')
        elif query == 2:
            p = int(input())
            b[31-p] = '1'
        elif query == 3:
            p = int(input())
            b[31 - p] = '0'
        else:
            p, q = list(map(int, input().split()))
            temp = b[31 - q]
            b[31 - q] = b[31 - p]
            b[31 - p] = temp


Solve in Python:
Bob needs a fast way to calculate the volume of a cuboid with three values: `length`, `width` and the `height` of the cuboid. Write a function to help Bob with this calculation.

```if:shell
In bash the script is ran with the following 3 arguments:
`length` `width` `height`
```

def getVolumeOfCubiod(leng, wid, hei):
    return leng*wid*hei


Solve in Python:
Bob recently read about bitwise operations used in computers: AND, OR and XOR. He have studied their properties and invented a new game.

Initially, Bob chooses integer m, bit depth of the game, which means that all numbers in the game will consist of m bits. Then he asks Peter to choose some m-bit number. After that, Bob computes the values of n variables. Each variable is assigned either a constant m-bit number or result of bitwise operation. Operands of the operation may be either variables defined before, or the number, chosen by Peter. After that, Peter's score equals to the sum of all variable values.

Bob wants to know, what number Peter needs to choose to get the minimum possible score, and what number he needs to choose to get the maximum possible score. In both cases, if there are several ways to get the same score, find the minimum number, which he can choose.

-----Input-----

The first line contains two integers n and m, the number of variables and bit depth, respectively (1 ≤ n ≤ 5000; 1 ≤ m ≤ 1000).

The following n lines contain descriptions of the variables. Each line describes exactly one variable. Description has the following format: name of a new variable, space, sign ":=", space, followed by one of:  Binary number of exactly m bits.  The first operand, space, bitwise operation ("AND", "OR" or "XOR"), space, the second operand. Each operand is either the name of variable defined before or symbol '?', indicating the number chosen by Peter.

Variable names are strings consisting of lowercase Latin letters with length at most 10. All variable names are different.

-----Output-----

In the first line output the minimum number that should be chosen by Peter, to make the sum of all variable values minimum possible, in the second line output the minimum number that should be chosen by Peter, to make the sum of all variable values maximum possible. Both numbers should be printed as m-bit binary numbers.

-----Examples-----
Input
3 3
a := 101
b := 011
c := ? XOR b

Output
011
100

Input
5...

def sumBin(a, b, varMap):
  lhs = varMap[a]
  rhs = varMap[b]
  return bin(int(lhs, 2) + int(rhs, 2))[2:]

def andBin(a, b, varMap):
  lhs = varMap[a]
  rhs = varMap[b]
  return bin(int(lhs, 2) & int(rhs, 2))[2:]

def orBin(a, b, varMap):
  lhs = varMap[a]
  rhs = varMap[b]
  return bin(int(lhs, 2) | int(rhs, 2))[2:]

def xorBin(a, b, varMap):
  lhs = varMap[a]
  rhs = varMap[b]
  return bin(int(lhs, 2) ^ int(rhs, 2))[2:]

mapOper = {'AND': andBin, 'OR': orBin, 'XOR' : xorBin}

n, m = list(map(int, input().split()))
minMap = {"?": "0", "": "0"}
maxMap = {"?": "1"*m, "": "0"}

minSum = "0"
maxSum = "0"
for _ in range(n):
  name, _, expr = input().split(' ', 2)

  if len(expr.split(' ')) == 1:
    minMap[name] = expr
    maxMap[name] = expr
  else:
    lhs, oper, rhs = expr.split()
    minMap[name] = mapOper[oper](lhs, rhs, minMap).zfill(m)
    maxMap[name] = mapOper[oper](lhs, rhs, maxMap).zfill(m)

  minSum = sumBin("", name, minMap)
  maxSum = sumBin("", name, maxMap)

def countOnes(i, varMap):
  ones = 0
  for name, num in list(varMap.items()):
    if name != "?" and name != "":
      ones += num[i] == "1"
  return ones

minRes = ""
maxRes = ""

for i in range(m):
  zeroOnes = countOnes(i, minMap)
  oneOnes = countOnes(i, maxMap)

  if zeroOnes > oneOnes:
    maxRes += "0"
    minRes += "1"
  elif zeroOnes < oneOnes:
    maxRes += "1"
    minRes += "0"
  else:
    maxRes += "0"
    minRes += "0"

print (minRes)
print (maxRes)


Solve in Python:
Bob watches TV every day. He always sets the volume of his TV to $b$. However, today he is angry to find out someone has changed the volume to $a$. Of course, Bob has a remote control that can change the volume.

There are six buttons ($-5, -2, -1, +1, +2, +5$) on the control, which in one press can either increase or decrease the current volume by $1$, $2$, or $5$. The volume can be arbitrarily large, but can never be negative. In other words, Bob cannot press the button if it causes the volume to be lower than $0$.

As Bob is so angry, he wants to change the volume to $b$ using as few button presses as possible. However, he forgets how to do such simple calculations, so he asks you for help. Write a program that given $a$ and $b$, finds the minimum number of presses to change the TV volume from $a$ to $b$.

-----Input-----

Each test contains multiple test cases. The first line contains the number of test cases $T$ ($1 \le T \le 1\,000$). Then the descriptions of the test cases follow.

Each test case consists of one line containing two integers $a$ and $b$ ($0 \le a, b \le 10^{9}$) — the current volume and Bob's desired volume, respectively.

-----Output-----

For each test case, output a single integer — the minimum number of presses to change the TV volume from $a$ to $b$. If Bob does not need to change the volume (i.e. $a=b$), then print $0$.

-----Example-----
Input
3
4 0
5 14
3 9

Output
2
3
2

-----Note-----

In the first example, Bob can press the $-2$ button twice to reach $0$. Note that Bob can not press $-5$ when the volume is $4$ since it will make the volume negative.

In the second example, one of the optimal ways for Bob is to press the $+5$ twice, then press $-1$ once.

In the last example, Bob can press the $+5$ once, then press $+1$.

import io, sys, atexit, os
import math as ma
from decimal import Decimal as dec
from itertools import permutations
from itertools import combinations

def li():
    return list(map(int, sys.stdin.readline().split()))

def num():
    return map(int, sys.stdin.readline().split())

def nu():
    return int(input())

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

def lcm(x, y):
    gg = find_gcd(x, y)
    return (x * y // gg)

mm = 1000000007

def solve():
    t = nu()
    for tt in range(t):
        a,b=num()
        if(a<=b):
            dd=b-a
            pq=dd//5
            yp=dd%5
            yo=yp//2
            yu=yp%2
            print(pq+yu+yo)
        else:
            a,b=b,a
            dd = b - a
            pq = dd // 5
            yp = dd % 5
            yo = yp // 2
            yu = yp % 2
            print(pq + yu + yo)

def __starting_point():
    solve()
__starting_point()


Solve in Python:
Bobby has decided to hunt some Parrots. There are n horizontal branch of trees aligned parallel to each other. Branches are numbered 1 to n from top to bottom. On each branch there are some parrots sitting next to each other. Supposed there are a[i]$a[i]$ parrots sitting on the i−th$ i-th$ branch.
Sometimes Bobby shots one of the parrot and the parrot dies (suppose that this parrots sat at the i−th$i-th$ branch). Consequently all the parrots on the i−th$i-th$ branch to the left of the dead parrot get scared and jump up on the branch number i − 1$i - 1$, if there exists no upper branch they fly away. Also all the parrots to the right of the dead parrot jump down on branch number i + 1$i + 1$, if there exists no such branch they fly away.
Bobby has shot m parrots. You're given the initial number of parrots on each branch, tell him how many parrots are sitting on each branch after the shots.

-----Input:-----
The first line of the input contains an integer N$N$. The next line contains a list of space-separated integers a1, a2, …, an.
The third line contains an integer M$M$. Each of the next M$M$ lines contains two integers x[i]$x[i]$ and y[i]$y[i]$. The integers mean that for the i-th time Bobby shoot the y[i]-th (from left) parrot on the x[i]-th branch. It's guaranteed there will be at least y[i] parrot on the x[i]-th branch at that moment.

-----Output:-----
On the i−th$i-th$ line of the output print the number of parrots on the i−th$i-th$ branch.

-----Constraints-----
- 1≤N≤100$1 \leq N \leq 100$
- 0≤a[i]≤100$0 \leq a[i] \leq 100$
- 0≤M≤100$0 \leq M \leq 100$
- 1≤x[i]≤n$1 \leq x[i] \leq n$, 1≤y[i]$1 \leq y[i] $

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

10 10 10 10 10

5

2 5

3 13

2 12

1 13

4 6
3

2 4 1

1

2 2

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

12

5

0

16
3

0

3

N = int(input())
branch = list(map(int,input().split()))
t = int(input())
for i in range(t):
    x, y = list(map(int,input().split()))
    if(x==1):
        try:
            branch[x] += branch[x-1] - y
        except:
            ...
    else:
        try:
            branch[x-2] += y - 1
        except:
            ...
        try:
            branch[x] += branch[x-1] - y
        except:
            ...
    branch[x-1] = 0
for j in branch:
    print(j)


Solve in Python:
Bohan loves milk tea so much and he drinks one cup of milk tea every day. The local shop sells milk tea in two sizes: a Medium cup for $3 and a Large cup for $4. For every cup of milk tea purchased Bohan receives a promotional stamp. Bohan may redeem 6 stamps for a free drink of milk tea regardless of the size. No stamp will be given for a free drink.

Determine the amount of money Bohan have spent on milk tea, given a sequence of milk tea sizes he got in the past a few days. Assume Bohan had no stamps in the beginning and he always redeemed the stamps for the next drink once he had collected 6 stamps.

-----Input-----
The input begins with the number of test cases T.
Each test case has a single line of letters. The i-th letter is either 'M' or 'L' denoting a Medium cup or a Large cup of milk tea Bohan got on the i-th day.

-----Output-----
For each case, output the amount of money in dollars Bohan have spent on milk tea.

-----Constraints-----
- T ≤ 100
- 1 ≤  length of each sequence ≤ 100

-----Example-----
Input:
3
MLM
MMLLMMLL
MMMMMMML

Output:
10
24
22

-----Explanation-----
Example 1: Bohan didn't redeem any stamps.
Example 2: Bohan redeemed 6 stamps for the Large cup of milk tea on the 7th day.
Example 3: Bohan redeemed 6 stamps for the Medium cup of milk tea on the 7th day.

t = int(input())
for tc in range(t):
 seq = input()
 dollar = 0
 stamp = 0
 for ct in seq:
  if stamp >= 6:
   stamp -= 6
   continue
  elif ct == 'M':
   dollar += 3
  elif ct == 'L':
   dollar += 4
  stamp += 1
 print(dollar)


Solve in Python:
Born a misinterpretation of [this kata](https://www.codewars.com/kata/simple-fun-number-334-two-beggars-and-gold/), your task here is pretty simple: given an array of values and an amount of beggars, you are supposed to return an array with the sum of what each beggar brings home, assuming they all take regular turns, from the first to the last.

For example: `[1,2,3,4,5]` for `2` beggars will return a result of `[9,6]`, as the first one takes `[1,3,5]`, the second collects `[2,4]`.

The same array with `3` beggars would have in turn have produced a better out come for the second beggar: `[5,7,3]`, as they will respectively take `[1,4]`, `[2,5]` and `[3]`.

Also note that not all beggars have to take the same amount of "offers", meaning that the length of the array is not necessarily a multiple of `n`; length can be even shorter, in which case the last beggars will of course take nothing (`0`).

***Note:*** in case you don't get why this kata is about *English* beggars, then you are not familiar on how religiously queues are taken in the kingdom ;)

def beggars(values: list, n: int):
    if n < 1: return []

    beggars = [0] * n
    for i, v in enumerate(values):
        beggars[i % n] += v

    return beggars


Solve in Python:
Brief
=====
In this easy kata your function has to take a **string** as input and **return a string** with everything removed (*whitespaces* included) but the **digits**. As you may have guessed **empty strings** are to be returned as they are & if the input string contains no digits then the output will be an **empty string**.By the way , you have to watch out for **non-string** inputs too.Return **'Invalid input !'** for them.

Hint
====
If you're writing more than 1 line of code, then think again! ;)
Good luck!

import re
def digit_all (x):
    if not isinstance(x, str): return 'Invalid input !'
    regex = re.compile(r'[^0-9]')
    return re.sub(regex, '', x)


Solve in Python:
Brief
=====
Sometimes we need information about the list/arrays we're dealing with. You'll have to write such a function in this kata. Your function must provide the following informations:

* Length of the array
* Number of integer items in the array
* Number of float items in the array
* Number of string character items in the array
* Number of whitespace items in the array

The informations will be supplied in arrays that are items of another array. Like below:

`Output array = [[array length],[no of integer items],[no of float items],[no of string chars items],[no of whitespace items]]`

Added Difficulty
----------------
If any item count in the array is zero, you'll have to replace it with a **None/nil/null** value (according to the language). And of course, if the array is empty then return **'Nothing in the array!**. For the sake of simplicity, let's just suppose that there are no nested structures.
Output
======
If you're head is spinning (just kidding!) then these examples will help you out-
```

array_info([1,2,3.33,4,5.01,'bass','kick',' '])--------->[[8],[3],[2],[2],[1]]
array_info([0.001,2,' '])------------------------------>[[3],[1],[1],[None],[1]]
array_info([])----------------------------------------->'Nothing in the array!'
array_info([' '])-------------------------------------->[[1],[None],[None],[None],[1]]

  ```
Remarks
-------
The input will always be arrays/lists. So no need to check the inputs.
Hint
====
See the tags!!!
Now let's get going !

def array_info(x):
    if not x: return 'Nothing in the array!'
    L = [0]*4
    for e in x:
        if   type(e) == int:   L[0] += 1
        elif type(e) == float: L[1] += 1
        elif e == ' ':         L[3] += 1
        else:                  L[2] += 1
    return [[len(x)]] + [[e or None] for e in L]


Solve in Python:
Build Tower Advanced
---

Build Tower by the following given arguments:
__number of floors__ (integer and always greater than 0)
__block size__ (width, height) (integer pair and always greater than (0, 0))

Tower block unit is represented as `*`

* Python: return a `list`;
* JavaScript: returns an `Array`;

Have fun!
***

for example, a tower of 3 floors with block size = (2, 3) looks like below
```
[
  '    **    ',
  '    **    ',
  '    **    ',
  '  ******  ',
  '  ******  ',
  '  ******  ',
  '**********',
  '**********',
  '**********'
]
```
and a tower of 6 floors with block size = (2, 1) looks like below
```
[
  '          **          ',
  '        ******        ',
  '      **********      ',
  '    **************    ',
  '  ******************  ',
  '**********************'
]
```
***
Go take a look at [Build Tower](https://www.codewars.com/kata/576757b1df89ecf5bd00073b) which is a more basic version :)

def tower_builder(n_floors, block_size):
    w, h = block_size
    return [(n_floors*w - i*w)*" " + (i*w*2-w)*"*" + (n_floors*w - i*w)*" " for i in sorted(list(range(1,n_floors+1))*h) ]
    # build here


Solve in Python:
Build a function `sumNestedNumbers`/`sum_nested_numbers` that finds the sum of all numbers in a series of nested arrays raised to the power of their respective nesting levels.  Numbers in the outer most array should be raised to the power of 1.

For example,

should return `1 + 2*2 + 3 + 4*4 + 5*5*5 === 149`

def sum_nested_numbers(x):
    return sum(f(x))

def f(lst, v=1):
    for x in lst:
        if isinstance(x, (list,tuple)):
            for j in f(x, v+1):
                yield j
        else:
            yield x**v


Solve in Python:
Caesar Ciphers are one of the most basic forms of encryption. It consists of a message and a key, and it shifts the letters of the message for the value of the key.

Read more about it here: https://en.wikipedia.org/wiki/Caesar_cipher

## Your task

Your task is to create a function encryptor that takes 2 arguments - key and message - and returns the encrypted message.

Make sure to only shift letters, and be sure to keep the cases of the letters the same. All punctuation, numbers, spaces, and so on should remain the same.

Also be aware of keys greater than 26 and less than -26. There's only 26 letters in the alphabet!

## Examples

A message `'Caesar Cipher'` and a key of `1` returns `'Dbftbs Djqifs'`.

A message `'Caesar Cipher'` and a key of `-1` returns `'Bzdrzq Bhogdq'`.

from string import maketrans as mt, ascii_lowercase as lc, ascii_uppercase as uc
def encryptor(key, message):
    key %= 26
    return message.translate(mt(lc+uc, lc[key:]+lc[:key]+uc[key:]+uc[:key]))


Solve in Python:
Calculate the number of items in a vector that appear at the same index in each vector, with the same value.

```python
   vector_affinity([1, 2, 3, 4, 5], [1, 2, 2, 4, 3]) # => 0.6
   vector_affinity([1, 2, 3], [1, 2, 3]) # => 1.0
```

Affinity value should be realized on a scale of 0.0 to 1.0, with 1.0 being absolutely identical. Two identical sets should always be evaulated as having an affinity or 1.0.

Hint: The last example test case holds a significant clue to calculating the affinity correctly.

def vector_affinity(*args):
    l1,l2 = list(map(len,args))
    return sum(x==y for x,y in zip(*args)) / (1.0 * (max(l1,l2))) if l1 or l2 else 1.0


Solve in Python:
Calculate the power of an army of numbers from 1 to $N$, both included.

-----Input:-----
- First line will contain a single integer $N$.

-----Output:-----
For each testcase, output in a single line containing the answer.

-----Constraints-----
- $1 \leq N \leq 5000$

-----Sample Input:-----
24

-----Sample Output:-----
5


Solve in Python:
Calculate the product of all elements in an array.
```if:csharp
If the array is *null*, you should throw `ArgumentNullException` and if the array is empty, you should throw `InvalidOperationException`.

As a challenge, try writing your method in just one line of code. It's possible to have only 36 characters within your method.
```
```if:javascript
If the array is `null` or is empty, the function should return `null`.
```
```if:haskell
If the array is empty then return Nothing, else return Just product.
```
```if:php
If the array is `NULL` or empty, return `NULL`.
```
```if:python
If the array is empty or `None`, return `None`.
```
```if:ruby
If the array is `nil` or is empty, the function should return `nil`.
```
```if:crystal
If the array is `nil` or is empty, the function should return `nil`.
```
```if:groovy
If the array is `null` or `empty` return `null`.
```
```if:julia
If the input is `nothing` or an empty array, return `nothing`
```

def product(numbers):
    if numbers: return eval('*'.join(map(str,numbers)))


Solve in Python:
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Example:
Given a = 1 and b = 2, return 3.

Credits:Special thanks to @fujiaozhu for adding this problem and creating all test cases.

class Solution:
     def getSum(self, a, b):
         """
         :type a: int
         :type b: int
         :rtype: int
         """
         if a == 0:
             return b
         if b == 0:
             return a

         MAX = 0x7FFFFFFF
         MIN = 0x80000000
         mask = 0xFFFFFFFF
         while b:
             a, b = (a ^ b) & mask, ((a & b) << 1) & mask

         return a if a <= MAX else ~(a ^ mask)


Solve in Python:
Calculate the trace of a square matrix. A square matrix has `n` rows and `n` columns, where `n` is any integer > 0. The entries of the matrix can contain any number of integers. The function should return the calculated trace of the matrix, or `nil/None` if the array is empty or not square; you can otherwise assume the input will be valid (of the form described below).

The trace of an n-by-n square matrix **A** is defined to be the sum of the elements on the main diagonal (the diagonal from the upper left to the lower right) of **A**.

A matrix will be defined as an array of arrays, where the 1st entry represents the 1st row, the 2nd entry the 2nd row, and so on.

For example, the following code...
```ruby,python
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
```
represents the matrix
```
|1 2 3|
|4 5 6|
|7 8 9|
```
which has a trace of `1 + 5 + 9 = 15`.

You can read more about the trace of a matrix at these sources:

 * http://en.wikipedia.org/wiki/Trace_(linear_algebra)
 * http://mathworld.wolfram.com/MatrixTrace.html

~~~if:ruby
Note: The `Matrix` class is disabled.
~~~
~~~if:python
Note: `Numpy` is disabled.
~~~

trace=lambda m:None if not m or len(m)!=len(m[0]) else sum([m[i][i] for i in range(len(m))])


Solve in Python:
Calculus class...is awesome! But you are a programmer with no time for mindless repetition. Your teacher spent a whole day covering differentiation of polynomials, and by the time the bell rang, you had already conjured up a program to automate the process.

You realize that a polynomial of degree n

anx^(n) + an-1x^(n-1) + ... + a0

can be represented as an array of coefficients

[an, an-1, ...,  a0]

For example, we would represent

5x^(2) + 2x + 1 as [5,2,1]

3x^(2) + 1 as [3,0,1]

x^(4) as [1,0,0,0,0]

x as [1, 0]

1 as [1]

Your function will take a coefficient array as an argument and return a **new array** representing the coefficients of the derivative.

```python
poly1 = [1, 1] # x + 1
diff(poly1) == [1] # 1

poly2 = [1, 1, 1] # x^2 + x + 1
diff(poly2) == [2, 1] # 2x + 1
diff(diff(poly2)) == [2] # 2

poly3 = [2, 1, 0, 0] # 2x^3 + x^2
diff(poly3) == [6, 2, 0] # 6x^2 + 2x
```
Note: your function will always return a new array which has one less element than the argument (unless the argument is [], in which case [] is returned).

def diff(poly):
    return [i * n for i, n in enumerate(poly[-2::-1], 1)][::-1]


Solve in Python:
Cara is applying for several different jobs.
The online application forms ask her to respond within a specific character count.
Cara needs to check that her answers fit into the character limit.

Annoyingly, some application forms count spaces as a character, and some don't.

Your challenge:

Write Cara a function `charCheck()` with the arguments:

- `"text"`: a string containing Cara's answer for the question
- `"max"`: a number equal to the maximum number of characters allowed in the answer
- `"spaces"`: a boolean which is `True` if spaces are included in the character count and `False` if they are not

The function `charCheck()` should return an array: `[True, "Answer"]` , where `"Answer"` is equal to the original text, if Cara's answer is short enough.

If her answer `"text"` is too long, return an array: `[False, "Answer"]`.
The second element should be the original `"text"` string truncated to the length of the limit.

When the `"spaces"` argument is `False`, you should remove the spaces from the `"Answer"`.

For example:

- `charCheck("Cara Hertz", 10, True)` should return `[ True, "Cara Hertz" ]`
- `charCheck("Cara Hertz", 9, False)` should return `[ True, "CaraHertz" ]`
- `charCheck("Cara Hertz", 5, True)` should return `[ False, "Cara " ]`
- `charCheck("Cara Hertz", 5, False)` should return `[ False, "CaraH" ]`

def charCheck(text, mx, spaces):
    if spaces == False:
        text = text.replace(" ", "")

    return [len(text) <= mx, text[:mx]]


Solve in Python:
Cascading Style Sheets (CSS) is a style sheet language used for describing the look and formatting of a document written in a markup language. A style sheet consists of a list of rules. Each rule or rule-set consists of one or more selectors, and a declaration block. Selector describes which element it matches.

Sometimes element is matched to multiple selectors. In this case, element inherits multiple styles, from each rule it matches. Rules can override each other. To solve this problem, each selector has it's own 'specificity' - e.g. weight. The selector with greater specificity overrides the other selector.

Your task is to calculate the weights of two selectors and determine which of them will beat the other one.

```python
compare("body p", "div") # returns "body p"
compare(".class", "#id") # returns "#id"
compare("div.big", ".small") # returns "div.big"
compare(".big", ".small") # returns ".small" (because it appears later)
```

For simplicity, all selectors in test cases are CSS1-compatible, test cases don't include pseudoclasses, pseudoelements, attribute selectors, etc. Below is an explanation on how to weight two selectors. You can read more about specificity here.

The simplest selector type is ``tagname`` selector. It writes as a simple  alphanumeric identifier: eg ``body``, ``div``, ``h1``, etc. It has the least weight. If selectors have multiple elements - the selector with more elements win. For example, ``body p`` beats ``div``, because it refers to 2 (nested) elements rather than 1.

Another simple selector is ``.class`` selector. It begins with dot and refer to element with specific ``class`` attribute. Class selectors can also be applied to tagname selectors, so ``div.red`` refer to ```` element. They can be grouped, for example, ``.red.striped``. Class selector beats tagname selector.

The most weighted selector type in stylesheet is ``#id`` selector. It begins with hash sign and refer to element with specific ``id`` attribute. It can also be standalone, or applied to an element. Id...

import re

def compare(a, b):
    return a if specificity(a) > specificity(b) else b

def specificity(s):
    return [len(re.findall(r, s)) for r in (r'#\w+', r'\.\w+', r'(^| )\w+')]


Solve in Python:
Catherine received an array of integers as a gift for March 8. Eventually she grew bored with it, and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute

$$ (a_1 + a_2) \oplus (a_1 + a_3) \oplus \ldots \oplus (a_1 + a_n) \\ \oplus (a_2 + a_3) \oplus \ldots \oplus (a_2 + a_n) \\ \ldots \\ \oplus (a_{n-1} + a_n) \\ $$

Here $x \oplus y$ is a bitwise XOR operation (i.e. $x$ ^ $y$ in many modern programming languages). You can read about it in Wikipedia: https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation.

-----Input-----

The first line contains a single integer $n$ ($2 \leq n \leq 400\,000$) — the number of integers in the array.

The second line contains integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^7$).

-----Output-----

Print a single integer — xor of all pairwise sums of integers in the given array.

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

Output
3
Input
3
1 2 3

Output
2

-----Note-----

In the first sample case there is only one sum $1 + 2 = 3$.

In the second sample case there are three sums: $1 + 2 = 3$, $1 + 3 = 4$, $2 + 3 = 5$. In binary they are represented as $011_2 \oplus 100_2 \oplus 101_2 = 010_2$, thus the answer is 2.

$\oplus$ is the bitwise xor operation. To define $x \oplus y$, consider binary representations of integers $x$ and $y$. We put the $i$-th bit of the result to be 1 when exactly one of the $i$-th bits of $x$ and $y$ is 1. Otherwise, the $i$-th bit of the result is put to be 0. For example, $0101_2 \, \oplus \, 0011_2 = 0110_2$.

import sys
input = sys.stdin.readline

n = int(input())
a = list(map(int, input().split()))
b = a

ans = 0
for k in range(29):
    a0 = []
    a1 = []
    a0a = a0.append
    a1a = a1.append

    b0 = []
    b1 = []
    b0a = b0.append
    b1a = b1.append
    for i in a:
        if i&(1<<k): a1a(i)
        else: a0a(i)
    for i in b:
        if i&(1<<k): b1a(i)
        else: b0a(i)

    a = a0+a1
    b = b0+b1
    mask = (1<<(k+1))-1

    aa = [i&mask for i in a]
    bb = [i&mask for i in b]

    res = 0
    p1 = 1<<k
    p2 = mask+1
    p3 = p1+p2

    j1 = j2 = j3 = 0
    for jj, ai in enumerate(reversed(aa)):
        while j1 < n and ai+bb[j1] < p1:
            j1 += 1
        while j2 < n and ai+bb[j2] < p2:
            j2 += 1
        while j3 < n and ai+bb[j3] < p3:
            j3 += 1
        res += max(n, n - jj) - max(j3, n - jj)
        res += max(j2, n - jj) - max(j1, n - jj)
    ans |= (res & 1) << k

print(ans)


Solve in Python:
Cengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows:   $f(0) = a$;  $f(1) = b$;  $f(n) = f(n-1) \oplus f(n-2)$ when $n > 1$, where $\oplus$ denotes the bitwise XOR operation.

You are given three integers $a$, $b$, and $n$, calculate $f(n)$.

You have to answer for $T$ independent test cases.

-----Input-----

The input contains one or more independent test cases.

The first line of input contains a single integer $T$ ($1 \le T \le 10^3$), the number of test cases.

Each of the $T$ following lines contains three space-separated integers $a$, $b$, and $n$ ($0 \le a, b, n \le 10^9$) respectively.

-----Output-----

For each test case, output $f(n)$.

-----Example-----
Input
3
3 4 2
4 5 0
325 265 1231232

Output
7
4
76

-----Note-----

In the first example, $f(2) = f(0) \oplus f(1) = 3 \oplus 4 = 7$.

for cas in range(int(input())):
    x, y, z = map(int, input().split())
    print([x, y, x ^ y][z % 3])


Solve in Python:
Cersei wants to be the queen of seven kingdoms.

For this to happen, she needs to address the soldiers in her army. There are n$n$ soldiers in her army (numbered 1$1$ through n$n$). Cersei passes on the message to the first soldier (soldier 1).
This message needs to reach every soldier in the army. For this, the soldiers communicate among themselves by one soldier passing the message to another soldier through some communication links. It is known that the message could reach every soldier using the given links.
Now, each soldier will receive the message from exactly one soldier or Cersei and could pass on the message to atmost two soldiers. That is each soldier (except soldier 1) has only one incoming link and every soldier (including soldier 1) has atmost two outgoing links.
Now, the High Sparrow feels that Cersei is planning to kill his people first. Hence, for the sake of his people, he decided to appoint some sparrows to overhear every conversation between the soldiers (The conversation between Cersei and the first soldier needn't be overheard due to the fear of Ser Gregor Clegane).
To overhear a conversation between soldiers A$A$ and B$B$, there needs to be a sparrow either at soldier A$A$ or soldier B$B$ or both.
Also, by his research, the High Sparrow has found that the soldiers are partitioned into some classes (1$1$ to k$k$). That is, every soldier belongs to exactly one class. He then demands the presence of atleast one sparrow with each class he knows (1$1$ to k$k$).
Find the minimum number of sparrows the High Sparrow needs to recruit for the job or tell that he couldn't.

-----Input:-----
- The first line of the input contains the number of test cases t$t$.
- The first line of each test case gives the number of soldiers n$n$ in the army, the number of communication links m$m$ between the soldiers and the number of classes k$k$ in soldiers.
- The next line of the test case consists of n$n$ integers A1,A2....An$A_1,A_2....A_n$ each denoting the class of the ith$i^{th}$ soldier.
- The next...


Solve in Python:
Challenge:

Given a two-dimensional array, return a new array which carries over only those arrays from the original, which were not empty and whose items are all of the same type (i.e. homogenous). For simplicity, the arrays inside the array will only contain characters and integers.

Example:

Given [[1, 5, 4], ['a', 3, 5], ['b'], [], ['1', 2, 3]], your function should return [[1, 5, 4], ['b']].

Addendum:

Please keep in mind that for this kata, we assume that empty arrays are not homogenous.

The resultant arrays should be in the order they were originally in and should not have its values changed.

No implicit type casting is allowed. A subarray [1, '2'] would be considered illegal and should be filtered out.

def f(array):
    if array == [] : return False
    return all([type(array[0]) == type(e) for e in array])

def filter_homogenous(arrays):
    return [a for a in arrays if f(a)]


Solve in Python:
Challenge:
Given two null-terminated strings in the arguments "string" and "prefix", determine if "string" starts with the "prefix" string. Return 1 (or any other "truthy" value) if true, 0 if false.

Example:
```
startsWith("hello world!", "hello"); // should return 1.
startsWith("hello world!", "HELLO"); // should return 0.
startsWith("nowai", "nowaisir"); // should return 0.
```

Addendum:
For this problem, an empty "prefix" string should always return 1 (true) for any value of "string".

If the length of the "prefix" string is greater than the length of the "string", return 0.

The check should be case-sensitive, i.e. startsWith("hello", "HE") should return 0, whereas startsWith("hello", "he") should return 1.

The length of the "string" as well as the "prefix" can be defined by the formula: 0 <= length < +Infinity

No characters should be ignored and/or omitted during the test, e.g. whitespace characters should not be ignored.

def starts_with(st, prefix):
    if len(st)==0!=len(prefix):
        return False
    elif len(prefix)==0:
        return True
    else:
        try:
            a = 0
            for i in range(len(prefix)):
                if st[i]==prefix[i]:
                    a+=1
            if a==len(prefix):
                return True
            else:
                return False
        except:
            return False


Solve in Python:
Chandler has a list of non zero positive integers with him. He made a very interesting observation about the list. He noticed that the number of unique integers in an array of size $N$ is in the range $L$ to $R$ (both inclusive) and every element was either 1 or an even number x, in which case x/2 was also definitely present in the array.
Chandler has misplaced the list of integers but he wants to impress Monica with his problem solving skills by finding out the minimum and maximum possible sum of all elements of the list of integers.
Can you also help him solve the problem so that he can win over Monica?

-----Input:-----
- First line will contain $T$, the number of testcases.
- The first line of each test case contains integers $N$, $L$, and $R$.

-----Output:-----
For each test case print 2 space-separated integers, the minimum and the maximum possible sum of N elements based on the above facts.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq N \leq 1000$
- $1 \leq L \leq R \leq min(N,20)$

-----Sample Input:-----
2

4 2 2

5 1 5

-----Sample Output:-----
5 7

5 31

-----EXPLANATION:-----
-
Example 1: For an array of size 4, with minimum 2 unique integers and maximum 2 unique integers, the possible arrays are (1,1,1,2), (1,1,2,2), (1,2,2,2)
Out of these, the minimum possible sum of elements is 5(1+1+1+2) and maximum possible sum is 7(1+2+2+2)
-
Example 2: For an array of size 5, with minimum 1 unique integer and maximum 5 unique integers, minimum possible sum of elements is 5(1+1+1+1+1) and maximum possible sum is 31(1+2+4+8+16)

# cook your dish here
for i in range(int(input())):
 n, l, r = list(map(int, input().split()))
 mins = 0
 maxs = 0
 start = 1
 end = 2 ** (min(r,n) - 1)
 cend = end
 reached = True
 add=True
 for j in range(n):
  mins +=start
  if j + 1 == l:
   reached = False
   start = 1
  elif reached:
   start *= 2

 reached = True
 for j in range(n):
  maxs += end
  if j + 1 == r:
   reached = False
   end = cend
  elif reached:
   end = end // 2
 print(mins, maxs)


Solve in Python:
Chaneka has a hobby of playing with animal toys. Every toy has a different fun value, a real number. Chaneka has four boxes to store the toys with specification:   The first box stores toys with fun values in range of $(-\infty,-1]$.  The second box stores toys with fun values in range of $(-1, 0)$.  The third box stores toys with fun values in range of $(0, 1)$.  The fourth box stores toys with fun value in range of $[1, \infty)$.

Chaneka has $A$, $B$, $C$, $D$ toys in the first, second, third, and fourth box, respectively. One day she decides that she only wants one toy, a super toy. So she begins to create this super toy by sewing all the toys she has.

While the number of toys Chaneka has is more than 1, she takes two different toys randomly and then sews them together, creating a new toy. The fun value of this new toy is equal to the multiplication of fun values of the sewn toys. She then puts this new toy in the appropriate box. She repeats this process until she only has one toy. This last toy is the super toy, and the box that stores this toy is the special box.

As an observer, you only know the number of toys in each box initially but do not know their fun values. You also don't see the sequence of Chaneka's sewing. Determine which boxes can be the special box after Chaneka found her super toy.

-----Input-----

The first line has an integer $T$ $(1 \le T \le 5 \cdot 10^4)$, the number of test cases.

Every case contains a line with four space-separated integers $A$ $B$ $C$ $D$ $(0 \le A, B, C, D \le 10^6, A + B + C + D > 0)$, which denotes the number of toys in the first, second, third, and fourth box, respectively.

-----Output-----

For each case, print four space-separated strings. Each string represents the possibility that the first, second, third, and fourth box can be the special box from left to right.

For each box, print "Ya" (Without quotes, Indonesian for yes) if that box can be the special box. Print "Tidak" (Without quotes, Indonesian for No)...


Solve in Python:
Chang's new maths teacher is very enthusiastic about making sure that students understand the concept rather than remembering it. On her first day at teaching, she gives an assignment to all the students to test their potential. Chang wants to demonstrate that he understands the concept rather than rote learning. Help Chang in doing this by solving the hardest problem in the assignment. The problem is written as follows.

A perfect function is defined in the following manner.

- F(x, y) = x2 + y for 1 ≤ x ≤ A, 1 ≤ y ≤ B
- F(x, y) = 2 otherwise

Find the number of integral pairs (x, y) such that F(x, y) is a perfect square.

-----Input-----
First and the only line of the input contains two single space separated integers A and B.

-----Output-----
Output a single integer indicating the output to the only test case.

-----Constraints-----
- 1 ≤ A, B ≤ 106

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

Output:
1

-----Explanation-----
Example case 1.
(1, 3) is the only pair such that x = 1, y = 3 satisfying x <= 4 and y <= 4. 1^2 + 3 = 4 which is a perfect square.

# cook your dish here
a,b=map(int,input().strip().split(' '))
count=0
import math
r=int(math.sqrt(b))
for i in range(1,a+1):
  for j in range(1,b+1):
   r=i*i+j
   x=math.sqrt(r)
   if(int(x)==x):
    count+=1
print(count)


Solve in Python:
Character recognition software is widely used to digitise printed texts. Thus the texts can be edited, searched and stored on a computer.

When documents (especially pretty old ones written with a typewriter), are digitised character recognition softwares often make mistakes.

Your task is correct the errors in the digitised text. You only have to handle the following mistakes:

* `S`  is misinterpreted as `5`
* `O` is misinterpreted as `0`
* `I` is misinterpreted as `1`

The test cases contain numbers only by mistake.

def correct(string):
    for strings in string:
        if strings.isdigit():
            string = string.replace("5","S")
            string = string.replace("0","O")
            string = string.replace("1","I")
    return string


Solve in Python:
Check if given chord is minor or major.

_____________________________________________________________
Rules:

1. Basic minor/major chord have three elements.

2. Chord is minor when interval between first and second element equals 3 and between second and third -> 4.

3. Chord is major when interval between first and second element equals 4 and between second and third -> 3.

4. In minor/major chord interval between first and third element equals... 7.

_______________________________________________________________
There is a preloaded list of the 12 notes of a chromatic scale built on C. This means that there are (almost) all allowed note' s names in music.

notes =
['C', ['C#', 'Db'], 'D', ['D#', 'Eb'], 'E', 'F', ['F#', 'Gb'], 'G', ['G#', 'Ab'], 'A', ['A#', 'Bb'], 'B']

Note that e. g. 'C#' - 'C' = 1, 'C' - 'C#' = 1, 'Db' - 'C' = 1 and 'B' - 'C' = 1.

Input:
String of notes separated by whitespace, e. g. 'A C# E'

Output:
String message: 'Minor', 'Major' or 'Not a chord'.

notes = ["C", ["C#", "Db"], "D", ["D#", "Eb"], "E", "F", ["F#", "Gb"], "G", ["G#", "Ab"], "A", ["A#", "Bb"], "B"]
mom = {(3, 4): "Minor", (4, 3): "Major"}
levels = {
    x: i
    for i, xs in enumerate(notes)
    for x in ([xs] if isinstance(xs, str) else xs)
}

def minor_or_major(chord):
    xs = [levels.get(c) for c in chord.split()]
    if None in xs:
        return "Not a chord"
    deltas = tuple((b - a) % len(notes) for a, b in zip(xs, xs[1:]))
    return mom.get(deltas, "Not a chord")


Solve in Python:
Check if given numbers are prime numbers.
If number N is prime ```return "Probable Prime"``` else ``` return "Composite"```.
HINT: Upper bount is really big so you should use an efficient algorithm.

Input
  1 < N ≤ 10^(100)

Example
  prime_or_composite(2)  # should return Probable Prime
  prime_or_composite(200)  # should return Composite

import random

def prime_or_composite(q, k=100):
    q = abs(q)
    if q == 2:
        return 'Probable Prime'
    if q < 2 or q & 1 == 0:
        return 'Composite'

    d = (q - 1) >> 1
    while d & 1 == 0:
        d >>= 1
    for i in range(k):
        a = random.randint(1, q - 1)
        t = d
        y = pow(a, t, q)
        while t != q - 1 and y != 1 and y != q - 1:
            y = pow(y, 2, q)
            t <<= 1
        if y != q - 1 and t & 1 == 0:
            return 'Composite'
    return 'Probable Prime'


Solve in Python:
Check if it is a vowel(a, e, i, o, u,) on the ```n``` position in a string (the first argument). Don't forget about uppercase.

A few cases:

```
{
checkVowel('cat', 1)  ->   true // 'a' is a vowel
checkVowel('cat', 0)  ->   false // 'c' is not a vowel
checkVowel('cat', 4)  ->   false // this position doesn't exist
}
```
P.S. If n < 0, return false

def check_vowel(s,t):
    if t==0 and s[t] in 'aioueAEIOU':
        return True
    return True if t>0  and t<len(s) and s[t] in 'aioueAEIOU'  else False
    pass


Solve in Python:
Check your arrows
You have a quiver of arrows, but some have been damaged. The quiver contains arrows with an optional range information (different types of targets are positioned at different ranges), so each item is an arrow.

You need to verify that you have some good ones left, in order to prepare for battle:
```python
anyArrows([{'range': 5}, {'range': 10, 'damaged': True}, {'damaged': True}])
```

If an arrow in the quiver does not have a damaged status, it means it's new.

The expected result is a boolean, indicating whether you have any good arrows left.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

any_arrows=lambda arrows: any([not x["damaged"] if "damaged" in x else True for x in arrows])


Solve in Python:
Cheesy Cheeseman just got a new monitor! He is happy with it, but he just discovered that his old desktop wallpaper no longer fits. He wants to find a new wallpaper, but does not know which size wallpaper he should be looking for, and alas, he just threw out the new monitor's box. Luckily he remembers the width and the aspect ratio of the monitor from when Bob Mortimer sold it to him. Can you help Cheesy out?
# The Challenge

Given an integer `width` and a string `ratio` written as `WIDTH:HEIGHT`, output the screen dimensions as a string written as `WIDTHxHEIGHT`.

def find_screen_height(width, ratio):
    r = ratio.split(':')
    return f'{width}x{int(width * int(r[1]) / int(r[0]))}'


Solve in Python:
Chef Ada has a matrix with $N$ rows (numbered $1$ through $N$ from top to bottom) and $N$ columns (numbered $1$ through $N$ from left to right) containing all integers between $1$ and $N^2$ inclusive. For each valid $i$ and $j$, let's denote the cell in the $i$-th row and $j$-th column by $(i,j)$.
Ada wants to sort the matrix in row-major order ― for each valid $i$ and $j$, she wants the cell $(i, j)$ to contain the value $(i-1) \cdot N + j$.
In one operation, Ada should choose an integer $L$ and transpose the submatrix between rows $1$ and $L$ and columns $1$ and $L$ (inclusive). Formally, for each $i$ and $j$ ($1 \le i, j \le L$), the value in the cell $(i, j)$ after this operation is equal to the value in $(j, i)$ before it.
The initial state of the matrix is chosen in such a way that it is possible to sort it using a finite number of operations (possibly zero). Find the smallest number of operations required to sort the matrix.

-----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 next $N$ lines describe the matrix. For each valid $i$, the $i$-th of these lines contains $N$ space-separated integers ― the initial values in cells $(i, 1), (i, 2), \ldots, (i, N)$.

-----Output-----
For each test case, print a single line containing one integer ― the smallest number of operations required to sort the matrix.

-----Constraints-----
- $4 \le N \le 64$
- the sum of $N^2$ over all test files does not exceed $3 \cdot 10^5$

-----Subtasks-----
Subtask #1 (10 points):
- $T \le 50$
- $N = 4$
Subtask #2 (90 points): original constraints

-----Example Input-----
1
4
1 2 9 13
5 6 10 14
3 7 11 15
4 8 12 16

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

-----Explanation-----
Example case 1: After the first operation, with $L = 2$, the resulting matrix is
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16

After the second operation, with $L = 4$, the matrix becomes sorted
1 2 3 4
5...

# cook your dish here
t= int(input())
for test in range(t):
 n= int(input())
 matrix = []
 count = 0
 for i in range(n):
  A = list(map(int,input().split()))
  matrix.append(A)

 for i in range(n-1,0,-1):
  if matrix[0][i] != i+1:
   count+=1
   for j in range(i,0,-1):
    temp = matrix[0][j]
    matrix[0][j] = matrix[j][0]
    matrix[j][0] = temp

 print(count)


Solve in Python:
Chef Ada is building a new restaurant in the following way:
- First, $N$ points $X_1, X_2, \ldots, X_N$ are chosen on the $x$-axis.
- Then, $N$ columns (numbered $1$ through $N$) are made. For simplicity, the columns are represented as vertical segments; for each valid $i$, the height of the $i$-th segment is $H_i$.
- Ada assigns a column to each of the points $X_1, X_2, \ldots, X_N$ in an arbitrary way (each column must be assigned to exactly one point).
- Finally, Ada constructs the roof of the restaurant, represented by a polyline with $N$ vertices. Let's denote the column assigned to the $i$-th point by $P_i$. For each valid $i$, the $i$-th of these vertices is $(X_i, H_{P_i})$, i.e. the polyline joins the tops of the columns from left to right.
Ada wants the biggest restaurant. Help her choose the positions of the columns in such a way that the area below the roof is the biggest possible. Formally, she wants to maximise the area of the polygon whose perimeter is formed by the roof and the segments $(X_N, H_{P_N}) - (X_N, 0) - (X_1, 0) - (X_1, H_{P_1})$. Let $S$ be this maximum area; you should compute $2 \cdot S$ (it is guaranteed that $2 \cdot S$ is an integer).

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- $N$ lines follow. For each valid $i$, the $i$-th of these lines contains two space-separated integers $X_i$ and $H_i$.

-----Output-----
For each test case, print a single line containing one integer $2 \cdot S$.

-----Constraints-----
- $1 \le T \le 3 \cdot 10^5$
- $2 \le N \le 10^5$
- $0 \le X_1 < X_2 < \ldots < X_N \le 2 \cdot 10^9$
- $1 \le H_i \le 10^9$ for each valid $i$
- the sum of $N$ over all test cases does not exceed $10^6$

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

-----Example Output-----
27

-----Explanation-----

# cook your dish here
# cook your dish here
t=int(input(''))
for k in range (t):
 n=int(input(''))
 li=[]
 li1=[]
 li2=[]
 for i in range (n):
  p,q=input().split()
  p=int(p)
  q=int(q)
  li.append(p)
  li1.append(q)
 r=li[1]-li[0]
 #print(r)
 li2.append(r)
 for i in range (1,n-1):
  p=li[i+1]-li[i-1]
  li2.append(p)
 li2.append(li[n-1]-li[n-2])
 li2.sort()
 li1.sort()
 ans=0
 for i in range (n):
  ans=ans+li1[i]*li2[i]
  #print(li2[i])
 print(ans)


Solve in Python:
Chef Ada is preparing $N$ dishes (numbered $1$ through $N$). For each valid $i$, it takes $C_i$ minutes to prepare the $i$-th dish. The dishes can be prepared in any order.
Ada has a kitchen with two identical burners. For each valid $i$, to prepare the $i$-th dish, she puts it on one of the burners and after $C_i$ minutes, removes it from this burner; the dish may not be removed from the burner before those $C_i$ minutes pass, because otherwise it cools down and gets spoiled. Any two dishes may be prepared simultaneously, however, no two dishes may be on the same burner at the same time. Ada may remove a dish from a burner and put another dish on the same burner at the same time.
What is the minimum time needed to prepare all dishes, i.e. reach the state where all dishes are prepared?

-----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 $C_1, C_2, \ldots, C_N$.

-----Output-----
For each test case, print a single line containing one integer ― the minimum number of minutes needed to prepare all dishes.

-----Constraints-----
- $1 \le T \le 1,000$
- $1 \le N \le 4$
- $1 \le C_i \le 5$ for each valid $i$

-----Subtasks-----
Subtask #1 (1 points): $C_1 = C_2 = \ldots = C_N$
Subtask #2 (99 points): original constraints

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

-----Example Output-----
4
3
7

-----Explanation-----
Example case 1: Place the first two dishes on the burners, wait for two minutes, remove both dishes and prepare the last one on one burner.
Example case 2: Place the first and third dish on the burners. When the first dish is prepared, remove it and put the second dish on the same burner.
Example case 3: Place the third and fourth dish on the burners. When the third dish is prepared, remove it and put the second dish on the same burner. Similarly, replace the fourth dish...

# cook your dish here
for _ in range(int(input())):
  n=int(input())
  a=list(map(int,input().split()))
  a.sort()
  if(n==1):
   print(a[0])
  elif(n==2):
   print(max(a[0],a[1]))
  else:
   b=a[n-1]
   c=a[n-2]
   for i in range(n-3,-1,-1):
     if(c<b):
      c+=a[i]
     else:
      b+=a[i]
   if(c<b):
     print(b)
   else:
     print(c)


Solve in Python:
Chef Ada is the FootBall coach of the Dinosaurs Institute of Technology.
There are $N$ dinosaurs (enumerated $1$ through $N$) placed in a line. The i-th dinosaur has a height of $i$ meters.
Ada is training The dinosaurs in the following tactic:
- Initially the leftmost dinosaur has the ball.
- The dinosaur that has the ball passes the ball to the nearest dinosaur to the right that is tallest than him.
- The previous step continues until the ball reaches the tallest dinosaur, then he throws the ball and scores a goal!
Help Ada reordering the dinosaurs in such a way that the ball is passed from dinosaur to dinosaur exactly $K$ times.
For example, if there are $5$ dinosaurs ordered as $[2,3,1,5,4]$, then the ball goes $2 \rightarrow 3\rightarrow5 \rightarrow goal$, and the ball was passed two times.

-----Input:-----
- First line will contain $T$, number of testcases.
- Each test case consist of a line with two space separated integers $N,K$.

-----Output:-----
For each testcase, output in a single line conaining $N$ integers representing one possible ordering in which the dinosaurs can be placed.

-----Constraints-----
- $1 \leq T \leq 2^8$
- $2 \leq N \leq 20$
- $0 \leq K \leq N-1$

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

-----Sample Output:-----
2 3 1 5 4

# cook your dish here
t=int(input())
while t!=0:
 n,k=map(int,input().split())
 lst=[]
 for i in range(1,n+1):
  lst.append(i)
 lst[k],lst[n-1]=lst[n-1],lst[k]
 for item in lst:
  print(item,end=' ')
 t-=1


Solve in Python:
Chef Al Gorithm was reading a book about climate and oceans when he encountered the word “glaciological”. He thought it was quite curious, because it has the following interesting property: For every two letters in the word, if the first appears x times and the second appears y times, then |x - y| ≤ 1.
Chef Al was happy about this and called such words 1-good words. He also generalized the concept: He said a word was K-good if for every two letters in the word, if the first appears x times and the second appears y times, then |x - y| ≤ K.
Now, the Chef likes K-good words a lot and so was wondering: Given some word w, how many letters does he have to remove to make it K-good?

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
Each test case consists of a single line containing two things: a word w and an integer K, separated by a space.

-----Output-----
For each test case, output a single line containing a single integer: the minimum number of letters he has to remove to make the word K-good.

-----Constraints-----
- 1 ≤ T ≤ 30
- 1 ≤ |w| ≤ 105
- 0 ≤ K ≤ 105
- w contains only lowercase English letters.

-----Example-----
Input:
4
glaciological 1
teammate 0
possessions 3
defenselessness 3

Output:
0
0
1
2

-----Explanation-----
Example case 1. The word “glaciological” is already 1-good, so the Chef doesn't have to remove any letter.
Example case 2. Similarly, “teammate” is already 0-good.
Example case 3. The word “possessions” is 4-good. To make it 3-good, the Chef can remove the last s to make “possession”.
Example case 4. The word “defenselessness” is 4-good. To make it 3-good, Chef Al can remove an s and an e to make, for example, “defenslesness”. Note that the word doesn't have to be a valid English word.

t = int(input())
while t:
 w,k = input().split()
 k = int(k)
 char = {}
 for c in w:
  if c not in list(char.keys()):
   char[c] = 1
  else:
   char[c] += 1
 counts = list(char.values())
 counts.sort()
 #counts = counts[::-1]
 l = len(counts)
 ans = len(w)+1
 for i in range(l):
  temp = 0
  for j in range(l):
   if counts[j]<counts[i]:
    temp += counts[j]
   elif counts[j]>counts[i]+k:
    temp += counts[j]-counts[i]-k
  ans = min(ans,temp)
 print(ans)
 t -= 1


Solve in Python:
Chef Ciel wants to put a fancy neon signboard over the entrance of her restaurant. She has not enough money to buy the new one so she bought some old neon signboard through the internet. Ciel was quite disappointed when she received her order - some of its letters were broken. But she realized that this is even better - she could replace each broken letter by any letter she wants. So she decided to do such a replacement that the resulting signboard will contain the word "CHEF" as many times as possible.
We can model the signboard as a string S having capital letters from 'A' to 'Z', inclusive, and question marks '?'. Letters in the string indicate the intact letters at the signboard, while question marks indicate broken letters. So Ciel will replace each question mark with some capital letter and her goal is to get the string that contains as many substrings equal to "CHEF" as possible. If there exist several such strings, she will choose the lexicographically smallest one.
Note 1. The string S = S1...SN has the substring "CHEF" if for some i we have SiSi+1Si+2Si+3 = "CHEF". The number of times "CHEF" is the substring of S is the number of those i for which SiSi+1Si+2Si+3 = "CHEF".
Note 2. The string A = A1...AN is called lexicographically smaller than the string B = B1...BN if there exists K from 1 to N, inclusive, such that Ai = Bi for i = 1, ..., K-1, and AK < BK. In particular, A is lexicographically smaller than B if A1 < B1. We compare capital letters by their positions in the English alphabet. So 'A' is the smallest letter, 'B' is the second smallest letter, ..., 'Z' is the largest letter.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The only line of each test case contains a string S.

-----Output-----
For each test case, output a single line containing the content of the signboard Chef Ciel will come up with. That is you should output the lexicographically smallest string that could be obtained from the...

# cook your dish here
for i in range(int(input())):
 s = list(input())
 for i in range(len(s)-4,-1,-1):
  c = 0
  if s[i] == "?":
   c+=1
  else:
   if s[i] == "C":
    c+=1
   else:
    continue

  if s[i+1] == "?":
   c+=1
  else:
   if s[i+1] == "H":
    c+=1
   else:
    continue

  if s[i+2] == "?":
   c+=1
  else:
   if s[i+2] == "E":
    c+=1
   else:
    continue

  if s[i+3] == "?":
   c+=1
  else:
   if s[i+3] == "F":
    c+=1
   else:
    continue
  if c == 4:
   s[i] = "C"
   s[i+1] = "H"
   s[i+2] = "E"
   s[i+3] = "F"
 for j in range(len(s)-1,-1,-1):
  if s[j] == "?":
   s[j] = "A"
 print(*s,sep="")


Solve in Python:
Chef Hari has got a new obsession now: he has started playing chess (read about it here) and he is liking this game very much. Since Hari has spent several months playing chess with his friends, he has now decided to take part in some chess tournament in Cheftown.

There are currently two tournaments going on in Cheftown and each tournament has its own entry fee. Due to this economical restriction and his budget, Hari can take part in only one tournament.

The entry fee for first tournament is F1 units of money. The structure of tournament is as follows: first there will be group matches and then there will be finals. If Hari reaches in finals and wins it, he'll get R1 units of money. If after reaching in finals, Hari loses, he'll get R2 units of money. If Hari fails to reach in finals, he'll get nothing. The probability of reaching in finals of first tournament for Hari is p1 and probability of winning in finals after reaching is p2.

The entry fee for second tournament is F2 units of money. The structure of tournament is as follows: first there will be group matches and then there will be finals. If Hari reaches in finals, he'll immediately get R3 units of money, otherwise he'll get nothing. If after reaching in finals, Hari wins, he'll get R4 units of money. The probability of reaching in finals of second tournament for Hari is p3 and probability of winning in finals after reaching is p4.

Now, Hari wants to maximise his profit. He wants to know which tournament he should participate in such that his expected profit is maximised. Help Hari in deciding this.

Note:
In the tournaments of Cheftown, the game never ends with a draw. So, either Hari wins a game, or he loses.

-----Input-----

First line of the input contains T, the number of test cases. The description of each test case is as following:

First line of each test case contains 6 integers F1, F2, R1, R2, R3 and R4.

Next line of each test case contains 4 floating point numbers p1, p2, p3 and p4.
Each number has exactly 2 digits after decimal...

t=int(input().strip())
while t:
 f1,f2,r1,r2,r3,r4=list(map(int,input().strip().split()))
 p1,p2,p3,p4=list(map(float,input().strip().split()))
 x=p1*(1-p2)*r2+p1*p2*r1-f1
 y=p3*r3+p3*p4*r4-f2
 if x>y:
  print("FIRST")
 elif x<y:
  print("SECOND")
 else:
  print("BOTH")
 t-=1


Solve in Python:
Chef Jessie has a lot of recipes with her (N). She often remembered the starting few characters of the recipe and forgot the rest. As all the great chefs do, Jessie also numbered the recipes depending on the priority. So, given the list of recipes along with their priorities answer Jessie’s queries.
Jessie’s queries are as follows:

She gives you the first few characters of a recipe; you have to print the complete recipe with the highest priority.
Note:

Every recipe has a unique priority

-----Input-----

First line contains an integer N - the number of recipes.

Followed by N strings Si along with an integer each Vi.
Si stands for the recipe and Vi for the priority.

It is followed by an integer Q - the number of queries.

Followed by Q strings Qi.

Each string Si, Qi contain only lowercase Latin alphabets ('a' - 'z') and '-'.

-----Output-----
Q – lines, each contain the answer for each of the query.

If for a query no recipe matches print "NO". (Without quotes)
Constraints:
0 <= N <= 1000

0 <= Q <= 1000

-10^9 <= Vi <= 10^9

1 <= |Si| <= 1000 (length of Si)

1 <= |Qi| <= 1000 (length of Qi)

-----Example-----
Input:
4
flour-with-eggs 100
chicken-ham -10
flour-without-eggs 200
fish-with-pepper 1100
6
f
flour-with
flour-with-
c
fl
chik

Output:
fish-with-pepper
flour-without-eggs
flour-with-eggs
chicken-ham
flour-without-eggs
NO

nr=int(input())
d={}
for r in range(nr):
 s,v=list(map(str,input().split()))
 d[int(v)]=s
q=int(input())
lis=[]
for i in range(q):
 lis.append(input())
l=list(d.keys())
l.sort(reverse=True)
ans='NO'

for j in lis:
 ans='NO'
 for k in l:
  if len(j)<=len(d[k]):
   a=d[k]
   if j==a[0:len(j)]:
    ans=a
    break
 print(ans)


Solve in Python:
Chef Leonardo has a decimal integer $N$ and a non-zero decimal digit $d$. $N$ does not contain the digit zero; specifically, $N$ should always be treated as a decimal integer without leading zeroes.
Chef likes $d$ and does not like any other digit, so he decided to change $N$. He may apply the following operation any number of times (including zero): append the digit $d$ to the decimal representation of $N$ ($d$ becomes the least significant digit of $N$), then remove one occurrence of one digit from the decimal representation of $N$.
Chef has already changed a lot of numbers and he got bored. Now, he wants to know the smallest possible value of $N$ which can be obtained by performing the operation described above. Can you help him?

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

-----Output-----
For each test case, print a single line containing one integer - the minimum number Chef can obtain.

-----Constraints-----
- $1 \le T \le 1,000$
- $1 \le N \le 10^{18}$
- $N$ does not contain the digit $0$
- $1 \le d \le 9$

-----Subtasks-----
Subtask #1 (40 points):
- $1 \le T \le 100$
- $1 \le N \le 10^9$
Subtask #2 (60 points): original constraints

-----Example Input-----
3
35 4
42 4
24 9

-----Example Output-----
34
24
24

-----Explanation-----
Example case 1: Chef can remove the digit $5$ and add $4$ to the end of $N$. Then, $N$ becomes $34$.
Example case 2: Chef can remove the digit $4$ from the beginning of $N$, add $4$ to the end of $N$ and get $N = 24$.
Example case 3: Chef cannot make his number any smaller.

t=int(input())
for _ in range(t):
 n,k=list(map(int,input().split()))
 s=list(str(n))
 l=len(s)
 s1=""
 if(int(min(s))>k):
  for i in range(l):
   s1+=str(k)
  print(s1)
 else:
  c=min(s)
  while(int(c)!=k and len(s)!=0):
   s1+=c
   ind=s.index(c)
   s=s[ind+1:]
   #print(s)
   for i in range(ind+1):
    s.append(str(k))
    #print(s)
   c=min(s)
  z=len(s1)
  for i in range(l-z):
   s1+=str(k)
  print(s1)


Solve in Python:
Chef Loves to listen to remix songs, but currently he had already finished the entire playlist of remix songs.
As Chef is smart, so he thought let's make my own remix songs of the original songs.
Chef is not having much knowledge of making remix songs, so he came up with the simple technique in which he will pick the word which contains the smallest number of characters from the lyrics of the song, and then he will append that word to the start and end of the lyrics, also Chef will insert this word between every two words of the lyrics.
Note: While inserting a new word Chef will also insert extra white-spaces, so that every word in the final remixed lyrics is separated by space.
It is Recommended to use fast Input/Ouput techniques.

-----Input:-----
- The input contains the text $S$, which denotes the lyrics of the song.

-----Output:-----
- Print the Remixed, lyrics as done by Chef.

-----Constraints:-----
- $1 \leq Length of text $S$ \leq 10^7$

-----Sample Input:-----
Mai Hu Jiyaan

-----Sample Output:-----
Hu Mai Hu Hu Hu Jiyaan Hu

S = input().split()
N=len(S)
sml=len(S[0])
val=S[0]
for i in S:
    if len(i)<sml:
        sml=len(i)
        val=i
print(val,end=' ')
i=0
while i<N:
    print(S[i],val,end=' ')
    i+=1


Solve in Python:
Chef Shifu wanted to celebrate the success of his new restaurant with all his employees. He was willing to host a party and he had decided the location of the party as well. However, Chef Shifu was a shy person and wanted to communicate with the least possible employees to inform them about the party, and that these employees could inform their friends.

Note that an employee could only inform his/her immediate friends about the party, not his/her friends’ friends.

Chef Shifu has a list of all the friendships among his employees. Help him find the minimum number of employees he should inform, so that every employee knows about the celebration party.

-----Input-----
First line contains a single integer T - the total number of testcases.

T testcases follow. For each testcase:

The first line contains 2 space-separated integers N and M - the total number of employees working under Chef Shifu and the number of friendship relations.

M lines follow - each line contains 2 space-separated integers u and v, indicating that employee u is a friend of employee v and vice-versa.

The employees are numbered from 1 to N, and each employee is assigned a distinct integer.

-----Output-----
For each testcase, print the minimum number of employees to be informed on a new line.

-----Constraints-----
Subtask 1: 5 points

1 ≤ T ≤ 5

1 ≤ N ≤ 4

0 ≤ M ≤ N*(N-1)/2

Subtask 2: 35 points

1 ≤ T ≤ 5

1 ≤ N ≤ 15

0 ≤ M ≤ N*(N-1)/2

Subtask 3: 60 points

1 ≤ T ≤ 5

1 ≤ N ≤ 20

0 ≤ M ≤ N*(N-1)/2

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

Output
1
2

Explanation

In testcase 1, since every employee is a friend of every other employee, we just need to select 1 employee.
In testcase 2, selecting employees 2 and 4 would ensure that all 4 employees are represented.

Similarly, selecting employees 1 and 3 would also ensure that all 4 employees are selected.

In both cases, we must select 2 employees in the best case.

t=int(input())
for _ in range(t):
    n,m=map(int,input().split())
    mat=[0 for i in range(n)]
    #mat=[[0 for i in range(n)] for j in range(n)]
    for i in range(m):
     u,v=map(int,input().split())
     u,v=(u-1),(v-1)
     mat[u]|=(1<<v)
     mat[v]|=(1<<u)
    for i in range(n):
     mat[i]|=(1<<i)

    goal=(2**n)-1
    ans=n

    for i in range(1,goal+1):
     mvs=0
     loc=0
     for j in range(n):
      if(i&(1<<j)):
       loc|=mat[j]
       mvs+=1
     if(loc==goal):
      ans=min(mvs,ans)
    print(ans)


Solve in Python:
Chef Tobby asked Bhuvan to brush up his knowledge of statistics for a test. While studying some distributions, Bhuvan learns the fact that for symmetric distributions, the mean and the median are always the same.
Chef Tobby asks Bhuvan out for a game and tells him that it will utilize his new found knowledge. He lays out a total of 109 small tiles in front of Bhuvan. Each tile has a distinct number written on it from 1 to 109.
Chef Tobby gives Bhuvan an integer N and asks him to choose N distinct tiles and arrange them in a line such that the mean of median of all subarrays lies between [N-1, N+1], both inclusive. The median of subarray of even length is the mean of the two numbers in the middle after the subarray is sorted
Bhuvan realizes that his book didn’t teach him how to solve this and asks for your help. Can you solve the problem for him?
In case, no solution exists, print -1.

-----Input section-----
First line contains, T, denoting the number of test cases.
Each of the next T lines, contain a single integer N.

-----Output section-----
If no solution, exists print -1.
If the solution exists, output N space separated integers denoting the elements of the array A such that above conditions are satisfied. In case, multiple answers exist, you can output any one them.

-----Input constraints-----
1 ≤ T ≤ 20
1 ≤ N ≤ 100

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

-----Sample Output-----
1
1 2
1 2 3

-----Explanation-----
For test case 3, the subarrays and their median are as follows:
- {1}, median = 1
- {2}, median = 2
- {3}, median = 3
- {1, 2}, median = 1.5
- {2, 3}, median = 2.5
- {1, 2, 3}, median = 2
The mean of the medians is 2 which lies in the range [2, 4]

x=int(input())
for a in range(x):
 n=int(input())
 L=[str(n)]
 c=1
 while(len(L)!=n):
  L.append(str(n+c))
  if len(L)==n:
   break
  L.append(str(n-c))

  c+=1

 a=" ".join(L)

 print(a)


Solve in Python:
Chef Tobby is playing a rapid fire with Bhuvan. He gives Bhuvan a string S and each time, Bhuvan has to guess whether there exists 2 equal subsequences in the string or not.
Bhuvan got a perfect score in the game with Chef Tobby. However, Chef Tobby has now asked Bhuvan to write a program that will do this automatically given a string S. Bhuvan is an intelligent man but he does not know how to write a code. Can you help him?
Find two different subsequences such that they are equal in their value, more formally, find two sequences of indices (a1, a2, ..., ak-1, ak) and (b1, b2, ..., bk-1, bk) such that:

- 1≤ ai, bi ≤ |S|
- ai < ai+1 for all valid i
- bi < bi+1 for all valid i
- Sai = Sbi for all valid i
- there exist at least one i such that ai is not equal to bi

-----Input section-----
The first line contains T, the number of test cases.
Each of the next T lines contain one string S each.
Input will only consist of lowercase english characters

-----Output section-----
For each test case, output "yes" or "no" (without quotes) as the solution to the problem.

-----Input constraints-----
1 ≤ T ≤ 1000
1 ≤ length of S ≤ 100

-----Sample Input-----
4
likecs
venivedivici
bhuvan
codechef

-----Sample Output-----
no
yes
no
yes

-----Explanation-----
In test case 2, one of the possible equal subsequence is "vi" and "vi". (one at position {0, 3} and other at {4, 7}, assuming 0-based indexing).
In test case 4, one of the possible equal subsequence is "ce" and "ce". (one at position {0, 3} and other at {4, 6}, assuming 0-based indexing).

# cook your dish here
try:
 for _ in range(int(input())):
  s=input()
  l1=len(s)
  l2=len(set(s))
  if l1!=l2:
   print('yes')
  else:
   print('no')
except:
 pass


Solve in Python:
Chef Tobby is trying to run a code given to him by Bhuvan for an experiment they want to include in the manuscript to be submitted to a conference. The deadline to submit the manuscript is within a couple of hours and Chef Tobby needs to finish the experiments before then.
The code given by Bhuvan is the following which runs given an array of N integers and another integer K :
void recurse ( array a, int n )
{
	// n = size of array
	define array b currently empty
	consider all 2^n subsets of a[]
	{
		x = bitwise OR of elements in the subsets
		add x into "b" if it is not present yet
	}
	if (sizeof( b ) == 1 << k)
	{
		printf(“Won”);
		return;
	}
	recurse ( b, sizeof( b ) );
}

Chef Tobby tried to run an experiment with only one integer in the array with value 2 and K = 3. To his horror, he found out that the algorithm is resulting in an infinite loop. He is livid with the possibility that the algorithm can lead to infinite loops for certain cases. On closer inspection he determines that it might be possible to insert additional elements in the initial array to subvert the problem. Since time is very less, Chef Tobby would like to insert the minimum number of elements.
Chef Tobby has to finish writing the paper, so he asks his graduate student Leamas to fix it. Leamas has no idea how to fix the problem so he asks you for help.

-----Input section-----
The first line contains T, the number of test cases.
Each test case consists of 2 lines. The first line contains 2 integers N and K, denoting the number of elements in the array and parameter mentioned in problem statement.
Next line contains N space separated integers, denoting the elements of the array.

-----Output section-----
Output the minimum number of elements that need to be inserted so that inifinite loop can be avoided.

-----Input constraints-----
1 ≤ T ≤ 10
1 ≤ Sum of N over all test cases ≤ 105
1 ≤ K ≤ 20
0 ≤ A[i] ≤ 2K-1, where A[i] denotes the ith element of the array.

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

-----Sample Output -...

t = eval(input())
for tt in range(t):
 nk = input().split()
 n = int(nk[0])
 k = int(nk[1])
 lis = input().split()
 for i in range(n):
  lis[i] = int(lis[i])
 tmp = []
 for i in range(k):
  tmp.append(1 << i)
 count = 0
 for i in tmp:
  if i not in lis:
   count += 1
 print(count)


Solve in Python:
Chef Two and Chef Ten are playing a game with a number $X$. In one turn, they can multiply $X$ by $2$. The goal of the game is to make $X$ divisible by $10$.
Help the Chefs find the smallest number of turns necessary to win the game (it may be possible to win in zero turns) or determine that it is impossible.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains a single integer denoting the initial value of $X$.

-----Output-----
For each test case, print a single line containing one integer — the minimum required number of turns or $-1$ if there is no way to win the game.

-----Constraints-----
- $1 \le T \le 1000$
- $0 \le X \le 10^9$

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

-----Example Input-----
3
10
25
1

-----Example Output-----
0
1
-1

t=int(input())
for ss in range(t):
 n=int(input())
 c=0
 if(n%10==0):
  c=1
  print(0)
 elif(n%10!=0):
  for i in range(1,11):
   if((n*(2**i))%10==0):
    c=1
    print(i)
    break
 if(c==0):
  print(-1)


Solve in Python:
Chef Vivek is good in mathematics and likes solving problems on prime numbers. One day his friend Jatin told him about Victory numbers. Victory number can be defined as a number formed after summing up all the prime numbers till given number n. Now, chef Vivek who is very fond of solving questions on prime numbers got busy in some other tasks. Your task is to help him finding victory number.

-----Input:-----
- First line will contain $T$, number of test cases. Then the test cases follow.
- Each test case contains of a single line of input $N$ till which sum of all prime numbers between 1 to n has to be calculated.

-----Output:-----
For each test case, output in a single line answer to the victory number.

-----Constraints-----
- $1 <= T <= 1000$
- $1 <= N <= 10^6$

-----Sample Input:-----
3
22
13
10

-----Sample Output:-----
77
41
17

def sumOfPrimes(n):
 prime = [True] * (n + 1)
 p = 2
 while p * p <= n:
  if prime[p] == True:
   i = p * 2
   while i <= n:
    prime[i] = False
    i += p
  p += 1

 sum = 0
 for i in range (2, n + 1):
  if(prime[i]):
   sum += i
 return sum
for _ in range(int(input())):
 print(sumOfPrimes(int(input())))


Solve in Python:
Chef Watson uses a social network called ChefBook, which has a new feed consisting of posts by his friends. Each post can be characterized by f - the identifier of the friend who created the post, p - the popularity of the post(which is pre-calculated by ChefBook platform using some machine learning algorithm) and s - the contents of the post which is a string of lower and uppercase English alphabets.
Also, Chef has some friends, which he has marked as special.
The algorithm used by ChefBook for determining the order of posts in news feed is as follows:

- Posts of special friends should be shown first, irrespective of popularity. Among all such posts the popular ones should be shown earlier.
- Among all other posts, popular posts should be shown earlier.

Given, a list of identifiers of Chef's special friends and a list of posts, you have to implement this algorithm for engineers of ChefBook and output the correct ordering of posts in the new feed.

-----Input-----
First line contains N, number of special friends of Chef and M, the number of posts. Next line contains N integers A1, A2, ..., AN denoting the identifiers of special friends of Chef. Each of the next M lines contains a pair of integers and a string denoting f, p and s, identifier of the friend who created the post, the popularity of the post and the contents of the post, respectively. It is guaranteed that no two posts have same popularity, but the same friend might make multiple posts.

-----Output-----
Output correct ordering of posts in news feed in M lines. Output only the contents of a post.

-----Constraints-----
- 1 ≤ N, M ≤ 103
- 1 ≤ Ai, f, p ≤  105
- 1 ≤ length(s) ≤  100

-----Example-----
Input:
2 4
1 2
1 1 WhoDoesntLoveChefBook
2 2 WinterIsComing
3 10 TheseViolentDelightsHaveViolentEnds
4 3 ComeAtTheKingBestNotMiss

Output:
WinterIsComing
WhoDoesntLoveChefBook
TheseViolentDelightsHaveViolentEnds
ComeAtTheKingBestNotMiss

-----Explanation-----

First we should show posts created by friends with identifiers 1 and 2. Among the posts by...

n,m=input().split()
K=list(map(int,input().split()))
L=[]
M=[]
for i in range(int(m)):
 a,b,c=input().split()
 if int(a) in K:
  M.append([int(b),c])
 else:
  L.append([int(b),c])
M.sort()
M.reverse()
L.sort()
L.reverse()
for i in range(len(M)):
 print(M[i][1])
for i in range(len(L)):
 print(L[i][1])


Solve in Python:
Chef Zidane likes the number 9. He has a number N, and he wants to turn it into a multiple of 9. He cannot add or remove digits, and he can only change one digit at a time. The only allowed operation is to increment or decrement a digit by one, and doing this takes exactly one second. Note that he cannot increase a digit 9 or decrease a digit 0, and the resulting number must not contain any leading zeroes unless N has a single digit.

Chef Zidane wants to know the minimum amount of time (in seconds) needed to accomplish this. Please help him, before his kitchen gets overwhelmed with mist!

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
Each test case consists of one line containing a single positive integer N.

-----Output-----
For each test case, output a single line containing the answer.

-----Constraints-----
- 1 ≤ T ≤ 105
- 1 ≤ N ≤ 10105
- N will not contain leading zeroes.
- Each test file is at most 3Mb in size.

-----Example-----
Input:4
1989
86236
90210
99999999999999999999999999999999999999988

Output:0
2
3
2

-----Explanation-----
Example case 1. 1989 is already divisible by 9, so no operations are needed to be performed.
Example case 2. 86236 can be turned into a multiple of 9 by incrementing the first and third digit (from the left), to get 96336. This takes 2 seconds.
Example case 3. 90210 can be turned into a multiple of 9 by decrementing the third digit twice and the fourth digit once, to get 90000. This takes 3 seconds.

'''

This File is created by Saurabh Sisodia
email address... "ssisodia507@gmail.com"

................................................................................    ............

'''
for _ in range(int(input())):
 n=input()
 sum=0
 len=0
 for v in n:
  len+=1
  sum+=int(v)
 rem=sum%9
 if len>1 and sum<9:
  ans=9-rem
 else:
  ans=min(rem,9-rem)
 print(ans)


Solve in Python:
Chef and Abhishek both are fighting for the post of Chairperson to be part of ACE committee and are trying their best. To select only one student their teacher gave them a binary string (string consisting of only 0's and 1's) and asked them to find number of sub-strings present in the given string that satisfy the following condition:
The substring should start with 0 and end with 1 or the substring should start with 1 and end with 0 but not start with 0 and end with 0 and start with 1 and end with 1.
More formally, strings such as 100,0101 are allowed since they start and end with different characters. But strings such as 0110,1101 are not allowed because they start and end with same characters.
Both Chef and Abhishek try their best to solve it but couldn't do it. You being a very good friend of Chef, he asks for your help so that he can solve it and become the Chairperson.

-----Input:-----
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N denoting the length of the string.
The second line of each test case contains a binary string of length N.

-----Output:-----
For each test case, print a single line containing one integer ― the number of sub strings satisfying above conditions.

-----Constraints-----
- $1 \leq T \leq 1000$
- $2 \leq N \leq 10^9$
Binary string consist's only 0 and 1.

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

1010

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

-----EXPLANATION:-----
All possible substring are : { (1),(0),(1),(0),(10),(01),(10),(101),(010),(1010) }. Out of these only 4 substrings {(10),(01),(10),(1010)} start and end with different characters. Hence the answer 4.

for t in range(int(input())):
    def csbstr(str,n,a,b):
        tot,c=0,0
        for i in range(n):
            if(str[i]==a):
                c+=1
            if(str[i]==b):
                tot+=c
        return tot

    n=int(input())
    str=input()
    count1=csbstr(str,n,"1","0")
    count2=csbstr(str,n,"0","1")
    print(count1+count2)


Solve in Python:
Chef and Chefina are best friends. Chefina wants to test the Problem Solving skills of chef so she provides Chef 2 integer number  $X$ and $Y$
The task of chef is to take the  two numbers $X$ and $Y$ and return their SUM.
Identify whether Chef can solve the problem or not?

-----Input:-----
- First line will contain the two integers $X$ and $Y$.

-----Output:-----
For each testcase, output in a single line the SUM of these two numbers $X$ and $Y$.

-----Constraints-----
- $1 \leq X \leq 100$
- $1 \leq Y \leq 100$

-----Sample Input:-----
6 70

-----Sample Output:-----
76

x, y = list(map(int , input().split()))
print(x+y)


Solve in Python:
Chef and Paja are bored, so they are playing an infinite game of ping pong. The rules of the game are as follows:
- The players play an infinite number of games. At the end of each game, the player who won it scores a point.
- In each game, one of the players serves. Chef serves in the first game.
- After every $K$ points are scored (regardless of which players scored them), i.e. whenever $K$ games have been played since the last time the serving player changed, the player that serves in the subsequent games changes: if Chef served in the game that just finished, then Paja will serve in the next game and all subsequent games until the serving player changes again; if Paja served, then Chef will serve.
The players got a little too caught up in the game and they forgot who is supposed to serve in the next game. Will you help them determine that? So far, Chef has scored $X$ points and Paja has scored $Y$ points.

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

-----Output-----
For each test case, print a single line containing the string "Chef" if Chef is supposed to serve next or "Paja" otherwise (without quotes).

-----Constraints-----
- $1 \le T \le 50$
- $0 \le X, Y \le 10^9$
- $1 \le K \le 10^9$

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

-----Example Input-----
3
1 3 3
5 7 2
38657 76322 564

-----Example Output-----
Paja
Chef
Paja

-----Explanation-----
Example case 1: Chef served for the first three games, after that Paja started serving. He only served in one game, so he is supposed to serve next.

n=int(input())
for _ in range(n):
 x,y,k=list(map(int,input().split()))
 sumxy=x+y
 div=sumxy//k
 rem=sumxy%k
 #print("x,y,k,sumxy,div,rem",x,y,k,sumxy,div,rem)
 if (div%2==0):
  print("Chef")
 else:
  print("Paja")


Solve in Python:
Chef and Roma are playing a game. Rules of the game are quite simple.
Initially there are N piles of stones on the table.
In each turn, a player can choose one pile and remove it from the table.
Each player want to maximize the total number of stones removed by him.
Chef takes the first turn.

Please tell Chef the maximum number of stones he can remove assuming that both players play optimally.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N denoting the number of piles.
The second line contains N space separated integers A1, A2, ..., AN denoting the number of stones in each pile.

-----Output-----
For each test case, output a single line containg the maximum number of stones that Chef can remove.

-----Constraints-----
- 1 ≤ Ai ≤ 109
- Subtask 1 (35 points): T = 10, 1 ≤ N ≤ 1000
- Subtask 2 (65 points): T = 10, 1 ≤ N ≤ 105

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

Output:
4
3

# cook your dish here
t=int(input())
for _ in range(t):
 n=int(input())
 s=list(map(int,input().split()))

 s.sort(reverse=True)
 cnt=0

 for i in range(0,n,2):
  cnt += s[i]

 print(cnt)


Solve in Python:
Chef and his best friend Aleksa are into mathematical games these days. Today, they have some ( ≥ 0 ) black cells represented as B, and a white cell represented as W, lying randomly in a straight line.
They have decided to play with these cells. In a move, a player chooses some ( > 0 ) black cells lying on any one side of the white cell and remove them. It should be noted that a player is not allowed to choose black cells from both side of the given white cell. Both the players alternate their moves, and play optimally. The player who is unable to move in his respective turn will lose the game.
Aleksa, being a girl, has a habit of playing first. But Chef is fairly smart himself, and will not play the game if he is going to lose it. Therefore, he wants to know the winner beforehand. Can you tell him who is going to win the game for the given configuration of cells?

-----Input-----
First line of input contains a single integer T denoting the number of test cases. First and the only line of each test case contains a string S consisting of the characters 'B' and 'W', denoting black and white cells, respectively.

-----Output-----
For each test case, output "Chef" if chef wins the game for the given configuration. Else print "Aleksa". (quotes for clarity only).

-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ |S| ≤ 10000
- S contains exactly 1 white cell.

-----Scoring-----
-  Subtask 1:  1 ≤ T ≤ 10, 1 ≤ |S| ≤ 10 : ( 30 pts )
-  Subtask 2:  1 ≤ T ≤ 10, 1 ≤ |S| ≤ 100 : ( 30 pts )
-  Subtask 3:  1 ≤ T ≤ 10, 1 ≤ |S| ≤ 10000 : ( 40 pts )

-----Example-----
Input
3
W
BW
BWBB

Output
Chef
Aleksa
Aleksa

----- Explanation-----
-  Test 1 : Aleksa cannot make a move in her first turn as there is no black cell in the given configuration.
-  Test 2 : Aleksa can remove 1 black cell lying on the left of white cell in her turn. But then, Chef cannot make a move in his turn as there will be no black cells left.
-  Test 3 : Figure out yourself.

for _ in range(int(input())):
 st=input().split('W')
 if len(st[1])==len(st[0]):
  print('Chef')
 else:
  print('Aleksa')


Solve in Python:
Chef and his competitor Kefa own two restaurants located at a straight road. The position of Chef's restaurant is $X_1$, the position of Kefa's restaurant is $X_2$.
Chef and Kefa found out at the same time that a bottle with a secret recipe is located on the road between their restaurants. The position of the bottle is $X_3$.
The cooks immediately started to run to the bottle. Chef runs with speed $V_1$, Kefa with speed $V_2$.
Your task is to figure out who reaches the bottle first and gets the secret recipe (of course, it is possible that both cooks reach the bottle at the same time).

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains five space-separated integers $X_1$, $X_2$, $X_3$, $V_1$ and $V_2$.

-----Output-----
For each test case, print a single line containing the string "Chef" if Chef reaches the bottle first, "Kefa" if Kefa reaches the bottle first or "Draw" if Chef and Kefa reach the bottle at the same time (without quotes).

-----Constraints-----
- $1 \le T \le 10^5$
- $|X_1|, |X_2|, |X_3| \le 10^5$
- $X_1 < X_3 < X_2$
- $1 \le V_1 \le 10^5$
- $1 \le V_2 \le 10^5$

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

-----Example Output-----
Kefa
Chef
Draw

-----Explanation-----
Example case 1. Chef and Kefa are on the same distance from the bottle, but Kefa has speed $2$, while Chef has speed $1$.

for t in range(int(input())):
 x1,x2,x3,v1,v2=map(int,input().split())
 a=abs(x1-x3)
 b=abs(x2-x3)
 g=a/v1
 h=b/v2
 if g>h:
  print("Kefa")
 elif g==h:
  print("Draw")
 else:
  print("Chef")