Solve in Python:
Initially, you have the array $a$ consisting of one element $1$ ($a = [1]$).

In one move, you can do one of the following things:

  Increase some (single) element of $a$ by $1$ (choose some $i$ from $1$ to the current length of $a$ and increase $a_i$ by one);  Append the copy of some (single) element of $a$ to the end of the array (choose some $i$ from $1$ to the current length of $a$ and append $a_i$ to the end of the array).

For example, consider the sequence of five moves:

  You take the first element $a_1$, append its copy to the end of the array and get $a = [1, 1]$.  You take the first element $a_1$, increase it by $1$ and get $a = [2, 1]$.  You take the second element $a_2$, append its copy to the end of the array and get $a = [2, 1, 1]$.  You take the first element $a_1$, append its copy to the end of the array and get $a = [2, 1, 1, 2]$.  You take the fourth element $a_4$, increase it by $1$ and get $a = [2, 1, 1, 3]$.

Your task is to find the minimum number of moves required to obtain the array with the sum at least $n$.

You have to answer $t$ independent test cases.

-----Input-----

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

The only line of the test case contains one integer $n$ ($1 \le n \le 10^9$) — the lower bound on the sum of the array.

-----Output-----

For each test case, print the answer: the minimum number of moves required to obtain the array with the sum at least $n$.

-----Example-----
Input
5
1
5
42
1337
1000000000

Output
0
3
11
72
63244

for __ in range(int(input())):
    n = int(input())
    ans = 10 ** 9
    for i in range(1, min(n, 10 ** 5)):
        ans = min(i - 1 + (n - 1) // i, 10 ** 6, ans)
    if ans == 10 ** 9:
        ans = 0
    print(ans)


Solve in Python:
Inspired by [Round to the next 5](/kata/55d1d6d5955ec6365400006d).
Warning! This kata contains spoilers on the mentioned one. Solve that one first!

# The Coins of Ter
Ter is a small country, located between Brelnam and the Orange juice ocean. It uses many different coins and bills for payment. However, one day, the leaders of Ter decide that there are too many small coins. Therefore, they ban the small coins. But no one knows _which_ coins they'll ban, so they ask you to provide a tool that can recalculate a price. After all, if one does not have a 1 Terrek bill and can only give a 2 Terrek bill, one needs to adjust the oddly priced items.

# Task
Write a function `adjust`, that takes a two integers: the lowest currency unit that's still allowed, and the price/debt that needs to get adjusted. All prices are going up, and debts are remitted. The lowest currency will always be positive.

In other words:`adjust` takes two integers, `b` and `n`, and returns the smallest number `k`, such that `n <= k` and `k % b == 0 `.

# Examples
```python
adjust( 3, 0 ) ==  0
adjust( 3, 1 ) ==  3
adjust( 3, -2) ==  0
adjust( 3, -4) == -3
adjust( 3, 3 ) ==  3
adjust( 3, 6 ) ==  6
adjust( 3, 7 ) ==  9
```

Translator notice: Make sure that you provide about the same random tests, so that a user can get feedback during "Run tests", and not only during "Submit".

def adjust(coin, price):
    q, r = divmod(price, coin)
    return price if not r else (q + 1) * coin


Solve in Python:
Inspired by the development team at Vooza, write the function `howManyLightsabersDoYouOwn`/`how_many_light_sabers_do_you_own` that

* accepts the name of a programmer, and
* returns the number of lightsabers owned by that person.

The only person who owns lightsabers is Zach, by the way. He owns 18, which is an awesome number of lightsabers. Anyone else owns 0.

```if:coffeescript,javascript,php,python,ruby,typescript
**Note**: your function should have a default parameter.
```

```c#
Kata.HowManyLightsabersDoYouOwn("Adam") == 0
Kata.HowManyLightsabersDoYouOwn("Zach") == 18
```
```python
how_many_light_sabers_do_you_own('Zach') == 18
how_many_light_sabers_do_you_own('Adam') == 0
how_many_light_sabers_do_you_own()       == 0
```

def how_many_light_sabers_do_you_own(name="null"):
    try:
        if name=="Zach":
            return 18
        else:
            return 0
    except TypeError:
        return 0


Solve in Python:
Integral numbers can be even or odd.

Even numbers satisfy `n = 2m` ( with `m` also integral ) and we will ( completely arbitrarily ) think of odd numbers as `n = 2m + 1`.
Now, some odd numbers can be more odd than others: when for some `n`, `m` is more odd than for another's. Recursively. :]
Even numbers are just not odd.

# Task

Given a finite list of integral ( not necessarily non-negative ) numbers, determine the number that is _odder than the rest_.
If there is no single such number, no number is odder than the rest; return `Nothing`, `null` or a similar empty value.

# Examples

```python
oddest([1,2]) => 1
oddest([1,3]) => 3
oddest([1,5]) => None
```

# Hint

Do you _really_ want one? Point or tap here.

def oddest(a):
    if all(n % 2 == 0 for n in a):
        return a[0] if len(a) == 1 else None
    if -1 in a:
        return -1 if a.count(-1) == 1 else None
    a = [(x, x) for x in a if x % 2 != 0]
    while True:
        if len(a) == 0:
            return None
        if len(a) == 1:
            return a[0][0]
        a = list(filter(lambda n: n[1] % 2 != 0, ((n[0], (n[1] - 1) // 2 if n[1] != -1 else 1) for n in a)))


Solve in Python:
Introduction

It's been more than 20 minutes since the negligent waiter has taken your order for the house special prime tofu steak with a side of chili fries.

Out of boredom, you start fiddling around with the condiments tray. To be efficient, you want to be familiar with the choice of sauces and spices before your order is finally served.

You also examine the toothpick holder and try to analyze its inner workings when - yikes - the holder's lid falls off and all 23 picks lay scattered on the table.

Being a good and hygiene oriented citizen, you decide not to just put them back in the holder. Instead of letting all the good wood go to waste, you start playing around with the picks.

In the first "round", you lay down one toothpick vertically. You've used a total of one toothpick.

In the second "round", at each end of the first toothpick, you add a perpendicular toothpick at its center point. You added two additional toothpicks for a total of three toothpicks.

In the next rounds, you continue to add perpendicular toothpicks to each free end of toothpicks already on the table.

With your 23 toothpicks, you can complete a total of six rounds:

You wonder if you'd be able to implement this sequence in your favorite programming language. Because your food still hasn't arrived, you decide to take out your laptop and start implementing...

Challenge
Implement a script that returns the amount of toothpicks needed to complete n amount of rounds of the toothpick sequence.

```
0 <= n <= 5000
```

Hint
You can attempt this brute force or get some inspiration from the math department.

from math import floor, log

"""
See: https://oeis.org/A139250
Formulas:
  Let n = msb(n) + j where msb(n) = A053644(n)
  let a(0) = 0.
  Then a(n) = (2 * msb(n)^2 + 1) / 3 + 2 * a(j) + a(j + 1) - 1
    - David A. Corneth, Mar 26 2015

Note: A053644(n) is the sequence of largest power of 2 <= n
See: https://oeis.org/A053644
"""

def toothpick(n):
    """Returns number of picks required for n rounds of the toothpick sequence"""
    if n < 2:
        return n

    msb_n = 2 ** floor(log(n, 2))
    j = n - msb_n
    return (2 * msb_n ** 2 + 1) / 3 + 2 * toothpick(j) + toothpick(j + 1) - 1


Solve in Python:
Introduction
Brainfuck is one of the most well-known esoteric programming languages. But it can be hard to understand any code longer that 5 characters. In this kata you have to solve that problem.

Description

In this kata you have to write a function which will do 3 tasks:

Optimize the given Brainfuck code.
Check it for mistakes.
Translate the given Brainfuck programming code into C programming code.

More formally about each of the tasks:

Your function has to remove from the source code all useless command sequences such as: '+-', '<>', '[]'. Also it must erase all characters except +-<>,.[].
Example:
"++--+." -> "+."
"[][+++]" -> "[+++]"
"<>><" -> ""

If the source code contains unpaired braces, your function should return "Error!" string.

Your function must generate a string of the C programming code as follows:

Sequences of the X commands + or - must be replaced by \*p += X;\n or \*p -= X;\n.
Example:
"++++++++++" -> "\*p += 10;\n"
"------" -> "\*p -= 6;\n"

Sequences of the Y commands > or < must be replaced by p += Y;\n or p -= Y;\n.
Example:
">>>>>>>>>>" -> "p += 10;\n"
"<<<<<<" -> "p -= 6;\n"

. command must be replaced by putchar(\*p);\n.
Example:
".." -> "putchar(\*p);\nputchar(\*p);\n"

, command must be replaced by \*p = getchar();\n.
Example:
"," -> "\*p = getchar();\n"

[ command must be replaced by if (\*p) do {\n. ] command must be replaced by } while (\*p);\n.
Example:
"[>>]" ->
if (\*p) do {\n
  p += 2;\n
} while (\*p);\n

Each command in the code block must be shifted 2 spaces to the right accordingly to the previous code block.
Example:
"[>>[<<]]" ->
if (\*p) do {\n
  p += 2;\n
  if (\*p) do {\n
    p -= 2;\n
  } while (\*p);\n
} while (\*p);\n

Examples

Input:
+++++[>++++.<-]
Output:
*p += 5;
if (*p) do {
  p += 1;
  *p += 4;
  putchar(*p);
  p -= 1;
  *p -= 1;
} while (*p);

import re

def brainfuck_to_c(source):
    # remove comments
    source = re.sub('[^+-<>,.\[\]]', '', source)

    # remove redundant code
    before = ''
    while source != before:
        before = source
        source = re.sub('\+-|-\+|<>|><|\[\]', '', source)

    # check braces status
    braces = re.sub('[^\[\]]', '', source)
    while braces.count('[]'):
        braces = braces.replace('[]', '')
    if braces:
        return 'Error!'

    # split code into commands
    commands = re.findall('\++|-+|>+|<+|[.,\[\]]', source)

    # translate to C
    output = []
    indent = 0
    for cmd in commands:
        if cmd[0] in '+-<>':
            line = ('%sp %s= %s;\n' %
                ('*' if cmd[0] in '+-' else '',
                 '+' if cmd[0] in '+>' else '-',
                 len(cmd)))
        elif cmd == '.':
            line = 'putchar(*p);\n'
        elif cmd == ',':
            line = '*p = getchar();\n'
        elif cmd == '[':
            line = 'if (*p) do {\n'
        elif cmd == ']':
            line = '} while (*p);\n'
            indent -= 1
        output.append('  ' * indent + line)
        if cmd == '[':
            indent += 1

    return ''.join(output)


Solve in Python:
Introduction

Mr. Safety loves numeric locks and his Nokia 3310. He locked almost everything in his house. He is so smart and he doesn't need to remember the combinations. He has an algorithm to generate new passcodes on his Nokia cell phone.

 Task

Can you crack his numeric locks? Mr. Safety's treasures wait for you. Write an algorithm to open his numeric locks. Can you do it without his Nokia 3310?

Input

The `str` or `message` (Python) input string consists of lowercase and upercase characters. It's a real object that you want to unlock.

Output
Return a string that only consists of digits.

Example
```
unlock("Nokia")  // => 66542
unlock("Valut")  // => 82588
unlock("toilet") // => 864538
```

table = str.maketrans("abcdefghijklmnopqrstuvwxyz", "22233344455566677778889999")

def unlock(message):
    return message.lower().translate(table)


Solve in Python:
Introduction

The GADERYPOLUKI is a simple substitution cypher used in scouting to encrypt messages. The encryption is based on short, easy to remember key. The key is written as paired letters, which are in the cipher simple replacement.

The most frequently used key is "GA-DE-RY-PO-LU-KI".

```
 G => A
 g => a
 a => g
 A => G
 D => E
  etc.
```

The letters, which are not on the list of substitutes, stays in the encrypted text without changes.

Other keys often used by Scouts:

```
PO-LI-TY-KA-RE-NU
KA-CE-MI-NU-TO-WY
KO-NI-EC-MA-TU-RY
ZA-RE-WY-BU-HO-KI
BA-WO-LE-TY-KI-JU
RE-GU-LA-MI-NO-WY
```

Task

Your task is to help scouts to encrypt and decrypt thier messages.
Write the `Encode` and `Decode` functions.

Input/Output

The function should have two parameters.
The `message` input string consists of lowercase and uperrcase characters and whitespace character.
The `key` input string consists of only lowercase characters.
The substitution has to be case-sensitive.

Example

 # GADERYPOLUKI collection

GADERYPOLUKI cypher vol 1

GADERYPOLUKI cypher vol 2

GADERYPOLUKI cypher vol 3 - Missing Key

GADERYPOLUKI cypher vol 4 - Missing key madness

def encode(str, key):
    key = key.lower() + key.upper()
    dict = { char: key[i-1] if i % 2 else key[i+1] for i, char in enumerate(key) }
    return ''.join( dict.get(char, char) for char in str )

decode = encode


Solve in Python:
Introduction

The GADERYPOLUKI is a simple substitution cypher used in scouting to encrypt messages. The encryption is based on short, easy to remember key. The key is written as paired letters, which are in the cipher simple replacement.

The most frequently used key is "GA-DE-RY-PO-LU-KI".

```
 G => A
 g => a
 a => g
 A => G
 D => E
  etc.
```

The letters, which are not on the list of substitutes, stays in the encrypted text without changes.

Task

Your task is to help scouts to encrypt and decrypt thier messages.
Write the `Encode` and `Decode` functions.

Input/Output

The input string consists of lowercase and uperrcase characters and white .
The substitution has to be case-sensitive.

Example

# GADERYPOLUKI collection

GADERYPOLUKI cypher vol 1

GADERYPOLUKI cypher vol 2

GADERYPOLUKI cypher vol 3 - Missing Key

GADERYPOLUKI cypher vol 4 - Missing key madness

encode = decode = lambda str: str.translate(str.maketrans('gaderypolukiGADERYPOLUKI', 'agedyropulikAGEDYROPULIK'))


Solve in Python:
Introduction to Disjunctions
In logic and mathematics, a disjunction is an operation on 2 or more propositions.  A disjunction is true if and only if 1 or more of its operands is true.  In programming, we typically denote a disjunction using "||", but in logic we typically use "v".
Example of disjunction:
p = 1 > 2 = false
q = 2 < 3 = true
therefore p v q is true
In a programming language, we might write this as:
var p = 1 > 2;        // false
var q = 2 < 3;        // true
var result = p || q;  // true
The above example demonstrates an inclusive disjunction (meaning it includes cases where both operands are true). Disjunctions can also be exlusive. An exclusive disjunction is typically represented by "⊻" and is true if and only if both operands have opposite values.
p = 1 < 2 = true
q = 2 < 3 = true
therefore p ⊻ q is false
This can become confusing when dealing with more than 2 operands.
r = 3 < 4 = true
p ⊻ q ⊻ r = ???
We handle these situations by evaluating the expression from left to right.
p ⊻ q = false
(p ⊻ q) ⊻ r = true
Directions:
For this kata, your task is to implement a function that performs a disjunction operation on 2 or more propositions.

Should take a boolean array as its first parameter and a single boolean as its second parameter, which, if true, should indicate that the disjunction should be exclusive as opposed to inclusive.
Should return true or false.

from functools import reduce

def disjunction(operands, is_exclusive):
    op = int.__xor__ if is_exclusive else int.__or__
    return reduce(op, operands)


Solve in Python:
Iroha has a sequence of N strings S_1, S_2, ..., S_N. The length of each string is L.
She will concatenate all of the strings in some order, to produce a long string.
Among all strings that she can produce in this way, find the lexicographically smallest one.
Here, a string s=s_1s_2s_3...s_n is lexicographically smaller than another string t=t_1t_2t_3...t_m if and only if one of the following holds:

 - There exists an index i(1≦i≦min(n,m)), such that s_j = t_j for all indices j(1≦j<i), and s_i<t_i.
 - s_i = t_i for all integers i(1≦i≦min(n,m)), and n<m.

-----Constraints-----
 - 1 ≦ N, L ≦ 100
 - For each i, the length of S_i equals L.
 - For each i, S_i consists of lowercase letters.

-----Input-----
The input is given from Standard Input in the following format:
N L
S_1
S_2
:
S_N

-----Output-----
Print the lexicographically smallest string that Iroha can produce.

-----Sample Input-----
3 3
dxx
axx
cxx

-----Sample Output-----
axxcxxdxx

The following order should be used: axx, cxx, dxx.

n, l = map(int, input().split())
sl = list(input() for _ in range(n))
sl_s = sorted(sl)

print(*sl_s, sep='')


Solve in Python:
Is every value in the array an array?

This should only test the second array dimension of the array. The values of the nested arrays don't have to be arrays.

Examples:

```python
[[1],[2]] => true
['1','2'] => false
[{1:1},{2:2}] => false
```

def arr_check(arr):
    return sum([isinstance(x, list) for x in arr]) == len(arr)


Solve in Python:
Is the number even?

If the numbers is even return `true`. If it's odd, return `false`.

Oh yeah... the following symbols/commands have been disabled!

 use of ```%```
 use of ```.even?``` in Ruby
 use of ```mod``` in Python


Solve in Python:
Ishank lives in a country in which there are N$N$ cities and N−1$N-1$ roads. All the cities are connected via these roads. Each city has been assigned a unique number from 1 to N$N$. The country can be assumed as a tree, with nodes representing the cities and edges representing the roads. The tree is rooted at 1.Every Time, when a traveler through a road, he will either gain some amount or has to pay some amount.
Abhineet is a traveler and wishes to travel to various cities in this country. There's a law in the country for travelers, according to which, when a traveler moves from the city A$A$ to city B$B$, where city A$A$ and B$B$ are connected by a road then the traveler is either paid or has to pay the amount of money equal to profit or loss respectively. When he moves from A$A$ to B$B$, he hires a special kind of vehicle which can reverse its direction at most once. Reversing the direction means earlier the vehicle is going towards the root, then away from the root or vice versa. Abhineet is analyzing his trip and therefore gave Q$Q$ queries to his friend, Ishank, a great coder. In every query, he gives two cities A$A$ and B$B$. Ishank has to calculate the maximum amount he can gain (if he cannot gain, then the minimum amount he will lose) if he goes from the city A$A$ to city B$B$.

-----Input:-----
-The first line of the input contains a two space-separated integers N and Q.
-The next N-1 line contains 3 space-separated integers Xi and Yi and Zi denoting that cities Xi and Yi are connected by a road which gives profit Zi (Negative Zi represents loss).
-The next Q contains 2 space-separated integers A and B denoting two cities.

-----Output:-----
Print a single line corresponding to each query — the maximum amount he can gain (if he cannot gain, then the minimum amount he will lose with negative sign) if he goes from city A to city B.

-----Constraints-----
- 2≤N≤105$2 \leq N \leq 10^5$
- 1≤Q≤105$1 \leq Q \leq 10^5$
- 1≤Xi,Yi,A,B≤N$1 \leq Xi, Yi, A, B \leq N$
- abs(Zi)≤109$ abs(Zi) \leq...

# cook your dish here
# cook your dish here
try:
    X=list(map(int, input().split()))
except:
    X=[0,0]
ch=[]
chnew=[]
par={}
par[1]=0
for i in range(X[0]+1):
    ch.append([])
    chnew.append([])
for i in range(X[0]-1):
    Y=list(map(int, input().split()))
    #par[Y[1]]=[Y[0],Y[2]]
    ch[Y[0]].append([Y[1],Y[2]])
    ch[Y[1]].append([Y[0],Y[2]])
tre=[1]
while(len(tre)):
    cr=tre[-1]
    tre=tre[:-1]
    for i in ch[cr]:
        chnew[cr].append(i)
        par[i[0]]=[cr,i[1]]
        tre.append(i[0])
        for j in ch[i[0]]:
            if(j[0]==cr):
                ch[i[0]].remove(j)
                break
ch=chnew
def goup(par,nd):
    if(nd==1):
        return 0
    else:
        p=par[nd]
        ans=p[1]+goup(par,p[0])
        return (max([ans,0]))

def godown(ch,nd):
    ans=0
    for i in ch[nd]:
        ans=max([(i[1]+godown(ch,i[0])),ans])
    return(ans)

for i in range(X[1]):
    Z=list(map(int,input().split()))
    r=Z[0]
    s=Z[1]
    nans=0
    while(r!=s):
        if(r>s):
            nans=nans+par[r][1]
            r=par[r][0]
        else:
            nans=nans+par[s][1]
            s=par[s][0]
    if((r==Z[0]) or (r==Z[1])):
        if(Z[0]<Z[1]):
            nans=nans+2*max(goup(par,Z[0]),godown(ch,Z[1]))
        else:
            nans=nans+2*max(goup(par,Z[1]),godown(ch,Z[0]))
    else:
        nans=nans+2*goup(par,r)
    print(nans)


Solve in Python:
Istiak is learning about arithmetic progressions. Today, he wrote an arithmetic sequence on a piece of paper. Istiak was very happy that he managed to write an arithmetic sequence and went out for lunch.
Istiak's friend Rafsan likes to irritate him by playing silly pranks on him. This time, he could have chosen one element of Istiak's sequence and changed it. When Istiak came back, he was devastated to see his sequence ruined — it became a sequence $a_1, a_2, \ldots, a_N$ (possibly identical to the original sequence, if Rafsan did not change anything, in which case Istiak is just overreacting). Help him recover the original sequence.
Formally, you have to find an arithmetic sequence $b_1, b_2, \ldots, b_N$ which differs from $a$ in at most one position. $b$ is said to be an arithmetic sequence if there is a real number $d$ such that $b_i - b_{i-1} = d$ for each $i$ ($2 \le i \le N$). If there are multiple valid solutions, you may find any one.

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

-----Output-----
For each test case, print a single line containing $N$ space-separated integers $b_1, b_2, \ldots, b_N$. It is guaranteed that a valid solution exists.

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

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

-----Example Output-----
1 3 5 7
-10 -5 0 5 10
2 2 2 2

-----Explanation-----
Example case 1: Rafsan changed the third element from $5$ to $10$.
Example case 2: No elements were changed.
Example case 3: Rafsan changed the fourth element from $2$ to $10$.

# cook your dish here
test_cases = int(input())
for i in range(test_cases):
 no_of_elements = int(input())
 sequence = list(map(int, input().split()))
 d1 = sequence[1] - sequence[0]
 d2 = sequence[2] - sequence[1]
 d3 = (sequence[3] - sequence[0])/3
 d4 = (sequence[3] - sequence[1])/2
 d5 = (sequence[2] - sequence[0])/2

 if (d2 == d4):
  d = d2

 elif(d3 == d5):
  d = d3

 elif(d1 == d3):
  d = d1

 elif(d1 == d5):
  d = d1

 if (d == d1):
  for i in range(no_of_elements):
   sequence[i] = int(sequence[0] + i*d)
 else:
  for i in range(no_of_elements):
   sequence[i] = int(sequence[-1] - ((no_of_elements - i - 1)*d))

 for i in sequence:
  print(i, end=" ")

 print('\n')


Solve in Python:
It is 2050 and romance has long gone, relationships exist solely for practicality.

MatchMyHusband is a website that matches busy working women with perfect house husbands. You have been employed by MatchMyHusband to write a function that determines who matches!!

The rules are... a match occurs providing the husband's "usefulness" rating is greater than or equal to the woman's "needs".

The husband's "usefulness" is the SUM of his cooking, cleaning and childcare abilities and takes the form of an array .

usefulness example --> [15, 26, 19]    (15 + 26 + 19) = 60

Every woman that signs up, begins with a "needs" rating of 100. However, it's realised that the longer women wait for their husbands, the more dissatisfied they become with our service. They also become less picky, therefore their needs are subject to exponential decay of 15% per month. https://en.wikipedia.org/wiki/Exponential_decay

Given the number of months since sign up, write a function that returns "Match!" if the husband is useful enough, or "No match!" if he's not.

def match(usefulness, months):
    match = sum(usefulness) >= 100 * 0.85 ** months
    return 'Match!' if match else 'No match!'


Solve in Python:
It is Borya's eleventh birthday, and he has got a great present: n cards with numbers. The i-th card has the number a_{i} written on it. Borya wants to put his cards in a row to get one greater number. For example, if Borya has cards with numbers 1, 31, and 12, and he puts them in a row in this order, he would get a number 13112.

He is only 11, but he already knows that there are n! ways to put his cards in a row. But today is a special day, so he is only interested in such ways that the resulting big number is divisible by eleven. So, the way from the previous paragraph is good, because 13112 = 1192 × 11, but if he puts the cards in the following order: 31, 1, 12, he would get a number 31112, it is not divisible by 11, so this way is not good for Borya. Help Borya to find out how many good ways to put the cards are there.

Borya considers all cards different, even if some of them contain the same number. For example, if Borya has two cards with 1 on it, there are two good ways.

Help Borya, find the number of good ways to put the cards. This number can be large, so output it modulo 998244353.

-----Input-----

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

Each test is described by two lines.

The first line contains an integer n (1 ≤ n ≤ 2000) — the number of cards in Borya's present.

The second line contains n integers a_{i} (1 ≤ a_{i} ≤ 10^9) — numbers written on the cards.

It is guaranteed that the total number of cards in all tests of one input data doesn't exceed 2000.

-----Output-----

For each test case output one line: the number of ways to put the cards to the table so that the resulting big number was divisible by 11, print the number modulo 998244353.

-----Example-----
Input
4
2
1 1
3
1 31 12
3
12345 67 84
9
1 2 3 4 5 6 7 8 9

Output
2
2
2
31680

mod = 998244353
f0 = [ [0 for i in range(11)] for j in range(2010) ]
f1 = [ [0 for i in range(11)] for j in range(2010) ]
fac = [0 for i in range(2010)]
tab = [0 for i in range(11)]
C = [ [0 for i in range(2010)] for j in range(2010) ]

def Init() :
    fac[0] = 1
    for i in range(2010) :
        if i > 0 : fac[i] = fac[i - 1] * i % mod
        C[i][0] = 1
        for j in range(1, 2010) :
            C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) % mod

def len(x) :
    res = 0
    while x > 0 :
        res += 1
        x = x // 10
    return res

def solve() :
    n = int(input())
    f0[0][0] = f1[0][0] = 1
    a = list(map(int, input().split()))
    c0, c1 = 0, 0
    s0, s1 = 0, 0
    for nu in a :
        m = nu % 11
        if len(nu) & 1 :
            c1 += 1
            s1 += m
            for i in range(11) :
                f1[c1][i] = 0
            for i in range(c1 - 1, -1, -1) :
                for j in range(11) :
                    if f1[i][j] == 0 : continue
                    f1[i + 1][(j + m) % 11] += f1[i][j]
                    f1[i + 1][(j + m) % 11] %= mod
        else :
            c0 += 1
            s0 += m
            for i in range(11) :
                f0[c0][i] = 0
            for i in range(c0 - 1, -1, -1) :
                for j in range(11) :
                    if f0[i][j] == 0 : continue
                    f0[i + 1][(j + m) % 11] += f0[i][j]
                    f0[i + 1][(j + m) % 11] %= mod
    s1 %= 11
    s0 %= 11
    part = c1 // 2
    for i in range(11) :
        tab[i] = 0
    for i in range(11) :
        tab[(i + i + 11 - s1) % 11] = f1[c1 - part][i]
    for i in range(11) :
        tab[i] = tab[i] * fac[part] % mod * fac[c1 - part] % mod

    ans = 0
    if c1 == 0 :
        ans = f0[c0][0] * fac[c0]
    elif c0 == 0 :
        ans = tab[0]
    else :
        for i in range(c0 + 1) :
            for j in range(11) :
                if f0[i][j] == 0 : continue
                # print(f0[i][j], tab[(j + j + 11 - s0) % 11] \
                # , fac[i] % mod *...


Solve in Python:
It is a well-known fact that behind every good comet is a UFO. These UFOs often come to collect loyal supporters from here on Earth. Unfortunately, they only have room to pick up one group of followers on each trip. They do, however, let the groups know ahead of time which will be picked up for each comet by a clever scheme: they pick a name for the comet which, along with the name of the group, can be used to determine if it is a particular group's turn to go (who do you think names the comets?). The details of the matching scheme are given below; your job is to write a program which takes the names of a group and a comet and then determines whether the group should go with the UFO behind that comet.

Both the name of the group and the name of the comet are converted into a number in the following manner: the final number is just the product of all the letters in the name, where "A" is 1 and "Z" is 26. For instance, the group "USACO" would be `21 * 19 * 1 * 3 * 15` = 17955. If the group's number mod 47 is the same as the comet's number mod 47, then you need to tell the group to get ready! (Remember that "a mod b" is the remainder left over after dividing a by b; 34 mod 10 is 4.)

Write a program which reads in the name of the comet and the name of the group and figures out whether according to the above scheme the names are a match, printing "GO" if they match and "STAY" if not. The names of the groups and the comets will be a string of capital letters with no spaces or punctuation, up to 6 characters long.

Example:

Converting the letters to numbers:
```
C  O   M   E  T   Q
3  15  13  5  20  17

H  V   N   G  A  T
8  22  14  7  1  20
```
then calculate the product mod 47:
```
3 * 15 * 13 * 5 * 20 * 17 = 994500 mod 47 = 27
8 * 22 * 14 * 7 *  1 * 20 = 344960 mod 47 = 27
```
Because both products evaluate to 27 (when modded by 47), the mission is 'GO'.

def ride(group,comet):
    n1 = 1
    n2 = 1
    for x in group:
        n1 *= ord(x.lower()) - 96
    for x in comet:
        n2 *= ord(x.lower()) - 96
    if n1 % 47 == n2 % 47:
        return "GO"
    else:
        return "STAY"


Solve in Python:
It is an interesting exercise to write a program to print out all permutations of $1, 2, …, n$. However, since there are $6227020800$ permutations of $1, 2, …, 13$, it is unlikely that we would ever run this program on an input of size more than $10$.
However, here is another interesting problem whose solution can also be used to generate permutations. We can order the permutations of $1, 2, …, n$ under the lexicographic (or dictionary) order. Here are the permutations of $1,2,3$ in lexicographic order:
123132213231312321123132213231312321 1 \, 2 \, 3 \quad    1 \, 3 \, 2 \quad     2 \, 1 \, 3 \quad     2 \, 3 \, 1 \quad     3 \, 1 \, 2 \quad     3 \, 2 \, 1
The problem we have is the following: given a permutation of $1,2, …, n$, generate the next permutation in lexicographic order. For example, for $2 3 1 4$ the answer is $2 3 4 1$.

-----Input:-----
The first line of the input contains two integers, $N$ and $K$. This is followed by $K$ lines, each of which contains one permutation of $1, 2,…,N$.

-----Output:-----
The output should consist of $K$ lines. Line $i$ should contain the lexicographically next permutation correponding to the permutation on line $i+1$ in the input.

-----Constraints:-----
- $1 \leq N \leq 1000$.
- $1 \leq K \leq 10$.

-----Sample input-----
3 2
3 1 2
2 3 1

-----Sample output-----
3 2 1
3 1 2

n, k=map(int, input().split())
for i in range(k):
    arr=list(map(int, input().split()))
    res=[]

    for i in range(len(arr)-1, 0, -1):
        if(arr[i]>arr[i-1]):
            res.append(arr[i-1])
            res.append(arr[i])
            temp=arr[i-1]
            break
        else:
            res.append(arr[i])

    res.sort()
    for j in range(len(res)):
        if(res[j]>temp):
            arr[i-1]=res[j]
            res.remove(res[j])
            break

    for j in range(len(res)):
        arr[i]=res[j]
        i+=1

    print(*arr)


Solve in Python:
It is known that there are k fish species in the polar ocean, numbered from 1 to k. They are sorted by non-decreasing order of their weight, which is a positive number. Let the weight of the i-th type of fish be w_{i}, then 0 < w_1 ≤ w_2 ≤ ... ≤ w_{k} holds.

Polar bears Alice and Bob each have caught some fish, and they are guessing who has the larger sum of weight of the fish he/she's caught. Given the type of the fish they've caught, determine whether it is possible that the fish caught by Alice has a strictly larger total weight than Bob's. In other words, does there exist a sequence of weights w_{i} (not necessary integers), such that the fish caught by Alice has a strictly larger total weight?

-----Input-----

The first line contains three integers n, m, k (1 ≤ n, m ≤ 10^5, 1 ≤ k ≤ 10^9) — the number of fish caught by Alice and Bob respectively, and the number of fish species.

The second line contains n integers each from 1 to k, the list of fish type caught by Alice. The third line contains m integers each from 1 to k, the list of fish type caught by Bob.

Note that one may have caught more than one fish for a same species.

-----Output-----

Output "YES" (without quotes) if it is possible, and "NO" (without quotes) otherwise.

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

Output
YES

Input
4 7 9
5 2 7 3
3 5 2 7 3 8 7

Output
NO

-----Note-----

In the first sample, if w_1 = 1, w_2 = 2, w_3 = 2.5,  then Alice has a total of 2 + 2 + 2 = 6 weight units, while Bob only has 1 + 1 + 2.5 = 4.5.

In the second sample, the fish that Alice caught is a subset of Bob's. Therefore, the total weight of Bob’s fish is always not less than the total weight of Alice’s fish.

n, m, k = [int(x) for x in input().split()]
alice = [int(x) for x in input().split()]
bob = [int(x) for x in input().split()]

alice.sort()
bob.sort()

balance = 0
i = n - 1
j = m - 1

while i >= 0 and j >= 0:
    if alice[i] > bob[j]:
        balance += 1
        i -= 1
    elif alice[i] < bob[j]:
        balance -= 1
        j -= 1
    else:
        i -= 1
        j -= 1
    if balance > 0:
        break

if i + 1 + balance > 0:
    print('YES')
else:
    print('NO')


Solve in Python:
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.

Marmot brought Mole n ordered piles of worms such that i-th pile contains a_{i} worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a_1, worms in second pile are labeled with numbers a_1 + 1 to a_1 + a_2 and so on. See the example for a better understanding.

Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.

Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 10^5), the number of piles.

The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^3, a_1 + a_2 + ... + a_{n} ≤ 10^6), where a_{i} is the number of worms in the i-th pile.

The third line contains single integer m (1 ≤ m ≤ 10^5), the number of juicy worms said by Marmot.

The fourth line contains m integers q_1, q_2, ..., q_{m} (1 ≤ q_{i} ≤ a_1 + a_2 + ... + a_{n}), the labels of the juicy worms.

-----Output-----

Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number q_{i} is.

-----Examples-----
Input
5
2 7 3 4 9
3
1 25 11

Output
1
5
3

-----Note-----

For the sample input:

  The worms with labels from [1, 2] are in the first pile.  The worms with labels from [3, 9] are in the second pile.  The worms with labels from [10, 12] are in the third pile.  The worms with labels from [13, 16] are in the fourth pile.  The worms with labels from [17, 25] are in the fifth pile.

from sys import stdin
from bisect import bisect_left

def main():
    stdin.readline()
    x, a = 0, []
    for y in map(int, stdin.readline().split()):
        x += y
        a.append(x)

    stdin.readline()
    for x in map(int, stdin.readline().split()):
        print(bisect_left(a, x) + 1)

main()


Solve in Python:
It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one).

If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.

-----Input-----

The first line contains an integer n (2 ≤ n ≤ 100) — the initial number of elements in the set. The second line contains n distinct space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — the elements of the set.

-----Output-----

Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes).

-----Examples-----
Input
2
2 3

Output
Alice

Input
2
5 3

Output
Alice

Input
3
5 6 7

Output
Bob

-----Note-----

Consider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice.

# coding = utf-8
from functools import reduce
div = 1000000007
s = input()
n = int(s)
s = input()
num = list([int(x) for x in s.split(" ")])

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

g = reduce(gcd,num)
m = max(num)

now = m/g
remain = now - len(num)
if remain%2==0:
	print("Bob")
else:
	print("Alice")


Solve in Python:
It is the end of 2019 — the 17th of November, the Cooking Challenge day.
There are N$N$ players participating in this competition, numbered 1$1$ through N$N$. Initially, the skill level of each player is zero. There are also M$M$ challenges (numbered 1$1$ through M$M$). For each valid i$i$, the i$i$-th challenge has three parameters Li$L_i$, Ri$R_i$ and Xi$X_i$ with the following meaning: for each player between the Li$L_i$-th and Ri$R_i$-th inclusive, if this player participates in this challenge, their skill level increases by Xi$X_i$ (Xi$X_i$ does not have to be positive).
The organizers of the Cooking Challenge decided that the contest would be boring if they let the participants participate in the challenges directly, so they decided to use the compos.
There are Q$Q$ compos (numbered 1$1$ through Q$Q$). For each valid i$i$, the i$i$-th compo has two parameters Ai$A_i$ and Bi$B_i$, which means that it includes the challenges Ai,Ai+1,…,Bi$A_i, A_i+1, \ldots, B_i$.
Each participant has to select a subset of the compos (possibly empty or the set of all Q$Q$ compos) and participate in all challenges those compos include. A participant may not select the same compo twice, but may participate in the same challenge more than once if it is included in multiple chosen compos.
For each player, find the maximum skill level this player can reach if the compos are chosen optimally.

-----Input-----
- The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows.
- The first line of each test case contains three space-separated integers N$N$, M$M$ and Q$Q$.
- M$M$ lines follow. For each valid i$i$, the i$i$-th of these lines contains three space-separated integers Li$L_i$, Ri$R_i$ and Xi$X_i$.
- Q$Q$ more lines follow. For each valid i$i$, the i$i$-th of these lines contains two space-separated integers Ai$A_i$ and Bi$B_i$.

-----Output-----
For each test case, print a single line containing N$N$ space-separated integers. For each valid i$i$,...

# cook your dish here
import numpy as np

def sort_it(array):
    new_list = []
    for i in range(len(array)):
        start = 0
        value = array[i][0]
        last = len(new_list)
        while start != last:
            mid = (start + last) // 2
            if new_list[mid][0] > value:
                last = mid
            else:
                start = mid+1
        new_list.insert(start,array[i])
    return new_list

tests = int(input())
for _ in range(tests):
    n, m, q = [int(j) for j in input().split()]
    challenges = [[0] * 3 for _ in range(m)]
    combos = [[0] * 2 for _ in range(q)]
    for i in range(m):
        challenges[i] = [int(j) for j in input().split()]
    for i in range(q):
        combos[i] = [int(j) for j in input().split()]

    sorted_chalenges = np.zeros((2 * m, 3),dtype=np.intc)
    for i in range(m):
        sorted_chalenges[2*i] = [challenges[i][0]-1,challenges[i][2],i]
        sorted_chalenges[2*i+1] = [challenges[i][1],-challenges[i][2],i]
    sorted_chalenges = np.array(sort_it(sorted_chalenges))
    types_of_players = np.zeros((m + 1, 2 * m + 1),dtype=np.intc)
    player_type = np.zeros(n,dtype=np.intc)
    last_player = 0
    for i in range(2 * m):
        start, value, chal = sorted_chalenges[i]
        types_of_players[chal+1:,i+1:] += value
        player_type[last_player:start] = i
        last_player = start
    player_type[last_player:] = 2 * m

    combo_types = np.zeros((q, 2 * m + 1),dtype = np.intc)
    for i in range(q):
        first, last = combos[i]
        r, p = [types_of_players[first - 1], types_of_players[last]]
        combo_types[i] = np.maximum(p-r,0)
    output = np.sum(combo_types,axis=0)[player_type]
    for i in range(n):
        print(output[i], end = " ")
    print("")


Solve in Python:
It is well-known that the elephants are afraid of mouses. The Little Elephant from the Zoo of Lviv is not an exception.

The Little Elephant is on a board A of n rows and m columns (0-based numeration). At the beginning he is in cell with coordinates (0; 0) and he wants to go to cell with coordinates (n-1; m-1). From cell (x; y) Little Elephant can go either to (x+1; y) or (x; y+1).

Each cell of the board contains either 1 or 0. If A[i][j] = 1, then there is a single mouse in cell (i; j). Mouse at cell (i; j) scared Little Elephants if and only if during the path there was at least one such cell (x; y) (which belongs to that path) and |i-x| + |j-y| <= 1.

Little Elephant wants to find some correct path from (0; 0) to (n-1; m-1) such that the number of mouses that have scared the Little Elephant is minimal possible. Print that number.

-----Input-----
First line contains single integer T - the number of test cases. Then T test cases follow. First line of each test case contain pair of integers n and m - the size of the board. Next n lines contain n strings, each of size m and consisted of digits 0 and 1.

-----Output-----
In T lines print T integer - the answers for the corresponding test.

-----Constraints-----
1 <= T <= 50
2 <= n, m <= 100

-----Example-----
Input:
2
3 9
001000001
111111010
100100100
7 9
010101110
110110111
010011111
100100000
000010100
011011000
000100101

Output:
9
10

-----Explanation-----
Example case 1:
The optimized path is: (0, 0) -> (0, 1) -> (0, 2) -> (0, 3) -> (0, 4) -> (0, 5) -> (0, 6) -> (0, 7) -> (0, 8) -> (1, 8) -> (2, 8). The mouses that scared the Little Elephant are at the following cells: (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 7), (0, 2), (0, 8).

Example case 2:
The optimized path is: (0, 0) -> (1, 0) -> (1, 1) -> (2, 1) -> (2, 2) -> (3, 2) -> (3, 3) -> (4, 3) -> (4, 4) -> (5, 4) -> (5, 5) -> (6, 5) -> (6, 6) -> (6, 7) -> (6, 8). The 10 mouses that scared the Little Elephant are at the following cells: (0, 1), (1, 0), (1, 1), (2, 1), (3, 3), (4, 4), (5, 4),...

from collections import defaultdict
from itertools import product
def solve(mouse,n,m):
 shadow=[[0 for i in range(m)]for j in range(n)]
 for i,j in product(list(range(n)),list(range(m))):
  if mouse[i][j]==1:
   if i>0:
    shadow[i-1][j]+=1
   if j>0:
    shadow[i][j-1]+=1
   if i<n-1:
    shadow[i+1][j]+=1
   if j<m-1:
    shadow[i][j+1]+=1

 dp=defaultdict(int)
 dp[(0,0,0)]=dp[(0,0,1)]=shadow[0][0]-mouse[0][0]

 for i in range(1,m):
  dp[(0,i,0)]=dp[(0,i,1)]=shadow[0][i]-mouse[0][i]+dp[(0,i-1,0)]

 for i in range(1,n):
  dp[(i,0,0)]=dp[(i,0,1)]=shadow[i][0]-mouse[i][0]+dp[(i-1,0,1)]

 for i,j in product(list(range(1,n)),list(range(1,m))):
  a=shadow[i][j]-mouse[i][j]
  b=a
  a+=min(dp[(i,j-1,0)],dp[(i,j-1,1)]-mouse[i-1][j])
  b+=min(dp[(i-1,j,1)],dp[(i-1,j,0)]-mouse[i][j-1])
  dp[(i,j,0)]=a
  dp[(i,j,1)]=b

 return min(dp[(n-1,m-1,0)],dp[(n-1,m-1,1)])+mouse[0][0]+mouse[n-1][m-1]

for _ in range(int(input())):
 n,m=list(map(int,input().split( )))
 mouse=[]
 for i in range(n):
  x=input()
  mouse.append(list(map(int,x)))
 print(solve(mouse,n,m))


Solve in Python:
It started as a discussion with a friend, who didn't fully grasp some way of setting defaults, but I thought the idea was cool enough for a beginner kata: binary `OR` each matching element of two given arrays (or lists, if you do it in Python; vectors in c++) of integers and give the resulting ORed array [starts to sound like a tonguetwister, doesn't it?].

If one array is shorter than the other, use the optional third parametero (defaulted to `0`) to `OR` the unmatched elements.

For example:

```python
or_arrays([1,2,3],[1,2,3]) == [1,2,3]
or_arrays([1,2,3],[4,5,6]) == [5,7,7]
or_arrays([1,2,3],[1,2]) == [1,2,3]
or_arrays([1,2],[1,2,3]) == [1,2,3]
or_arrays([1,2,3],[1,2,3],3) == [1,2,3]
```

def or_arrays(arr1, arr2,n=0):
    res=[]
    i=0
    while i<len(arr1) and i<len(arr2):
        res.append(arr1[i] | arr2[i])
        i+=1
    while i<len(arr1):
        res.append(arr1[i] | n)
        i+=1
    while i<len(arr2):
        res.append(arr2[i] | n)
        i+=1
    return res


Solve in Python:
It's 3AM and you get the dreaded call from a customer: the program your company sold them is hanging. You eventually trace the problem down to a call to a function named `mystery`. Usually, `mystery` works fine and produces an integer result for an integer input. However, on certain inputs, the `mystery` function just locks up.

Unfortunately, the `mystery` function is part of a third-party library, and you don't have access to the source code. Uck. It may take a while to get support from the provider of the library, and in the meantime, your customer is getting frustrated.

Your mission, should you choose to accept it, is to create a new function called `wrap_mystery` that returns the same results as `mystery`, but does not hang. Since you're not sure exactly what values `mystery` should be returning for hangs, just have `wrap_mystery` return -1 for problematic input. Your customer is counting on you!

`wrap_mystery` will only be called with positive integers less than 1,000,000.

def mystery_solved(n):
    """
Recreated mystery function from bytecode using the dis module.
   How to print the bytecode: import dis
                              print(dis.dis(mystery))
    Apparently,
    the function is a wrong implementation of the 5n+1 problem ->
    https://math.stackexchange.com/questions/14569/the-5n1-problem
    http://www.sciencedirect.com/science/article/pii/S0304414905001602
    """
    c=0
    while(n != 1 and n != 13 and n < 1000000): # Should have "n != 17" too.
              c=c+1
              # Without the line below the function hangs for some n > 0.
              if(n==17): return -1
              if (n&1):
                     n=n+n+n+n+n+1 # n = 5n+1
                     continue
              n=n>>1 # n = n/2
    return c

def wrap_mystery(n): return mystery_solved(n)


Solve in Python:
It's Christmas time and Santa is in town. There are N children each having a bag with a mission to fill in as many toffees as possible. They are accompanied by a teacher whose ulterior motive is to test their counting skills. The toffees are of different brands (denoted by lowercase letters a-z). Santa picks up a child numbered m and gives n toffees of brand p to the child.

The teacher wishes to ask the children to calculate the number of toffees there are of a particular brand amongst a given range of children. Formally, there are 2 queries:

Input:

First line consists of Q queries.

Each line follows and consists of four space separated values:

Type 1: It is of the form 1 m x p

1 is the type no,"m" is the child to which "x" toffees of a brand "p" are given

Type 2: It is of the form 2 m n p
where m - n is the range of children (inclusive) being queried for brand p

Output:

Report the sum of toffees of brand p within the given range m - n for each query of type 2

Constraints:

1 <= Q <= 10^5

1 <= N <= 10^6

1 <= m <= n <= 10^6

1 <= x <= 10^6

all brand of toffees are lowercase letters

Subtask 1: (30 points)

1 <= Q <= 10^3

1 <= m <= n <= 10^3

1 <= x <= 10^3

Subtask 2: (70 points)

Original Constraints

Sample Input:

5

1 3 4 a

1 5 8 a

1 1 7 x

2 1 6 a

2 3 6 y

Sample Output:

12

0

In first case, there are two children between 3 and 5 between 0 - 6  having sum (4 + 8)

There's no toffee for y in given range

import numpy as np

N=10**6+1
t=eval(input())
inp = ()

t1=ord('z')
#bag=[[0  for _ in xrange(t1)] for _ in xrange(N+1)]
bag=np.zeros((N+1,t1),dtype=np.int)
#print bag
while t:
 t-=1
 inp=input().split()
 t2=ord(inp[3]) - ord('a')
 t3=int(inp[1])
 t4=int(inp[2]) + 1
 if inp[0]=="1":
  #print "enter"
  bag[t3][t2]+=int(inp[2])

 if inp[0]=="2":
  sum=0
  for i in range(t3,t4):
   sum+=bag[i][t2]
  print(sum)

#
# for j in range(ord('z')-ord('a')):
#     for i in range(N+1):
#         if bag[i][j]!=0:
#             print bag[i][j] ,i,j


Solve in Python:
It's Diwali time and you are on a tour of Codepur, a city consisting of buildings of equal length and breadth because they were designed by a computer architect with a bit of OCD.
The ruling party of Codepur wants to have a blockbuster Diwali celebration but lack enough funds and decided to open a donation channel called Codepur Cares Fund (CCF). So they decided to run a survey.
Each building eihter has permanent donors, whose impact value is represented as a positive integer, or potential donors, whose impact value is represented by negative integers.
Overwhelmed by the response, and sticking to their resource optimized philosophy, they decided to hire you to determine the contiguous buildings which are allowed to donate to CCF with the following rule:
The contiguous buildings / areas with the maximum sum impact shall be allowed for donating to Codepur Cares Fund (CCF).
Help them out to get a stunning Diwali bonus and rest of your trip sponsered!

-----Input:-----
The first line consists of two tab spaced integers m and n, indicating number of rows and columns respectively in the Codepur's city plan (which is a 2-D Matrix).
The next $m$ lines consist of $n$ tab spaced integers $ti$ indicating rows in the matrix.

-----Output:-----
Print the bulidings (represented by their donors numbers) which are eligible to donate to CCF (i.e, have the largest sum contiguously) as a 2-D matrix with the elements being tab-spaced.

-----Constraints-----
- $0 \leq m,n \leq 10^{15}$
- $-10^{15} \leq ti \leq 10^5$

-----Sample Input:-----
6    5
0    -2    -7    0    -1
9    2    -6    2    0
-4    1    -4    1    0
-1    8    0    -2    1
-10    1    1    -5    6
-15    -1    1    5    -4

-----Sample Output:-----
9    2
-4    1
-1    8

#dt = {} for i in x: dt[i] = dt.get(i,0)+1
import sys;input = sys.stdin.readline
inp,ip = lambda :int(input()),lambda :[int(w) for w in input().split()]

def kadane(arr, start, finish, n):
    Sum = 0
    maxSum = float('-inf')
    i = None
    finish[0] = -1
    local_start = 0
    for i in range(n):
        Sum += arr[i]
        if Sum < 0:
            Sum = 0
            local_start = i + 1
        elif Sum > maxSum:
            maxSum = Sum
            start[0] = local_start
            finish[0] = i

    if finish[0] != -1:
        return maxSum

    maxSum = arr[0]
    start[0] = finish[0] = 0

    for i in range(1, n):
        if arr[i] > maxSum:
            maxSum = arr[i]
            start[0] = finish[0] = i
    return maxSum

def findMaxSum(M):
    nonlocal ROW, COL
    maxSum, finalLeft = float('-inf'), None
    finalRight, finalTop, finalBottom = None, None, None
    left, right, i = None, None, None

    temp = [None] * ROW
    Sum = 0
    start = [0]
    finish = [0]

    for left in range(COL):
        temp = [0] * ROW
        for right in range(left, COL):
            for i in range(ROW):
                temp[i] += M[i][right]
            Sum = kadane(temp, start, finish, ROW)
            if Sum > maxSum:
                maxSum = Sum
                finalLeft = left
                finalRight = right
                finalTop = start[0]
                finalBottom = finish[0]

    for i in range(finalTop,finalBottom+1):
        print(*M[i][finalLeft:finalRight+1])

ROW,COL = ip()
M = [ip() for i in range(ROW)]
findMaxSum(M)


Solve in Python:
It's Friday night, and Chuck is bored. He's already run 1,000 miles, stopping only to eat a family sized bag of Heatwave Doritos and a large fistful of M&Ms. He just can't stop thinking about kicking something!

There is only one thing for it, Chuck heads down to his local MMA gym and immediately challenges every fighter there to get in the cage and try and take him down... AT THE SAME TIME!

You are provided an array of strings that represent the cage and Chuck's opponents. Your task, in traditional Chuck style, is to take their heads off!! Throw punches, kicks, headbutts (or more likely - regex or iteration...) but whatever you do, remove their heads. Return the same array of strings, but with the heads ('O') removed and replaced with a space (' ').

If the provided array is empty, or is an empty string, return 'Gym is empty'. If you are given an array of numbers, return 'This isn't the gym!!'.

FIGHT!!

*Original design of this kata was a much more beautiful thing - the test cases illustrate the idea, and the intended output. I am unable to make the actual output go over multiple lines so for now at least you will have to imagine the beauty!*

def head_smash(arr):
    if not arr:return "Gym is empty"
    if not isinstance(arr,list):return "This isn't the gym!!"
    return list(map(lambda x:x.replace("O"," "),arr))


Solve in Python:
It's John's birthday; he has brought some candies in distribute among N of his friends. Being a good friend, he decided to distribute all of his candies equally among his friend and he don't want to keep any for himself. He left the task of distributing candies up to his friends, but his friends haven't done a great job in distributing them and now they all have unequal amount of candies.
He asked all of his friends to keep all the candies in their hands (A[1] to A[N]) so that he can redistribute the candies. Taking a candy away from someone makes them sad and makes the person who gets it happy. Thus, you do not want to do many operations on the number of candies.
Here each operation stands for, taking away 1 candy from someone and giving it to somebody else.
After applying the operations, he might not be able to distribute all the candies among all of your friends, and you might need to buy some more candies as well. Buying each candy will be counted as 1 operation as well. John is saving up for his birthday party in the evening and so he wants to spend the least amount of money on candies as possible.
Thus, he asks for your help. You have to find the minimum number of operations required to make the distributions equal.

-----Input:-----
- The first line consists of the number T representing the number of test cases.
- Each test case consists of 2 lines.
- The first line contains of the number N representing the number of friends.
- The second line contains space separated numbers (A[1] to A[N]) representing the number of candies each friend currently has.

-----Output:-----
For each test case, you much print the minimum number of operations.

-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq N \leq 10^5$
- $0 \leq A[i] \leq 10^9$

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

4

7 8 6 4

6

7 3 10 2 3 8

1

10

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

10

0

import math
t = int(input())
for i in range(t):
    n = int(input())
    lst = list(map(int,input().split()))
    v = math.ceil(sum(lst)/n)
    b = 0
    t = 0
    for i in lst:
        if i > v:
            b+=(i-v)

    t+=b

    for i in lst:
        if i < v :
            b-=(v-i)
            i+=(v-i)

    t+=abs(b)
    print(t)


Solve in Python:
It's March and you just can't seem to get your mind off brackets. However, it is not due to basketball. You need to extract statements within strings that are contained within brackets.

You have to write a function that returns a list of statements that are contained within brackets given a string. If the value entered in the function is not a string, well, you know where that variable should be sitting.

Good luck!

import re

REGEX = re.compile(r'\[(.*?)\]')

def bracket_buster(strng):
    try:
        return REGEX.findall(strng)
    except TypeError:
        return 'Take a seat on the bench.'


Solve in Python:
It's a Pokemon battle! Your task is to calculate the damage that a particular move would do using the following formula (not the actual one from the game):

Where:

* attack = your attack power
* defense = the opponent's defense
* effectiveness = the effectiveness of the attack based on the matchup (see explanation below)

Effectiveness:

Attacks can be super effective, neutral, or not very effective depending on the matchup. For example, water would be super effective against fire, but not very effective against grass.

* Super effective: 2x damage
* Neutral: 1x damage
* Not very effective: 0.5x damage

To prevent this kata from being tedious, you'll only be dealing with four types: `fire`, `water`, `grass`, and `electric`.  Here is the effectiveness of each matchup:

* `fire > grass`
* `fire < water`
* `fire = electric`

* `water < grass`
* `water < electric`

* `grass = electric`

For this kata, any type against itself is not very effective. Also, assume that the relationships between different types are symmetric (if `A` is super effective against `B`, then `B` is not very effective against `A`).

The function you must implement takes in:
1. your type
2. the opponent's type
3. your attack power
4. the opponent's defense

import math

def calculate_damage(your_type, opponent_type, attack, defense):
    powerMap = {
        ('fire','grass') : 2,
        ('water', 'fire'): 2,
        ('fire', 'electric'): 1,
        ('grass', 'water'): 2,
        ('electric', 'water'): 2,
        ('grass', 'electric'): 1

    }
    print((your_type, opponent_type, attack, defense))
    effectiveness = 0
    if your_type == opponent_type or ((opponent_type, your_type) in powerMap and powerMap[(opponent_type, your_type)] == 2):
        effectiveness = 0.5
    elif (your_type, opponent_type) in powerMap:
        effectiveness = powerMap[(your_type, opponent_type)]
    elif (opponent_type, your_type) in powerMap and powerMap[(opponent_type, your_type)] == 1:
        effectiveness = 1

    return math.ceil(attack/defense * 50 * effectiveness)


Solve in Python:
It's autumn now, the time of the leaf fall.
Sergey likes to collect fallen leaves in autumn. In his city, he can find fallen leaves of maple, oak and poplar. These leaves can be of three different colors: green, yellow or red.
Sergey has collected some leaves of each type and color. Now he wants to create the biggest nice bouquet from them. He considers the bouquet nice iff all the leaves in it are either from the same type of tree or of the same color (or both). Moreover, he doesn't want to create a bouquet with even number of leaves in it, since this kind of bouquets are considered to attract bad luck. However, if it's impossible to make any nice bouquet, he won't do anything, thus, obtaining a bouquet with zero leaves.
Please help Sergey to find the maximal number of leaves he can have in a nice bouquet, which satisfies all the above mentioned requirements.
Please note that Sergey doesn't have to use all the leaves of the same color or of the same type. For example, if he has 20 maple leaves, he can still create a bouquet of 19 leaves.

-----Input-----
IThe 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 three space-separated integers MG MY MR denoting the number of green, yellow and red maple leaves respectively.
The second line contains three space-separated integers OG OY OR denoting the number of green, yellow and red oak leaves respectively.
The third line of each test case contains three space-separated integers PG PY PR denoting the number of green, yellow and red poplar leaves respectively.

-----Output-----
For each test case, output a single line containing the maximal amount of flowers in nice bouquet, satisfying all conditions or 0 if it's impossible to create any bouquet, satisfying the conditions.

-----Constraints-----

- 1 ≤ T ≤ 10000
- Subtask 1 (50 points): 0 ≤ MG, MY, MR, OG, OY, OR, PG, PY, PR ≤ 5
- Subtask 2 (50 points): 0 ≤ MG, MY, MR, OG, OY, OR, PG, PY, PR ≤...


Solve in Python:
It's been a tough week at work and you are stuggling to get out of bed in the morning.

While waiting at the bus stop you realise that if you could time your arrival to the nearest minute you could get valuable extra minutes in bed.

There is a bus that goes to your office every 15 minute, the first bus is at `06:00`, and the last bus is at `00:00`.

Given that it takes 5 minutes to walk from your front door to the bus stop, implement a function that when given the curent time will tell you much time is left, before you must leave to catch the next bus.

## Examples

```
"05:00"  =>  55
"10:00"  =>  10
"12:10"  =>  0
"12:11"  =>  14
```

### Notes

1. Return the number of minutes till the next bus
2. Input will be formatted as `HH:MM` (24-hour clock)
3. The input time might be after the buses have stopped running, i.e. after `00:00`

def bus_timer(current_time):
    tim = current_time[3:]
    time = int(tim)
    tume = int(current_time[:2])
    if tume == 5 and time > 55:
            return 60 - time + 15 - 5
    elif tume < 6 and tume >= 0:
        return ((6 - tume) * 60) - 5 - time

    else:
        if tume == 23 and time > 55:
            return 360 - 5 + 60 - time
        elif time < 15 and time <= 10:
            return 15 - time - 5
        elif time < 30 and time <= 25:
            return 30 - time - 5
        elif time < 45 and time <=40:
            return 45 - time - 5
        elif time < 15 and time > 10:
            return 30 - time - 5
        elif time < 30 and time > 25:
            return 45 - time - 5
        elif time < 45 and time > 40:
            return 60 - time - 5
        elif time < 60 and time > 55:
            return 75 - time - 5
        else:
            return 60 - time - 5


Solve in Python:
It's bonus time in the big city! The fatcats are rubbing their paws in anticipation... but who is going to make the most money?

Build a function that takes in two arguments (salary, bonus). Salary will be an integer, and bonus a boolean.

If bonus is true, the salary should be multiplied by 10. If bonus is false, the fatcat did not make enough money and must receive only his stated salary.

Return the total figure the individual will receive as a string prefixed with "£" (= `"\u00A3"`, JS, Go, and Java), "$" (C#, C++, Ruby, Clojure, Elixir, PHP and Python, Haskell, Lua) or "¥" (Rust).

def bonus_time(salary, bonus):
    return '$' + str(salary * [1,10][bonus])


Solve in Python:
It's pretty straightforward. Your goal is to create a function that removes the first and last characters of a string. You're given one parameter, the original string.  You don't have to worry with strings with less than two characters.

def remove_char(s):
    s1=[]
    for x in s:
        s1.append(x)
    s1.pop(0)
    s1.pop(-1)
    s2=""
    for x in s1:
       s2+=x
    return s2


Solve in Python:
It's the academic year's end, fateful moment of your school report.
The averages must be calculated. All the students come to you and entreat you to calculate their average for them.
Easy ! You just need to write a script.

Return the average of the given array rounded **down** to its nearest integer.

The array will never be empty.

def get_average(marks):

    import math
    x = (marks, math.floor(sum(marks)/len(marks)))

    return x[-1]


Solve in Python:
It's the annual military parade, and all the soldier snakes have arrived at the parade arena, But they aren't standing properly. The entire parade must be visible from the main podium, and all the snakes must be in a line. But the soldiers are lazy, and hence you must tell the soldiers to move to their new positions in such a manner that the total movement is minimized.
Formally, the entire parade strip can be thought of as the integer line. There are N snakes, where each snake is a line segment of length L. The i-th snake is initially at the segment [Si, Si + L]. The initial positions of the snakes can overlap. The only segment of the strip visible from the podium is [A, B], and hence all the snakes should be moved so that all of them are visible from the podium. They should also all be in a line without gaps and every consecutive pair touching each other. In other words, they should occupy the segments [X, X + L], [X + L, X + 2*L], ... , [X + (N-1)*L, X + N*L], for some X, such that A ≤ X ≤ X + N*L ≤ B. You are guaranteed that the visible strip is long enough to fit all the snakes.

If a snake was initially at the position [X1, X1 + L] and finally is at the position [X2, X2 + L], then the snake is said to have moved a distance of |X2 - X1|. The total distance moved by the snakes is just the summation of this value over all the snakes. You need to move the snakes in such a manner that it satisfies all the conditions mentioned above, as well as minimize the total distance. You should output the minimum total distance achievable.

-----Input-----
- The first line contains a single integer, T, the number of testcases. The description of each testcase follows.
- The first line of each testcase contains four integers, N, L, A and B, where N denotes the number of snakes, L denotes the length of each snake, and [A, B] is the segment visible from the podium.
- The next line contains N integers, the i-th of which is Si. This denotes that the i-th snake is initially in the segment [Si, Si + L].

-----Output-----
- For...

T = eval(input())
def diff(seqA, seqB):
 d = 0
 for i in range(len(seqA)):
  d += abs(seqA[i]- seqB[i])
 return d
def gen_seq(start, L, N):
 return [start + i*L for i in range(N)]

def binSearch(s,e,ll,L,N):
 # find the middle item
 if s==e:
  return diff(ll,gen_seq(s,L,N))

 mid = int((s+e)/2)
 if diff(ll,gen_seq(mid,L,N)) > diff(ll,gen_seq(mid+1,L,N)):
  # we go left
  return binSearch(mid+1,e,ll,L,N)
 else:
  return binSearch(s,mid,ll,L,N)
  #we go right

while T>0:
 T-=1

 N,L,A,B = list(map(int,input().split()))
 ll = list(map(int,input().split()))
 ll = sorted(ll)

 lastpossible = B - L
 startA = A

 # the one for which the last one remains there in range
 lastA = int((B-L) - (N-1)*L)
 # print "N %d L %d A %d B %d" % (N,L,A,B)
 # print "startA %d, lastA %d" %(startA,lastA)
 # print(lastA - startA)/(1.0*L)

 seq_cost_beg = diff(ll,gen_seq(startA,L,N))
 seq_cost_end = diff(ll,gen_seq(lastA,L,N))

 # print min(seq_cost_beg, seq_cost_end)

 print(binSearch(startA,lastA,ll,L,N))

 # for j in range(startA,lastA+1):
 #     leg_seq = gen_seq(j,L,N)
 #     print ll,leg_seq,diff(ll,leg_seq)
 # print "-------------"


Solve in Python:
It's the fourth quater of the Super Bowl and your team is down by 4 points. You're 10 yards away from the endzone, if your team doesn't score a touchdown in the next four plays you lose. On a previous play, you were injured and rushed to the hospital. Your hospital room has no internet, tv, or radio and you don't know the results of the game. You look at your phone and see that on your way to the hospital a text message came in from one of your teamates. It contains an array of the last 4 plays in chronological order. In each play element of the array you will receive the yardage of the play and the type of the play. Have your function let you know if you won or not.

# What you know:

* Gaining greater than 10 yds from where you started is a touchdown and you win.
* Yardage of each play will always be a positive number greater than 0.
* There are only four types of plays: "run", "pass", "sack", "turnover".
* Type of plays that will gain yardage are: "run", "pass".
* Type of plays that will lose yardage are: "sack".
* Type of plays that will automatically lose the game are: "turnover".
* When a game ending play occurs the remaining (plays) arrays will be empty.
* If you win return true, if you lose return false.

# Examples:

[[8, "pass"],[5, "sack"],[3, "sack"],[5, "run"]]
`false`
[[12, "pass"],[],[],[]])
`true`
[[2, "run"],[5, "pass"],[3, "sack"],[8, "pass"]]
`true`
[[5, "pass"],[6, "turnover"],[],[]]
`false`

Good Luck!

def did_we_win(plays):
    s = 0
    for i in range(4):
        if not plays[i]: break
        if plays[i][1] == "turnover": return False
        s += plays[i][0] * (-1)**(plays[i][1] == "sack")
    return s > 10


Solve in Python:
It's the most hotly anticipated game of the school year - Gryffindor vs Slytherin! Write a function which returns the winning team.

You will be given two arrays with two values.

The first given value is the number of points scored by the team's Chasers and the second a string with a 'yes' or 'no' value if the team caught the golden snitch!

The team who catches the snitch wins their team an extra 150 points - but doesn't always win them the game.

If the score is a tie return "It's a draw!""

** The game only ends when someone catches the golden snitch, so one array will always include 'yes' or 'no.' Points scored by Chasers can be any positive integer.

def game_winners(gryffindor, slytherin):
    g = gryffindor[0]
    s = slytherin[0]
    if gryffindor[1] == "yes":
        g += 150
    else:
        s += 150
    if g > s:
        return "Gryffindor wins!"
    elif g < s:
        return "Slytherin wins!"
    else:
        return "It's a draw!"


Solve in Python:
It's tricky keeping track of who is owed what when spending money in a group. Write a function to balance the books.

* The function should take one parameter: an object/dict with two or more name-value pairs which represent the members of the group and the amount spent by each.
* The function should return an object/dict with the same names, showing how much money the members should pay or receive.

**Further points:**

* The values should be positive numbers if the person should receive money from the group, negative numbers if they owe money to the group.
* If value is a decimal, round to two decimal places.

Translations and comments (and upvotes!) welcome.

### Example

3 friends go out together: A spends £20, B spends £15, and C spends £10. The function should return an object/dict showing that A should receive £5, B should receive £0, and C should pay £5.

def split_the_bill(x):
    perperson = 1.0 * sum(x.values()) / len(x)

    for name, val in x.items():
        x[name] = round(val - perperson, 2)

    return x


Solve in Python:
It's winter and taking a bath is a delicate matter. Chef has two buckets of water. The first bucket has $v_1$ volume of cold water at temperature $t_1$. The second has $v_2$ volume of hot water at temperature $t_2$. Chef wants to take a bath with at least $v_3$ volume of water which is at exactly $t_3$ temperature. To get the required amount of water, Chef can mix some water obtained from the first and second buckets.
Mixing $v_x$ volume of water at temperature $t_x$ with $v_y$ volume of water at temperature $t_y$ yields $v_x + v_y$ volume of water at temperature calculated as
vxtx+vytyvx+vyvxtx+vytyvx+vy\frac{v_x t_x + v_y t_y}{v_x + v_y}
Help Chef figure out if it is possible for him to take a bath with at least $v_3$ volume of water at temperature $t_3$.
Assume that Chef has no other source of water and that no heat is lost by the water in the buckets with time, so Chef cannot simply wait for the water to cool.

-----Input-----
- The first line contains $n$, the number of test cases. $n$ cases follow.
- Each testcase contains of a single line containing 6 integers $v_1, t_1, v_2, t_2, v_3, t_3$.

-----Output-----
- For each test case, print a single line containing "YES" if Chef can take a bath the way he wants and "NO" otherwise.

-----Constraints-----
- $1 \leq n \leq 10^5$
- $1 \leq v_1, v_2, v_3 \leq 10^6$
- $1 \leq t_1 < t_2 \leq 10^6$
- $1 \leq t_3 \leq 10^6$

-----Sample Input-----
3
5 10 5 20 8 15
5 10 5 20 1 30
5 10 5 20 5 20

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

-----Explanation-----
- Case 1: Mixing all the water in both buckets yields 10 volume of water at temperature 15, which is more than the required 8.
- Case 2: It is not possible to get water at 30 temperature.
- Case 3: Chef can take a bath using only the water in the second bucket.

from sys import stdin,stdout

def lin(): return int(stdin.readline())
def mlin(): return map(int,stdin.readline().rstrip().split())
def llin(): return list(mlin())
def res():
 for i in range(lin()):
  v1,t1,v2,t2,v3,t3=mlin()
  if v1+v2<v3:
   print("NO")
  else:
   x=(v3*(t3-t2))/(t1-t2)
   y=(v3*(t3-t1))/(t2-t1)
   if x<=v1 and y<=v2 and x>=0 and y>=0:
    print("YES")
   else:
    print("NO")
res()


Solve in Python:
It's year 2018 and it's Christmas time! Before going for vacations, students of Hogwarts School of Witchcraft and Wizardry had their end semester exams.
$N$ students attended the semester exam. Once the exam was over, their results were displayed as either "Pass" or "Fail" behind their magic jacket which they wore. A student cannot see his/her result but can see everyone else's results. Each of $N$ students count the number of passed students they can see.
Given the number of "Pass" verdicts that each of the $N$ students counted, we have to figure out conclusively, the number of students who failed, or report that there is some inconsistency or that we cannot be sure.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- The first line of each test case will contain $N$, representing the number of students who attended the exam.
- Next line contains  $N$ spaced integers representing the number of "Pass" counted by each of the $N$ students.

-----Output:-----
- For each test case, output the answer in a single line.
- If the counts reported by the students are not consistent with each other or if it's not possible to predict the number of failed students from the given input, then print -1.

-----Constraints-----
- $1 \leq T \leq 50$
- $1 \leq N \leq 10^{5}$
- $0 \leq$ Count given by each Student $\leq 10^{5}$

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

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

-----EXPLANATION:-----
There are 4 students, and they counted the number of passed students as 3,2,2,2. The first student can see that all others have passed, and all other students can see only 2 students who have passed. Hence, the first student must have failed, and others have all passed. Hence, the answer is 1.

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

 if n == 1 or len(s) > 2:
  print(-1)
  continue

 if len(s) == 1:
  x = s.pop()

  if x == 0:
   print(n)
  elif x == n-1:
   print(0)
  else:
   print(-1)

  continue

 x, y = sorted(s)
 xc, yc = a.count(x), a.count(y)

 if xc == y:
  print(yc)
 else:
  print(-1)


Solve in Python:
It's your Birthday. Your colleagues buy you a cake. The numbers of candles on the cake is provided (x). Please note this is not reality, and your age can be anywhere up to 1,000. Yes, you would look a mess.

As a surprise, your colleagues have arranged for your friend to hide inside the cake and burst out. They pretend this is for your benefit, but likely it is just because they want to see you fall over covered in cake. Sounds fun!

When your friend jumps out of the cake, he/she will knock some of the candles to the floor. If the number of candles that fall is higher than 70% of total candles (x), the carpet will catch fire.

You will work out the number of candles that will fall from the provided string (y). You must add up the character ASCII code of each even indexed (assume a 0 based indexing) character in y, with the alphabetical position of each odd indexed character in y to give the string a total.

example: 'abc' --> a=97, b=2, c=99 --> y total = 198.

If the carpet catches fire, return 'Fire!', if not, return 'That was close!'.

def cake(candles,debris):
    return 'Fire!' if sum(ord(c) - (i % 2 and 96) for i, c in enumerate(debris)) > 0.7 * candles and candles != 0 else 'That was close!'


Solve in Python:
Its Christmas time and Santa has started his ride to deliver gifts to children waiting for him in a 1-dimentional city. All houses in this city are on a number line numbered as 1, 2, 3… and so on. Santa wants to deliver to houses from n to m, but he found that all the kids living at positions that are divisible by a, a+d, a+2d, a+3d or a+4d are naughty and he does not want to deliver them any gifts. Santa wants to know how many gifts he has to carry before leaving to the city given that there is only one kid in a house. Help him out!
Formally, Given $m, n, a, d \in \mathbb{N}$ where $n < m$, find the number of $x \in \{n, n+1, ..., m-1, m\}$ such that $x$ is not divisible by $a$, $a+d$, $a+2d$, $a+3d$ or $a+4d$

-----Input-----
The first line is the number $t$, corresponding to number of test cases\
This is followed by $t$ lines of the format: $n$ $m$ $a$ $d$

-----Output-----
For each test case, print a single number that is the number of gifts Santa should pack.

-----Constraints-----
- $1 < m, n, a \leq 2^{32}$
- $1 < d \leq 2^{10}$

-----Sample Input:-----
1
2 20 2 1

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

-----Explanation:-----
In the range {2, 3, 4, …, 19, 20}, only {7, 11, 13, 17, 19} are not divisible by 2, 3, 4, 5, or 6

from math import gcd
from math import ceil
from itertools import combinations as c
t=int(input())
for _ in range(t):
    n,m,a,d=list(map(int,input().split()))

    l=[]
    for i in range(5):
        l.append(a+i*d)
    ans=m-n+1
    for i in range(1,6):
        x=list(c(l,i))
        for j in x:
            e=j[0]
            for v in j:
                e=(e*v)//gcd(e,v)
            #print(e)
            if i%2:
                ans-=m//e-(n-1)//e
            else:
                ans+=m//e-(n-1)//e
    print(ans)


Solve in Python:
Ivan has an array consisting of n different integers. He decided to reorder all elements in increasing order. Ivan loves merge sort so he decided to represent his array with one or several increasing sequences which he then plans to merge into one sorted array.

Ivan represent his array with increasing sequences with help of the following algorithm.

While there is at least one unused number in array Ivan repeats the following procedure:  iterate through array from the left to the right;  Ivan only looks at unused numbers on current iteration;  if current number is the first unused number on this iteration or this number is greater than previous unused number on current iteration, then Ivan marks the number as used and writes it down.

For example, if Ivan's array looks like [1, 3, 2, 5, 4] then he will perform two iterations. On first iteration Ivan will use and write numbers [1, 3, 5], and on second one — [2, 4].

Write a program which helps Ivan and finds representation of the given array with one or several increasing sequences in accordance with algorithm described above.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 2·10^5) — the number of elements in Ivan's array.

The second line contains a sequence consisting of distinct integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — Ivan's array.

-----Output-----

Print representation of the given array in the form of one or more increasing sequences in accordance with the algorithm described above. Each sequence must be printed on a new line.

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

Output
1 3 5
2 4

Input
4
4 3 2 1

Output
4
3
2
1

Input
4
10 30 50 101

Output
10 30 50 101

n = int(input())

a = []
arr = list(map(int, input().split()))

for i in range(n):
    if len(a) == 0:
        a.append([arr[i]])
        continue
    el = arr[i]
    l, r = 0, len(a) - 1
    while r - l >= 1:
        m = (l + r) // 2
        if el > a[m][-1]:
            r = m
        else:
            l = m + 1
    if el < a[l][-1]:
        a.append([el])
    else:
        a[l].append(el)

for x in a:
    for el in x:
        print(el, end=' ')
    print()


Solve in Python:
Ivan wants to make a necklace as a present to his beloved girl. A necklace is a cyclic sequence of beads of different colors. Ivan says that necklace is beautiful relative to the cut point between two adjacent beads, if the chain of beads remaining after this cut is a palindrome (reads the same forward and backward).

 [Image]

Ivan has beads of n colors. He wants to make a necklace, such that it's beautiful relative to as many cuts as possible. He certainly wants to use all the beads. Help him to make the most beautiful necklace.

-----Input-----

The first line of the input contains a single number n (1 ≤ n ≤ 26) — the number of colors of beads. The second line contains after n positive integers a_{i}   — the quantity of beads of i-th color. It is guaranteed that the sum of a_{i} is at least 2 and does not exceed 100 000.

-----Output-----

In the first line print a single number — the maximum number of beautiful cuts that a necklace composed from given beads may have. In the second line print any example of such necklace.

Each color of the beads should be represented by the corresponding lowercase English letter (starting with a). As the necklace is cyclic, print it starting from any point.

-----Examples-----
Input
3
4 2 1

Output
1
abacaba
Input
1
4

Output
4
aaaa

Input
2
1 1

Output
0
ab

-----Note-----

In the first sample a necklace can have at most one beautiful cut. The example of such a necklace is shown on the picture.

In the second sample there is only one way to compose a necklace.

from fractions import gcd
from functools import reduce

LETTERS = 'abcdefghijklmnopqrstuvwxyz'

def necklace_odd(a):
    oi = next(i for i, ai in enumerate(a) if ai%2)
    o = a[oi]
    g = reduce(gcd, a)
    s = [LETTERS[i] * (a[i]//(2*g)) for i in range(len(a)) if i != oi]
    return g, (''.join(s) + (LETTERS[oi]*(o//g)) + ''.join(reversed(s))) * g

def necklace_even(a):
    g = reduce(gcd, a)//2
    s = [LETTERS[i]*(a[i]//(2*g)) for i in range(len(a))]
    return 2*g, (''.join(s) + ''.join(reversed(s))) * g

def necklace(a):
    if len(a) == 1:
        return a[0], LETTERS[0]*a[0]

    nodd = sum(ai%2 for ai in a)
    if nodd > 1:
        return 0, ''.join(LETTERS[i]*a[i] for i in range(len(a)))

    return (necklace_odd if nodd else necklace_even)(a)

def __starting_point():
    n = int(input())
    a = list(map(int, input().split()))
    assert len(a) == n
    k, e = necklace(a)
    print(k)
    print(e)

# Made By Mostafa_Khaled

__starting_point()


Solve in Python:
Jack and Jill are playing a game. They have balls numbered from `0` to `n - 1`. Jack looks the other way and asks Jill to reverse the position of the balls, for instance, to change the order from say, `0,1,2,3` to `3,2,1,0`. He further asks Jill to reverse the position of the balls `n` times, each time starting from one position further to the right, till she reaches the last ball. So, Jill has to reverse the positions of the ball starting from position `0`, then from position `1`, then from position `2` and so on. At the end of the game, Jill will ask Jack to guess the final position of any ball numbered `k`.

You will be given `2` integers, the first will be `n`(balls numbered from `0` to `n-1`) and the second will be `k`. You will return the position of the ball numbered `k` after the rearrangement.

```Perl
solve(4,1) = 3. The reversals are [0,1,2,3] -> [3,2,1,0] -> [3,0,1,2] -> [3,0,2,1]. => 1 is in position 3.
```

More examples in the test cases. Good luck!


Solve in Python:
Jack really likes his number five: the trick here is that you have to multiply each number by 5 raised to the number of digits of each numbers, so, for example:
```python
multiply(3)==15
multiply(10)==250
multiply(200)==25000
multiply(0)==0
multiply(-3)==-15
```

def multiply(n):
    return n*pow(5, len(str(n))-1) if n < 0 else n*pow(5, len(str(n)))


Solve in Python:
Jamie is a programmer, and James' girlfriend. She likes diamonds, and wants a diamond string from James. Since James doesn't know how to make this happen, he needs your help.

## Task

You need to return a string that looks like a diamond shape when printed on the screen, using asterisk (`*`) characters. Trailing spaces should be removed, and every line must be terminated with a newline character (`\n`).

Return `null/nil/None/...` if the input is an even number or negative, as it is not possible to print a diamond of even or negative size.

## Examples

A size 3 diamond:

```
 *
***
 *
```

...which would appear as a string of `" *\n***\n *\n"`

A size 5 diamond:

```
  *
 ***
*****
 ***
  *
```

...that is: `"  *\n ***\n*****\n ***\n  *\n"`

def diamond(n):
    if n < 0 or n % 2 == 0:
        return None

    result = "*" * n + "\n";
    spaces = 1;
    n = n - 2
    while n > 0:
        current = " " * spaces + "*" * n + "\n"
        spaces = spaces + 1
        n = n - 2
        result = current + result + current

    return result


Solve in Python:
January and February are usually very cold in ChefLand. The temperature may reach -20 and even -30 degrees Celsius. Because of that, many people seal up windows in their houses.
Sergey also lives in ChefLand. He wants to seal the window in his house. The window has the shape of a   simple convex polygon with N vertices.
For the sealing, there are M kinds of sticky stripes, which are sold in the shops. The stripe of the ith type has the length of Li millimeters and the cost of Ci rubles.
The sealing process consists in picking the stripe and sticking it on the border of the window. The stripe can't be cut (it is made of very lasting material) and can only be put straight, without foldings. It is not necessary to put the strip strictly on the window border, it can possibly extend outside the border side of window too (by any possible amount). The window is considered sealed up if every point on its' border is covered with at least one stripe.
Now Sergey is curious about the stripes he needs to buy. He wonders about the cheapest cost, at which he can seal his window. Please help him.

-----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 number of vertices in the polygon denoting Sergey's window.
Each of the following N lines contains a pair of space-separated integer numbers Xi Yi, denoting the coordinates of the ith points.
The following line contains a single integer M denoting the number of types of sticky stripe which is sold in the shop.
Each of the following M lines contains a pair of space-separated integers Li Ci denoting the length and the cost of the sticky stripe of the ith type respectively.

-----Output-----
For each test case, output a single line containing the minimum cost of sealing up the window.

-----Constraints-----
- 1 ≤ T ≤ 10
- The coordinates of the window are given either in clockwise or in a counter-clockwise...

from math import sqrt
import sys
sys.setrecursionlimit(10**8)
intMax = 10**18
def knapsack(rl,l,c,m):
 if m==0 and rl>0:
  return intMax
 if rl<=0:
  return 0
 return min(c[m-1]+knapsack(rl-l[m-1],l,c,m),knapsack(rl,l,c,m-1))
for _ in range(int(input())):
 n= int(input())
 cost=[]
 length=[]
 sides=[]
 for i in range(n):
  x,y = map(int,input().split())
  if i == 0:
   x0 = x
   y0 = y
   prevx = x
   prevy = y
  elif i == n-1:
   sides.append(sqrt((prevx-x)**2 + (prevy-y)**2))
   sides.append(sqrt((x0-x)**2 + (y0-y)**2))
  else:
   sides.append(sqrt((prevx-x)**2 + (prevy-y)**2))
   prevx = x
   prevy = y
 m = int(input())
 for j in range(m):
  li,ci = map(int,input().split())
  length.append(li)
  cost.append(ci)
 ans=0
 #print(sides)
 for k in sides:
  ans= ans + knapsack(k,length,cost,m)
 print(int(ans))


Solve in Python:
JavaScript provides a built-in parseInt method.

It can be used like this:

- `parseInt("10")` returns `10`
- `parseInt("10 apples")` also returns `10`

We would like it to return `"NaN"` (as a string) for the second case because the input string is not a valid number.

You are asked to write a `myParseInt` method with the following rules:

- It should make the conversion if the given string only contains a single integer value (and possibly spaces - including tabs, line feeds... - at both ends)
- For all other strings (including the ones representing float values), it should return NaN
- It should assume that all numbers are not signed and written in base 10

def my_parse_int(num_str):
  try:
    return int(num_str.strip())
  except:
    return 'NaN'


Solve in Python:
Jeff has become friends with Furik. Now these two are going to play one quite amusing game.

At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p_1, p_2, ..., p_{n}. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and i + 1, for which an inequality p_{i} > p_{i} + 1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and i + 1, for which the inequality p_{i} < p_{i} + 1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.

Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.

You can consider that the coin shows the heads (or tails) with the probability of 50 percent.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 3000). The next line contains n distinct integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ n) — the permutation p. The numbers are separated by spaces.

-----Output-----

In a single line print a single real value — the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10^{ - 6}.

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

Output
0.000000

Input
5
3 5 2 4 1

Output
13.000000

-----Note-----

In the first test the sequence is already sorted, so the answer is 0.

def merge_sort(a, l, r):

  res = 0

  if l < r:

    m = (l + r) // 2

    res += merge_sort(a, l, m)

    res += merge_sort(a, m + 1, r)

    i = l

    j = m + 1

    b = []

    while i <= m and j <= r:

      if a[i] <= a[j]:

        b.append(a[i])

        i += 1

      else:

        b.append(a[j])

        j += 1

        res += m - i + 1

    while i <= m:

      b.append(a[i])

      i += 1

    while j <= r:

      b.append(a[j])

      j += 1

    for idx, val in enumerate(b):

      a[idx + l] = val

  return res

input()

a = [int(x) for x in input().split()]

n = len(a)

ans = merge_sort(a, 0, n - 1)

if ans & 1 == 0:

  ans *= 2

else:

  ans = ans * 2 - 1

print(ans)

# Made By Mostafa_Khaled


Solve in Python:
Jeff's friends know full well that the boy likes to get sequences and arrays for his birthday. Thus, Jeff got sequence p_1, p_2, ..., p_{n} for his birthday.

Jeff hates inversions in sequences. An inversion in sequence a_1, a_2, ..., a_{n} is a pair of indexes i, j (1 ≤ i < j ≤ n), such that an inequality a_{i} > a_{j} holds.

Jeff can multiply some numbers of the sequence p by -1. At that, he wants the number of inversions in the sequence to be minimum. Help Jeff and find the minimum number of inversions he manages to get.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 2000). The next line contains n integers — sequence p_1, p_2, ..., p_{n} (|p_{i}| ≤ 10^5). The numbers are separated by spaces.

-----Output-----

In a single line print the answer to the problem — the minimum number of inversions Jeff can get.

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

Output
0

Input
9
-2 0 -1 0 -1 2 1 0 -1

Output
6

n = int(input())
inp = input()
seq = inp.split(' ')
seq = [ abs(int(x)) for x in seq ]
Max = max(seq)
nxt = [0] * n
cnt = [0] * n
pos = [n] * (Max+1)
for i in range(n-1, -1, -1):
    nxt[i] = pos[seq[i]]
    pos[seq[i]] = i
for i in range(0, Max+1):
    j = pos[i]
    while(j<n):
        front = sum(cnt[0:j])
        back  = sum(cnt[j+1:n])
        if(front < back):
            seq[j] = 0 - seq[j]
        j = nxt[j]
    j = pos[i]
    while(j < n):
        cnt[j] = 1
        j = nxt[j]
#for i in range(0, n-1):
#    print(seq[i], sep=' ')
#print(seq[n-1])
inv = 0
for i in range(len(seq)):
    for j in range(i+1, len(seq)):
        if(seq[i] > seq[j]):
            inv += 1
print(inv)


Solve in Python:
Jem is famous for his laziness at school. He always leaves things to last minute. Now Jem has N problems in the assignment of "Advanced topics in algorithm" class to solved. The assignment is due tomorrow and as you may guess he hasn't touch any of the problems. Fortunately he got a plan as always.

The first step will be buying a pack of Red Bull and then to work as hard as he can. Here is how he is going to spend the remaining time:

Jem will not take a break until he finishes at least half of the remaining problems. Formally, if N is even then he will take he first break after finishing N / 2 problems. If N is odd then the break will be after he done (N + 1) / 2 problems. Each of his break will last for B minutes. Initially, he takes M minutes in solving a problem, after each break he will take twice more time in solving a problem, i.e. 2 * M minutes per problem after the first break.

Jem will start working soon and ask you to help him calculate how much time it will take until he finish the last problem!

-----Input-----

The first line contains a single integer T represents the number of test cases in the input.
Each line in the next T line contains three integers N, B and M represents a test case.

-----Output-----

For each test case output a single line containing an integer represent how much time Jem will need (in minutes).

-----Constraints-----
- 1 ≤ T ≤ 100
- 1 ≤ N, B, M ≤ 108

-----Example-----
Input:
2
9 1 2
123456 123456 123456

Output:
45
131351258112

-----Explanation-----

In the first test case, Jem will proceed as below:

- Initially, Jem has 9 problems to solve. since it is an odd number, Jem will finish the first (9 + 1) / 2 = 5 problems with speed of 2 minutes/problem.
- After that, Jem takes 1 minute break.
- Now he has 4 problems to solve, which is an even number, so Jem will solve the next 4 / 2 = 2 problems. his speed after the first break has now became 4 minutes/problem.

- Again, he takes a 1 minute break.
- he has now 2 problems left so he do one more problem in 8 minutes.
-...

import sys

for i in range(int(input())):
 # line =
 [N,B,M] = list(map(int,input().split()))
 t = 0
 while N > 0:
  if N%2 == 0:
   t += (N/2)*M
   N = N/2
  else:
   t += ((N+1)/2)*M
   N = (N-1)/2
  M = M*2
  if N > 0:
   t += B
 print(t)


Solve in Python:
Jenny has written a function that returns a greeting for a user. However, she's in love with Johnny, and would like to greet him slightly different. She added a special case to her function, but she made a mistake.

Can you help her?

def greet(name):
    Johnny = 'my love'
    return f'Hello, {Johnny if name=="Johnny" else name}!'


Solve in Python:
Jenny is 9 years old. She is the youngest detective in North America. Jenny is a 3rd grader student, so when a new mission comes up, she gets a code to decipher in a form of a sticker (with numbers) in her math notebook and a comment (a sentence) in her writing notebook. All she needs to do is to figure out one word, from there she already knows what to do.
And here comes your role - you can help Jenny find out what the word is!

In order to find out what the word is, you should use the sticker (array of 3 numbers) to retrive 3 letters from the comment (string) that create the word.

- Each of the numbers in the array refers to the position of a letter in the string, in increasing order.
- Spaces are not places, you need the actual letters. No spaces.
- The returned word should be all lowercase letters.
- if you can't find one of the letters using the index numbers, return "No mission today". Jenny would be very sad, but that's life... :(

Example:
input: [5, 0, 3], "I Love You"
output: "ivy"
(0 = "i", 3 = "v", 5 = "y")

def missing(nums, s):
    s = s.lower().replace(" ","")
    nums = sorted(nums)
    return "No mission today" if any(i>= len(s) for i in nums) else ''.join(s[i] for i in nums)