Solve in Python:
This morning Tolik has understood that while he was sleeping he had invented an incredible problem which will be a perfect fit for Codeforces! But, as a "Discuss tasks" project hasn't been born yet (in English, well), he decides to test a problem and asks his uncle.

After a long time thinking, Tolik's uncle hasn't any ideas on how to solve it. But, he doesn't want to tell Tolik about his inability to solve it, so he hasn't found anything better than asking you how to solve this task.

In this task you are given a cell field $n \cdot m$, consisting of $n$ rows and $m$ columns, where point's coordinates $(x, y)$ mean it is situated in the $x$-th row and $y$-th column, considering numeration from one ($1 \leq x \leq n, 1 \leq y \leq m$). Initially, you stand in the cell $(1, 1)$. Every move you can jump from cell $(x, y)$, which you stand in, by any non-zero vector $(dx, dy)$, thus you will stand in the $(x+dx, y+dy)$ cell. Obviously, you can't leave the field, but also there is one more important condition — you're not allowed to use one vector twice. Your task is to visit each cell of the field exactly once (the initial cell is considered as already visited).

Tolik's uncle is a very respectful person. Help him to solve this task!

-----Input-----

The first and only line contains two positive integers $n, m$ ($1 \leq n \cdot m \leq 10^{6}$) — the number of rows and columns of the field respectively.

-----Output-----

Print "-1" (without quotes) if it is impossible to visit every cell exactly once.

Else print $n \cdot m$ pairs of integers, $i$-th from them should contain two integers $x_i, y_i$ ($1 \leq x_i \leq n, 1 \leq y_i \leq m$) — cells of the field in order of visiting, so that all of them are distinct and vectors of jumps between them are distinct too.

Notice that the first cell should have $(1, 1)$ coordinates, according to the statement.

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

Output
1 1
1 3
1 2
2 2
2 3
2 1
Input
1 1

Output
1 1

-----Note-----

The vectors from the first example in the order of...

import sys
import math
from collections import defaultdict
n,m=list(map(int,sys.stdin.readline().split()))
#cur=[1,1]
#ans=[-1 for _ in range(2*n*m)]
up,down=1,n
count=0
while up<=down:
    left,right=1,m
    #ans.append(cur)
    while left<=m and count<n*m:
        #ans.append([up,left])
        #ans[count]=[up,left]
        if count<n*m:
            sys.stdout.write((str(up)+" "+str(left)+"\n"))
        count+=1
        left+=1
        #ans[count]=[down,right]
        if count<n*m:
            sys.stdout.write((str(down)+" "+str(right)+"\n"))
        count+=1
            #ans.append([down,right])
        right-=1
    up+=1
    down-=1
'''if n==1:
    a=len(ans)
    #print(a,'a')
    for i in range(a//2):
        print(ans[i][0],ans[i][1])
else:
    a=len(ans)
    for i in range(a//2):
        print(ans[i][0],ans[i][1])
    #print(ans)'''


Solve in Python:
This problem is a version of problem D from the same contest with some additional constraints and tasks.

There are $n$ candies in a candy box. The type of the $i$-th candy is $a_i$ ($1 \le a_i \le n$).

You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all distinct (i. e. for example, a gift having two candies of type $1$ and two candies of type $2$ is bad).

It is possible that multiple types of candies are completely absent from the gift. It is also possible that not all candies of some types will be taken to a gift.

You really like some of the candies and don't want to include them into the gift, but you want to eat them yourself instead. For each candy, a number $f_i$ is given, which is equal to $0$ if you really want to keep $i$-th candy for yourself, or $1$ if you don't mind including it into your gift. It is possible that two candies of the same type have different values of $f_i$.

You want your gift to be as large as possible, but you don't want to include too many of the candies you want to eat into the gift. So, you want to calculate the maximum possible number of candies that can be included into a gift, and among all ways to choose maximum number of candies, you want to maximize the number of candies having $f_i = 1$ in your gift.

You have to answer $q$ independent queries.

If you are Python programmer, consider using PyPy instead of Python when you submit your code.

-----Input-----

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

The first line of each query contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of candies.

Then $n$ lines follow, each containing two integers $a_i$ and $f_i$ ($1 \le a_i \le n$, $0 \le f_i \le 1$), where $a_i$ is the type of the $i$-th candy, and $f_i$ denotes whether you want to keep the $i$-th candy for yourself ($0$ if you want to keep it, $1$ if you don't mind giving it away).

It...

# @author

import sys

class GCandyBoxHardVersion:
    def solve(self):
        q = int(input())
        for _ in range(q):
            n = int(input())
            a = [0] * n
            f = [0] * n
            for i in range(n):
                a[i], f[i] = [int(_) for _ in input().split()]

            d = {key: [0, 0] for key in a}
            for i in range(n):
                d[a[i]][f[i]] += 1
            rev_d = {sum(key): [] for key in list(d.values())}
            for x in d:
                rev_d[d[x][0] + d[x][1]] += [d[x]]

            for x in rev_d:
                rev_d[x].sort(key=lambda item:item[1])

            # print(rev_d)

            cur = max(rev_d)
            cnt = max(rev_d)
            nb_candies = 0
            given_away = 0
            while 1:
                if cnt == 0 or cur == 0:
                    break
                if cur > cnt:
                    cur -= 1
                    continue

                if cnt not in rev_d or not rev_d[cnt]:
                    cnt -= 1
                    continue

                mx_f = -1
                v = -1
                for max_cnt in range(cur, cnt + 1):
                    if max_cnt in rev_d and rev_d[max_cnt] and rev_d[max_cnt][-1][1] > mx_f:
                        v = max_cnt
                        mx_f = rev_d[max_cnt][-1][1]
                to_take = rev_d[v].pop()
                # rev_d[cnt] -= 1
                nb_candies += cur
                given_away += min(to_take[1], cur)
                cur -= 1
                # rev_d[cnt - cur] += 1
            print(nb_candies, given_away)

solver = GCandyBoxHardVersion()
input = sys.stdin.readline

solver.solve()


Solve in Python:
This problem is about sequences of positive integers $a_1,a_2,...,a_N$. A subsequence of a sequence is anything obtained by dropping some of the elements. For example, $3,7,11,3$ is a subsequence of $6,3,11,5,7,4,3,11,5,3$ , but $3,3,7$ is not a subsequence of $6,3,11,5,7,4,3,11,5,3$ .
A fully dividing sequence is a sequence $a_1,a_2,...,a_N$ where $a_i$ divides $a_j$ whenever $i < j$. For example, $3,15,60,720$ is a fully dividing sequence.
Given a sequence of integers your aim is to find the length of the longest fully dividing subsequence of this sequence.
Consider the sequence $2,3,7,8,14,39,145,76,320$
It has a fully dividing sequence of length $3$, namely $2,8,320$, but none of length $4$ or greater.
Consider the sequence $2,11,16,12,36,60,71,17,29,144,288,129,432,993$.
It has two fully dividing subsequences of length $5$,
- $2,11,16,12,36,60,71,17,29,144,288,129,432,993$ and
- $2,11,16,12,36,60,71,17,29,144,288,129,432,993$
and none of length $6$ or greater.

-----Input:-----
The first line of input contains a single positive integer $N$ indicating the length of the input sequence. Lines $2,...,N+1$ contain one integer each. The integer on line $i+1$ is $a_i$.

-----Output:-----
Your output should consist of a single integer indicating the length of the longest fully dividing subsequence of the input sequence.

-----Constraints:-----
- $1 \leq N \leq 10000$
- $1 \leq a_i \leq 1000000000$

-----Sample input 1:-----
9
2
3
7
8
14
39
145
76
320

-----Sample output 1:-----
3

-----Sample input 2:-----
14
2
11
16
12
36
60
71
17
29
144
288
129
432
993

-----Sample output 2:-----
5

n = int(input())
a = []
for i in range(n):
    a.append(int(input()))
ans = [1] * n
for i in range(n-2, -1, -1):
    for j in range(i+1, n):
        if(a[j] % a[i] == 0):
            ans[i] = max(ans[i], 1 + ans[j])
print(max(ans))


Solve in Python:
This problem is actually a subproblem of problem G from the same contest.

There are $n$ candies in a candy box. The type of the $i$-th candy is $a_i$ ($1 \le a_i \le n$).

You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all distinct (i. e. for example, a gift having two candies of type $1$ and two candies of type $2$ is bad).

It is possible that multiple types of candies are completely absent from the gift. It is also possible that not all candies of some types will be taken to a gift.

Your task is to find out the maximum possible size of the single gift you can prepare using the candies you have.

You have to answer $q$ independent queries.

If you are Python programmer, consider using PyPy instead of Python when you submit your code.

-----Input-----

The first line of the input contains one integer $q$ ($1 \le q \le 2 \cdot 10^5$) — the number of queries. Each query is represented by two lines.

The first line of each query contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of candies.

The second line of each query contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$), where $a_i$ is the type of the $i$-th candy in the box.

It is guaranteed that the sum of $n$ over all queries does not exceed $2 \cdot 10^5$.

-----Output-----

For each query print one integer — the maximum possible size of the single gift you can compose using candies you got in this query with the restriction described in the problem statement.

-----Example-----
Input
3
8
1 4 8 4 5 6 3 8
16
2 1 3 3 4 3 4 4 1 3 2 2 2 4 1 1
9
2 2 4 4 4 7 7 7 7

Output
3
10
9

-----Note-----

In the first query, you can prepare a gift with two candies of type $8$ and one candy of type $5$, totalling to $3$ candies.

Note that this is not the only possible solution — taking two candies of type $4$ and one candy of type $6$ is also valid.

'''input
3
8
1 4 8 4 5 6 3 8
16
2 1 3 3 4 3 4 4 1 3 2 2 2 4 1 1
9
2 2 4 4 4 7 7 7 7
'''
from sys import stdin, setrecursionlimit
from itertools import combinations
import collections

def doc(s):
    if hasattr(s, '__call__'):
        s = s.__doc__
    def f(g):
        g.__doc__ = s
        return g
    return f

class heapdict(collections.MutableMapping):
    __marker = object()

    @staticmethod
    def _parent(i):
        return ((i - 1) >> 1)

    @staticmethod
    def _left(i):
        return ((i << 1) + 1)

    @staticmethod
    def _right(i):
        return ((i+1) << 1)

    def __init__(self, *args, **kw):
        self.heap = []
        self.d = {}
        self.update(*args, **kw)

    @doc(dict.clear)
    def clear(self):
        self.heap.clear()
        self.d.clear()

    @doc(dict.__setitem__)
    def __setitem__(self, key, value):
        if key in self.d:
            self.pop(key)
        wrapper = [value, key, len(self)]
        self.d[key] = wrapper
        self.heap.append(wrapper)
        self._decrease_key(len(self.heap)-1)

    def _min_heapify(self, i):
        l = self._left(i)
        r = self._right(i)
        n = len(self.heap)
        if l < n and self.heap[l][0] < self.heap[i][0]:
            low = l
        else:
            low = i
        if r < n and self.heap[r][0] < self.heap[low][0]:
            low = r

        if low != i:
            self._swap(i, low)
            self._min_heapify(low)

    def _decrease_key(self, i):
        while i:
            parent = self._parent(i)
            if self.heap[parent][0] < self.heap[i][0]: break
            self._swap(i, parent)
            i = parent

    def _swap(self, i, j):
        self.heap[i], self.heap[j] = self.heap[j], self.heap[i]
        self.heap[i][2] = i
        self.heap[j][2] = j

    @doc(dict.__delitem__)
    def __delitem__(self, key):
        wrapper = self.d[key]
        while wrapper[2]:
            parentpos = self._parent(wrapper[2])
            parent = self.heap[parentpos]
           ...


Solve in Python:
This problem is different from the easy version. In this version Ujan makes at most $2n$ swaps. In addition, $k \le 1000, n \le 50$ and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.

After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.

Ujan has two distinct strings $s$ and $t$ of length $n$ consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most $2n$ times: he takes two positions $i$ and $j$ ($1 \le i,j \le n$, the values $i$ and $j$ can be equal or different), and swaps the characters $s_i$ and $t_j$.

Ujan's goal is to make the strings $s$ and $t$ equal. He does not need to minimize the number of performed operations: any sequence of operations of length $2n$ or shorter is suitable.

-----Input-----

The first line contains a single integer $k$ ($1 \leq k \leq 1000$), the number of test cases.

For each of the test cases, the first line contains a single integer $n$ ($2 \leq n \leq 50$), the length of the strings $s$ and $t$.

Each of the next two lines contains the strings $s$ and $t$, each having length exactly $n$. The strings consist only of lowercase English letters. It is guaranteed that strings are different.

-----Output-----

For each test case, output "Yes" if Ujan can make the two strings equal with at most $2n$ operations and "No" otherwise. You can print each letter in any case (upper or lower).

In the case of "Yes" print $m$ ($1 \le m \le 2n$) on the next line, where $m$ is the number of swap operations to make the strings equal. Then print $m$ lines, each line should contain two integers $i, j$ ($1 \le i, j \le n$) meaning that Ujan swaps $s_i$ and $t_j$ during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than $2n$ is...

from bisect import *
from collections import *
from itertools import *
import functools
import sys
import math
from decimal import *
from copy import *
from heapq import *
from fractions import *
getcontext().prec = 30
MAX = sys.maxsize
MAXN = 1000010
MOD = 10**9+7
spf = [i for i in range(MAXN)]
def sieve():
    for i in range(2,MAXN,2):
        spf[i] = 2
    for i in range(3,int(MAXN**0.5)+1):
        if spf[i]==i:
            for j in range(i*i,MAXN,i):
                if spf[j]==j:
                    spf[j]=i
def fib(n,m):
    if n == 0:
        return [0, 1]
    else:
        a, b = fib(n // 2)
        c = ((a%m) * ((b%m) * 2 - (a%m)))%m
        d = ((a%m) * (a%m))%m + ((b)%m * (b)%m)%m
        if n % 2 == 0:
            return [c, d]
        else:
            return [d, c + d]

def charIN(x= ' '):
    return(sys.stdin.readline().strip().split(x))

def arrIN(x = ' '):
    return list(map(int,sys.stdin.readline().strip().split(x)))

def ncr(n,r):
    num=den=1
    for i in range(r):
        num = (num*(n-i))%MOD
        den = (den*(i+1))%MOD

    return (num*(pow(den,MOD-2,MOD)))%MOD

def flush():
    return sys.stdout.flush()

'''*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*'''
for _ in range(int(input())):
    n = int(input())
    s = [i for i in input()]
    t = [i for i in input()]
    d = defaultdict(int)
    for i in range(n):
        d[s[i]]+=1
        d[t[i]]+=1
    if len(list(d.keys()))>n or sum(i%2 for i in list(d.values())):
        print('No')
    else:
        ans = []
        for i in range(n):
            if s[i]!=t[i]:
                for j in range(i+1,n):
                    if s[j]!=t[j]:
                        if s[i]==s[j]:
                            ans.append([j,i])
                            s[j],t[i] = t[i],s[j]
                            break
                        elif s[i]==t[j]:
                            ans.append([j,j])
                            s[j],t[j] = t[j],s[j]
                            ans.append([j,i])
                   ...


Solve in Python:
This problem is the most boring one you've ever seen.

Given a sequence of integers a_1, a_2, ..., a_{n} and a non-negative integer h, our goal is to partition the sequence into two subsequences (not necessarily consist of continuous elements). Each element of the original sequence should be contained in exactly one of the result subsequences. Note, that one of the result subsequences can be empty.

Let's define function f(a_{i}, a_{j}) on pairs of distinct elements (that is i ≠ j) in the original sequence. If a_{i} and a_{j} are in the same subsequence in the current partition then f(a_{i}, a_{j}) = a_{i} + a_{j} otherwise f(a_{i}, a_{j}) = a_{i} + a_{j} + h.

Consider all possible values of the function f for some partition. We'll call the goodness of this partiotion the difference between the maximum value of function f and the minimum value of function f.

Your task is to find a partition of the given sequence a that have the minimal possible goodness among all possible partitions.

-----Input-----

The first line of input contains integers n and h (2 ≤ n ≤ 10^5, 0 ≤ h ≤ 10^8). In the second line there is a list of n space-separated integers representing a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^8).

-----Output-----

The first line of output should contain the required minimum goodness.

The second line describes the optimal partition. You should print n whitespace-separated integers in the second line. The i-th integer is 1 if a_{i} is in the first subsequence otherwise it should be 2.

If there are several possible correct answers you are allowed to print any of them.

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

Output
1
1 2 2

Input
5 10
0 1 0 2 1

Output
3
2 2 2 2 2

-----Note-----

In the first sample the values of f are as follows: f(1, 2) = 1 + 2 + 2 = 5, f(1, 3) = 1 + 3 + 2 = 6 and f(2, 3) = 2 + 3 = 5. So the difference between maximum and minimum values of f is 1.

In the second sample the value of h is large, so it's better for one of the sub-sequences to be empty.


Solve in Python:
This problem takes its name by arguably the most important event in the life of the ancient historian Josephus: according to his tale, he and his 40 soldiers were trapped in a cave by the Romans during a siege.

Refusing to surrender to the enemy, they instead opted for mass suicide, with a twist: **they formed a circle and proceeded to kill one man every three, until one last man was left (and that it was supposed to kill himself to end the act)**.

Well, Josephus and another man were the last two and, as we now know every detail of the story, you may have correctly guessed that they didn't exactly follow through the original idea.

You are now to create a function that returns a Josephus permutation, taking as parameters the initial *array/list of items* to be permuted as if they were in a circle and counted out every *k* places until none remained.

**Tips and notes:** it helps to start counting from 1 up to n, instead of the usual range 0..n-1; k will always be >=1.

For example, with n=7 and k=3 `josephus(7,3)` should act this way.
```
[1,2,3,4,5,6,7] - initial sequence
[1,2,4,5,6,7] => 3 is counted out and goes into the result [3]
[1,2,4,5,7] => 6 is counted out and goes into the result [3,6]
[1,4,5,7] => 2 is counted out and goes into the result [3,6,2]
[1,4,5] => 7 is counted out and goes into the result [3,6,2,7]
[1,4] => 5 is counted out and goes into the result [3,6,2,7,5]
[4] => 1 is counted out and goes into the result [3,6,2,7,5,1]
[] => 4 is counted out and goes into the result [3,6,2,7,5,1,4]
```
So our final result is:
```
josephus([1,2,3,4,5,6,7],3)==[3,6,2,7,5,1,4]
```
For more info, browse the Josephus Permutation page on wikipedia; related kata: Josephus Survivor.

Also, [live game demo](https://iguacel.github.io/josephus/) by [OmniZoetrope](https://www.codewars.com/users/OmniZoetrope).

def josephus(n,k):
    i, ans = 0, []
    while n: i = (i + k - 1) % len(n); ans.append(n.pop(i))
    return ans


Solve in Python:
This program tests the life of an
evaporator containing a gas.

We know the content of the evaporator (content in ml),
the percentage of foam or gas lost every day (evap_per_day)
and the threshold (threshold) in percentage beyond which
the evaporator is no longer useful.
All numbers are strictly positive.

The program reports the nth day (as an integer)
on which the evaporator will be out of use.

**Note** : Content is in fact not necessary in the body of the function "evaporator", you can use it or not use it, as you wish. Some people might prefer to reason with content, some other with percentages only. It's up to you but you must keep it as a parameter because the tests have it as an argument.

def evaporator(content, evap_per_day, threshold):
    hold = content*threshold / 100
    day = 0
    evap = evap_per_day / 100
    while (hold < content):
        content = content - content*evap
        day += 1
    return(day)


Solve in Python:
This question is similar to the $"Operation$ $on$ $a$ $Tuple"$ problem in this month's Long Challenge but with a slight variation.

Consider the following operations on a triple of integers. In one operation, you should:

- Choose a positive integer $d>0$ and an arithmetic operation - in this case, it will only be addition.

- Choose a subset of elements of the triple.

- Apply arithmetic operation to each of the chosen elements.

For example, if we have a triple $(3,5,7)$, we may choose to add $3$ to the first and third element, and we get $(6,5,10)$ using one operation.

You are given an initial triple $(p,q,r)$ and a target triple $(a,b,c)$. Find the maximum number of operations needed to transform $(p,q,r)$ into $(a,b,c)$ or say the conversion is impossible .
Input:
- The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
- The first line of each test case contains three space-separated integers p, q and r.
- The second line contains three space-separated integers a, b and c.Output:
For each test case, print a single line containing one integer ― the maximum required number of operations(if the conversion is possible), or else print "-1"

Constraints:
- $1 \leq T \leq 1,000$
- $2 \leq |p|,|q|,|r|,|a|,|b|,|c| \leq 10^9$Sample Input:
	1

	2 2 1

	3 3 2

Sample Output:
	3

def diff(x,y):
    ans=[]

    for i in range(3):
        if x[i]>y[i]:
            return -1
        if x[i]!=y[i]:
            ans.append(abs(x[i]-y[i]))
    return sum(ans)

for _ in range(int(input())):
    q = list(map(int,input().strip().split(" ")))
    a = list(map(int,input().strip().split(" ")))
    print(diff(q,a))


Solve in Python:
This series of katas will introduce you to basics of doing geometry with computers.

`Point` objects have `x`, `y`,  and `z` attributes. For Haskell there are `Point` data types described with record syntax with fields `x`, `y`, and `z`.

Write a function calculating distance between `Point a` and `Point b`.

Tests round answers to 6 decimal places. Tests in Haskell will not round.

def distance_between_points(a, b):
    return ((a.x-b.x)**2 + (a.y-b.y)**2 + (a.z-b.z)**2)**0.5


Solve in Python:
This the second part part of the kata:

https://www.codewars.com/kata/the-sum-and-the-rest-of-certain-pairs-of-numbers-have-to-be-perfect-squares

In this part we will have to create a faster algorithm because the tests will be more challenging.

The function ```n_closestPairs_tonum()```, (Javascript: ```nClosestPairsToNum()```), will accept two arguments, ```upper_limit``` and ```k```.

The function should return the ```k``` largest pair of numbers [m, n] and the closest to ```upper_limit```. Expressing it in code:

```python
n_closestPairs_tonum(upper_limit, k) #-> [[m1, n1], [m2, n2], ...., [mk, nk]]
```
Such that:
```
upper_limit >= m1 >= m2 >= ....>= mk > 0
```
Examples:
```python
upper_limit = 1000; k = 4
n_closestPairs_tonum(upper_limit, k) == [[997, 372], [986, 950], [986, 310], [985, 864]]

upper_limit = 10000; k = 8
n_closestPairs_tonum(upper_limit, k) == [[9997, 8772], [9997, 2772], [9992, 6392], [9986, 5890], [9985, 7176], [9985, 4656], [9981, 9900], [9973, 9348]]
```
Features of the tests:
```
1000 ≤ upper_limit ≤ 200000
2 ≤ k ≤ 20
```

Enjoy it!

def n_closestPairs_tonum(num, k):
    result = []
    squares = []
    for i in range(1, (int)((2 * num) ** 0.5) + 2):
        squares.append(i ** 2)
    squares.reverse()
    for i in range(1, num):
        m = num - i
        np = []
        for s in squares:
            if s > m:
                np.append(s - m)
            else:
                break
        for n in np:
            if (m - n) in squares:
                result.append([m, n])
                if len(result) == k:
                    return result


Solve in Python:
This time minions are celebrating Diwali Festival. There are N minions in total. Each of them owns a house. On this Festival, Each of them wants to decorate their house. But none of them have enough money to do that. One of the minion, Kevin, requested Gru for money. Gru agreed for money distribution but he will be giving money to a minion if and only if demanded money is less than or equal to the money Gru have. Now Gru wonders if he can spend all the money or not.

-----Input-----
First line have number of test cases T. Each test case consist of Two Lines. First line contains two space separated integers N and K i.e. Number of minions and Amount of Money Gru have. Next line contains N space separated integers A1,A2,A3,.....,AN representing amount of money demanded by ith minion.

-----Output-----
Output YES if Gru can spend his all of the money on minions i.e. after distribution Gru have zero amount of money else NO.

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

-----Example-----
Input:
2
4 9
5 2 2 4
4 9
5 2 18 3

Output:
YES
NO

-----Explanation-----
Example case 1.At first Gru is having 9 Rs. If he gives 5 Rs. to first minion then remaining 4 Rs. can be given to 2nd and 3rd minion or to the 4th minion. Which will leave zero amount of money in the hands of Gru.
Example case 2.At first Gru is having 9 Rs. If he gives 5 Rs. to the first minion then from remaining 4 Rs. either he can give 2 Rs. to the 2nd minion or 3 Rs. to the fourth minion. Which will leave either 2 Rs. or 1 Rs. in the hands of Gru.

def find_combinations(list, sum):
 if not list:
  if sum == 0:
   return [[]]
  return []
 return find_combinations(list[1:], sum) + \
  [[list[0]] + tail for tail in
   find_combinations(list[1:], sum - list[0])]
for tc in range(int(input())):
 n,k=list(map(int,input().split()))
 a=list(map(int,input().split()))
 a.sort()
 if len(find_combinations(a,k))==0:
  print("NO")
 else:
  print("YES")


Solve in Python:
This time no story, no theory. The examples below show you how to write function `accum`:

**Examples:**
```
accum("abcd") -> "A-Bb-Ccc-Dddd"
accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
accum("cwAt") -> "C-Ww-Aaa-Tttt"
```

The parameter of accum is a string which includes only letters from `a..z` and `A..Z`.

def accum(s):
    return "-".join(list(x.upper() + x.lower() * count for count, x in enumerate(s)))


Solve in Python:
This will probably be a little series :)

X-Shape

You will get an odd Integer n (>= 3) and your task is to draw a X. Each line is separated with '\n'.

Use the following characters:  ■ □

For Ruby, Crystal and PHP:   whitespace and o

e.g.:

                                     ■□□□■
            ■□■                      □■□■□
  x(3) =>   □■□              x(5)=>  □□■□□
            ■□■                      □■□■□
                                     ■□□□■

 Series: ASCII Fun

ASCII Fun #1: X-Shape
ASCII Fun #2: Funny Dots
ASCII Fun #3: Puzzle Tiles
ASCII Fun #4: Build a pyramid

def x(n):
  return '\n'.join(''.join('■' if row==col or row==n-1-col else '□' for col in range(n)) for row in range(n))


Solve in Python:
This year $p$ footballers and $q$ cricketers have been invited to participate in IPL (Indian Programming League) as guests. You have to accommodate them in $r$ rooms such that-
- No room may remain empty.
- A room may contain either only footballers or only cricketers, not both.
- No cricketers are allowed to stay alone in a room.
Find the number of ways to place the players. Note though, that all the rooms are identical. But each of the cricketers and footballers are unique.
Since the number of ways can be very large, print the answer modulo $998,244,353$.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains three space-separated integers $p$, $q$ and $r$ denoting the number of footballers, cricketers and rooms.

-----Output-----
For each test case, output the number of ways to place the players modulo $998,244,353$.

-----Constraints-----
- $1 \le T \le 100$
- $1 \le p, q, r \le 100$

-----Example Input-----
4
2 1 4
2 4 4
2 5 4
2 8 4

-----Example Output-----
0
3
10
609

-----Explanation-----
Example case 2: Three possible ways are:
- {Footballer 1}, {Footballer 2}, {Cricketer 1, Cricketer 2}, {Cricketer 3, Cricketer 4}
- {Footballer 1}, {Footballer 2}, {Cricketer 1, Cricketer 3}, {Cricketer 2, Cricketer 4}
- {Footballer 1}, {Footballer 2}, {Cricketer 1, Cricketer 4}, {Cricketer 2, Cricketer 3}
Please note that the rooms are identical.

# -*- coding: utf-8 -*-
"""
Created on Thu Jan 23 18:46:38 2020

@author: 736473
"""

MOD = 998244353

fball = [ [0]*101 for _ in range(101) ]

cric = [ [0]*101 for _ in range(101) ]

def calSNum(n, r):
 if n == r or r == 1:
  fball[r][n] = 1
  return
 if n > 0 and r > 0 and n > r:
  fball[r][n] = (fball[r-1][n-1]%MOD + (r*fball[r][n-1])%MOD )%MOD
  return
 fball[r][n] = 0

def calASNum(n, r):
 if n == 0 and r == 0 :
  cric[r][n] = 0
  return
 if n >= 2 and r == 1:
  cric[r][n] = 1
  return
 if r > 0 and n > 0 and n >= 2*r:
  cric[r][n] = ((r*cric[r][n-1])%MOD + ((n-1)*cric[r-1][n-2])%MOD )%MOD
  return
 cric[r][n] = 0

def preCompute():
 for r in range(1,101):
  for n in range(1, 101):
   calSNum(n, r)
   calASNum(n, r)

def main():

 preCompute()

 t = int(input())
 while True:

  try:
   f, c, r = list(map(int, input().split()))
  except EOFError:
   break

  ans = 0

  if f + (c//2) >= r:
   minv = min(f, r)

   for i in range(1, minv+1):
    if r-i <= c//2:
     ans = (ans + (fball[i][f] * cric[r-i][c])%MOD )%MOD

  print(ans)

def __starting_point():
 main()
__starting_point()


Solve in Python:
Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).

q events are about to happen (in chronological order). They are of three types:  Application x generates a notification (this new notification is unread).  Thor reads all notifications generated so far by application x (he may re-read some notifications).  Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation.

Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone.

-----Input-----

The first line of input contains two integers n and q (1 ≤ n, q ≤ 300 000) — the number of applications and the number of events to happen.

The next q lines contain the events. The i-th of these lines starts with an integer type_{i} — type of the i-th event. If type_{i} = 1 or type_{i} = 2 then it is followed by an integer x_{i}. Otherwise it is followed by an integer t_{i} (1 ≤ type_{i} ≤ 3, 1 ≤ x_{i} ≤ n, 1 ≤ t_{i} ≤ q).

-----Output-----

Print the number of unread notifications after each event.

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

Output
1
2
3
2

Input
4 6
1 2
1 4
1 2
3 3
1 3
1 3

Output
1
2
3
0
1
2

-----Note-----

In the first sample:  Application 3 generates a notification (there is 1 unread notification).  Application 1 generates a notification (there are 2 unread notifications).  Application 2 generates a notification (there are 3 unread notifications).  Thor reads the...

#!/usr/bin/env	python
#-*-coding:utf-8 -*-
import collections
n,q=list(map(int,input().split()))
Q=collections.deque()
A=n*[0]
B=A[:]
L=[]
s=n=0
for _ in range(q):
	y,x=list(map(int,input().split()))
	if 2>y:
		x-=1
		Q.append(x)
		B[x]+=1
		A[x]+=1
		s+=1
	elif 3>y:
		x-=1
		s-=A[x]
		A[x]=0
	else:
		while x>n:
			n+=1
			y=Q.popleft()
			B[y]-=1
			if(B[y]<A[y]):
				A[y]-=1
				s-=1
	L.append(str(s))
print('\n'.join(L))


Solve in Python:
Three Best Friends $AMAN$ , $AKBAR$ , $ANTHONY$ are planning to go to “GOA”  , but just like every other goa trip plan there is a problem to their plan too.
Their parents will only give permission if they can solve this problem for them
They are a given a number N and they have to calculate the total number of triplets (x ,y ,z)
Satisfying the given condition  y * x +z=n.
For ex if N=3
Then there exist 3 triplets( x ,y ,z):   (1,1,2) , (1,2,1) , (2,1,1) which satisfy the condition
Help the group to get permission for the trip

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

-----Output:-----
the possible number of triplets satisfying the given condition

-----Constraints-----
- $2 \leq N \leq 10^6$

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

-----Sample Output:-----
3

-----EXPLANATION:-----
there exist 3 triplets ( x ,y ,z):   (1,1,2) , (1,2,1) , (2,1,1)  which satisfy the condition

n=int(input())
ans=0
for i in range(1,n):
    ans+=(n-1)//i
print(ans)


Solve in Python:
Three candidates take part in a TV show.

In order to decide who will take part in the final game and probably become rich, they have to roll the Wheel of Fortune!

The Wheel of Fortune is divided into 20 sections, each with a number from 5 to 100 (only mulitples of 5).

Each candidate can roll the wheel once or twice and sum up the score of each roll.
The winner one that is closest to 100 (while still being lower or equal to 100).
In case of a tie, the candidate that rolled the wheel first wins.

You receive the information about each candidate as an array of objects: each object should have a `name` and a `scores` array with the candidate roll values.

Your solution should return the name of the winner or `false` if there is no winner (all scored more than 100).

__Example:__

```python
c1 = {"name": "Bob", "scores": [10, 65]}
c2 = {"name": "Bill", "scores": [90, 5]}
c3 = {"name": "Charlie", "scores": [40, 55]}
winner([c1, c2, c3]) #Returns "Bill"
```

Please note that inputs may be invalid: in this case, the function should return false.

Potential errors derived from the specifications are:
- More or less than three candidates take part in the game.
- A candidate did not roll the wheel or rolled it more than twice.
- Scores are not valid.
- Invalid user entry (no name or no score).

def winner(candidates):
    # Filter inputs
    if len(candidates) != 3 or any(
            not c.get("name") or not c.get("scores")
            or len(c["scores"]) not in (1, 2)
            or any(s % 5 or not (5 <= s <= 100) for s in c["scores"])
            for c in candidates):
        return False

    qualified = [c for c in candidates if sum(c["scores"]) <= 100]
    if not qualified: return False

    winner = max(qualified, key=lambda c: sum(c["scores"]))
    return winner["name"]


Solve in Python:
Tic-tac-toe is played by two players A and B on a 3 x 3 grid.
Here are the rules of Tic-Tac-Toe:

Players take turns placing characters into empty squares (" ").
The first player A always places "X" characters, while the second player B always places "O" characters.
"X" and "O" characters are always placed into empty squares, never on filled ones.
The game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal.
The game also ends if all squares are non-empty.
No more moves can be played if the game is over.

Given an array moves where each element is another array of size 2 corresponding to the row and column of the grid where they mark their respective character in the order in which A and B play.
Return the winner of the game if it exists (A or B), in case the game ends in a draw return "Draw", if there are still movements to play return "Pending".
You can assume that moves is valid (It follows the rules of Tic-Tac-Toe), the grid is initially empty and A will play first.

Example 1:
Input: moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]
Output: "A"
Explanation: "A" wins, he always plays first.
"X  "    "X  "    "X  "    "X  "    "X  "
"   " -> "   " -> " X " -> " X " -> " X "
"   "    "O  "    "O  "    "OO "    "OOX"

Example 2:
Input: moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]
Output: "B"
Explanation: "B" wins.
"X  "    "X  "    "XX "    "XXO"    "XXO"    "XXO"
"   " -> " O " -> " O " -> " O " -> "XO " -> "XO "
"   "    "   "    "   "    "   "    "   "    "O  "

Example 3:
Input: moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]
Output: "Draw"
Explanation: The game ends in a draw since there are no moves to make.
"XXO"
"OOX"
"XOX"

Example 4:
Input: moves = [[0,0],[1,1]]
Output: "Pending"
Explanation: The game has not finished yet.
"X  "
" O "
"   "

Constraints:

1 <= moves.length <= 9
moves[i].length == 2
0 <= moves[i][j] <= 2
There are no repeated elements on moves.
moves follow the rules of tic tac toe.

class Solution:
    def tictactoe(self, moves: List[List[int]]) -> str:
        # player one and two moves
        player_a, player_b = moves[0::2], moves[1::2]

        # possible wins
        possible_wins = {
            0: [[0, 0], [1, 1], [2, 2]],
            1: [[0, 0], [1, 0], [2, 0]],
            2: [[0, 1], [1, 1], [2, 1]],
            3: [[0, 2], [1, 2], [2, 2]],
            4: [[0, 0], [0, 1], [0, 2]],
            5: [[1, 0], [1, 1], [1, 2]],
            6: [[2, 0], [2, 1], [2, 2]],
            7: [[0, 2], [1, 1], [2, 0]]
        }

        # count player one and two correct moves
        for possible_win in list(possible_wins.values()):
            count_a = 0
            for move in player_a:
                if move in possible_win:
                    count_a += 1
                if count_a == 3:
                    return 'A'

            count_b = 0
            for move in player_b:
                if move in possible_win:
                    count_b += 1
                if count_b == 3:
                    return 'B'

        return 'Draw' if len(player_a) + len(player_b) == 9 else 'Pending'


Solve in Python:
Time to build a crontab parser... https://en.wikipedia.org/wiki/Cron

A crontab command is made up of 5 fields in a space separated string:

```
minute: 0-59
hour: 0-23
day of month: 1-31
month: 1-12
day of week: 0-6 (0 == Sunday)
```

Each field can be a combination of the following values:

* a wildcard `*` which equates to all valid values.
* a range `1-10` which equates to all valid values between start-end inclusive.
* a step `*/2` which equates to every second value starting at 0, or 1 for day of month and month.
* a single value `2` which would be 2.
* a combination of the above separated by a `,`

Note: In the case of multiple values in a single field, the resulting values should be sorted.

Note: Steps and ranges can also be combined `1-10/2` would be every second value in the `1-10` range `1 3 5 7 9`.

For an added challenge day of week and month will both support shortened iso formats:

```
SUN MON TUE ...
JAN FEB MAR ...
```

Examples
========

`*` should output every valid value `0 1 2 3 4 5 6 ...`

`1` should output the value `1`.

`1,20,31` should output the values `1 20 31`.

`1-10` should output the values `1 2 3 4 5 6 7 8 9 10`.

`*/2` should output every second value `0 2 4 6 8 10 ...`.

`*/2` should output `1 3 5 7 9 ...` in the cases, day of month and month.

`1-10/2` should output `1 3 5 7 9`.

`*/15,3-5` should output the values `0 3 4 5 15 30 45` when applied to the minute field.

Output
======

The purpose of this kata is to take in a crontab command, and render it in a nice human readable format.

The output format should be in the format `field_name      values`. The field name should be left justified and
padded to 15 characters. The values should be a space separated string of the returned values.

For example the crontab `*/15 0 1,15 * 1-5` would have the following output:

```
minute          0 15 30 45
hour            0
day of month    1 15
month           1 2 3 4 5 6 7 8 9 10 11 12
day of week     1 2 3 4 5
```

All test cases will receive a valid crontab, there is no need to...

RANGES = {
    'minute': (0, 59),
    'hour': (0, 23),
    'day of month': (1, 31),
    'month': (1, 12),
    'day of week': (0, 6),
}

ALIASES = {
    'month': ' JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC'.split(' '),
    'day of week': 'SUN MON TUE WED THU FRI SAT'.split(),
}

def get_alias(field, value):
    try:
        return ALIASES[field].index(value)
    except:
        return int(value)

def parse(crontab):
    def parse_field(field, value):
        values = set()
        for part in value.split(','):
            part, *end = part.split('/')
            step = int(end[0]) if end else 1
            if part == '*':
                start, stop = RANGES[field]
            else:
                part, *end = part.split('-')
                start = get_alias(field, part)
                stop = get_alias(field, end[0]) if end else start
            values.update(range(start, stop + 1, step))
        return ' '.join(map(str, sorted(values)))
    return '\n'.join(f'{field:<15}{parse_field(field, value)}'
                     for field, value in zip(RANGES, crontab.split()))


Solve in Python:
Time to win the lottery!

Given a lottery ticket (ticket), represented by an array of 2-value arrays, you must find out if you've won the jackpot.  Example ticket:

To do this, you must first count the 'mini-wins' on your ticket.  Each sub array has both a string and a number within it. If the character code of any of the characters in the string matches the number, you get a mini win. Note you can only have one mini win per sub array.

Once you have counted all of your mini wins, compare that number to the other input provided (win). If your total is more than or equal to (win), return 'Winner!'. Else return 'Loser!'.

All inputs will be in the correct format. Strings on tickets are not always the same length.

def bingo(ticket,win):
    mini_wins = 0
    for arr in ticket:
        mini_wins += any(map(lambda x: ord(x) == arr[1], arr[0]))
    return ['Loser!', 'Winner!'][mini_wins >= win]


Solve in Python:
Timmy & Sarah think they are in love, but around where they live, they will only know once they pick a flower each. If one of the flowers has an even number of petals and the other has an odd number of petals it means they are in love.

Write a function that will take the number of petals of each flower and return true if they are in love and false if they aren't.

def lovefunc( flower1, flower2 ):
    return True if (flower1 % 2 == 0 and flower2 % 2 != 0) or (flower2 % 2 == 0 and flower1 % 2 != 0) else False


Solve in Python:
Timothy (age: 16) really likes to smoke. Unfortunately, he is too young to buy his own cigarettes and that's why he has to be extremely efficient in smoking.

It's now your task to create a function that calculates how many cigarettes Timothy can smoke out of the given amounts of `bars` and `boxes`:

- a bar has 10 boxes of cigarettes,
- a box has 18 cigarettes,
- out of 5 stubs (cigarettes ends) Timothy is able to roll a new one,
- of course the self made cigarettes also have an end which can be used to create a new one...

Please note that Timothy never starts smoking cigarettes that aren't "full size" so the amount of smoked cigarettes is always an integer.

from math import log
def start_smoking(bars,boxes):
    n=(bars*10+boxes)*18
    stubs=n
    while stubs>4:
        n+=stubs//5
        stubs=sum(divmod(stubs,5))
    return n


Solve in Python:
Tired of the overpopulated world, Miu - The introverted cat visits a new continent in search for a new house.
There are $N$ houses lying on the X-axis.

Their positions are given by $X$$i$ , where $i$ refers to the $i$th house. ( $1 <= i <= N$ )

Each of these positions are pairwise distinct
Miu is supposed to choose one of these houses for herself.

Miu defines a term - The Distance of Peace,  as the minimum distance from her house to any other house.
Miu wonders what is maximum Distance of Peace she can obtain. Can you help her?

-----Input:-----
- The first line of the input consists of a single integer $T$, denoting the number of test cases
- The first line of each test case consists of a single integer $N$
- The second line of each test case consists of $N$ space-separated integers
$X$$1$ $X$$2$ $X$$3$ … $X$$N$

-----Output:-----
- For each test case print the answer in a single line, the maximum Distance of Peace Miu can obtain

-----Constraints-----
- 1 <= $T$ <= 100
- 2 <= $N$ <= 105
- -109 <= $X$$i$ <= 109
- Sum of $N$ over all test cases does not exceed 106

-----Subtasks-----
Subtask #1 (30 points):
- $N$ <= 103
Subtask #2 (70 points):
- Original Constraints

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

6

7 -1 2 13 -5 15

4

6 10 3 12

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

3

-----EXPLANATION:-----
Test Case 1:

The $1$st house has the maximum Distance of Peace, which is from the $3$rd house:
$| 7 - 2 | = 5$

Hence, the answer is $5$

# cook your dish here

t = int(input())
for rep in range(t):
 n = int(input())
 x = list(map(int,input().split()))
 x.sort()
 l = []
 if n > 2:
  for i in range(1,n-1):
   l.append(min(x[i]-x[i-1],x[i+1]-x[i]))
  l.append(x[1]-x[0])
  l.append(x[n-1]-x[n-2])
 else:
  l.append(x[1]-x[0])
 print(max(l))


Solve in Python:
Tired of those repetitive javascript challenges? Here's a unique hackish one that should keep you busy for a while ;)

There's a mystery function which is already available for you to use. It's a simple function called `mystery`. It accepts a string as a parameter and outputs a string. The exercise depends on guessing what this function actually does.

You can call the mystery function like this:

```python
my_output = mystery("my_input")
```

Using your own test cases, try to call the mystery function with different input strings and try to analyze its output in order to guess what is does. You are free to call the mystery function in your own test cases however you want.

When you think you've understood how my mystery function works, prove it by reimplementing its logic in a function that you should call 'solved(x)'. To validate your code, your function 'solved' should return the same output as my function 'mystery' given the same inputs.

Beware! Passing your own test cases doesn't imply you'll pass mine.

Cheaters are welcome :)

Have fun!

---

Too easy? Then this kata will totally blow your mind:

http://www.codewars.com/kata/mystery-function-number-2

def solved(s): return ''.join(sorted(s if len(s)%2==0 else s[:len(s)//2] + s[(len(s)//2)+1:]))


Solve in Python:
To almost all of us solving sets of linear equations is quite obviously the most exciting bit of linear algebra. Benny does not agree though and wants to write a quick program to solve his homework problems for him. Unfortunately Benny's lack of interest in linear algebra means he has no real clue on how to go about this. Fortunately, you can help him!

Write a method ```solve``` that accepts a list of linear equations that your method will have to solve. The output should be a map (a `Map` object in JavaScript) with a value for each variable in the equations. If the system does not have a unique solution (has infinitely many solutions or is unsolvable), return ```null``` (`None` in python).

For example :

"2x + 4y + 6z = 18"
"3y + 3z = 6"
"x + 2y = z - 3"

should result in a map :

x = 2
y = -1
z = 3

Possible input equations have the following rules:
-   Only the plus and minus operators are used on both the left and right hand side of the equation.
-   Both sides of the equation can have variables; One variable can appear in multiple terms, on both sides.
-   Variable names are strings of arbitrary length.
-   All coefficients are integers and generally fall within the range of -150 to 150, with a few ranging from -1000 to 1000. Free terms are integers in range -20000 to 20000.
-   Equations do not necessarily have variables.
-   Equations have exactly one operator (+ or -) between terms.

Comparisons are performed with accuracy of `1e-6`.

**Note on numerical stability:**

There are many possible ways to solve a system of linear equations. One group of such algorithms is based on reduction and elimination methods. If you are going to use any of these, remember that such algorithms are in general *numerically unstable*, i.e. division operations repeated over and over introduce inaccuracies which accumulate from row to row. As a result it might occur that some value which is expected to be zero is actually larger, for example, `2.5e-10`. Such inaccuracies tend to be...

import re
from fractions import Fraction
def solve(*equations):
        equations2 = []
        for x in equations:
           equations2.append(x)
        equations = equations2
        def parsing(equations):
            vectconstant = []
            matrixcoefficient = []
            listvariables = []
            for equation in equations :
                eqvariables = re.findall('[A-Za-z]+' , equation )
                listvariables = listvariables + eqvariables
            listvariables = list(set(listvariables))
            for equation in equations :
                listcoefficient = []
                equation = re.sub('\s' , '' , equation)
                eqdivided = equation.split('=')
                firstp , secondp = eqdivided[0] , eqdivided[1]
                constantterm1 = re.findall('[\-\+]*\d+\.?\d*(?=[+-])|[\-\+]*\d+\.?\d*$', firstp)
                constantterm2 = re.findall('[\-\+]*\d+\.?\d*(?=[+-])|[\-\+]*\d+\.?\d*$', secondp)
                for x in range(len(constantterm1)):
                    constantterm1[x] = '-' + constantterm1[x]
                    constantterm1[x] = re.sub('\+\+|\-\-', '+', re.sub('\+\-|\-\+', '-',constantterm1[x]))
                constantterm = Fraction((sum(list(map(float, constantterm1 + constantterm2)))))
                vectconstant.append(constantterm)
                for x in listvariables :
                    values1 = re.findall('([\-\+]*[\d.]*)'+re.escape(x)+'(?=[+-]|$)' , firstp)
                    values2 = re.findall('([\-\+]*[\d.]*)'+re.escape(x)+'(?=[+-]|$)', secondp)
                    for x in range(len(values2)):
                        values2[x] = '-' + values2[x]
                        values2[x] = re.sub('\+\+|\-\-', '+', re.sub('\+\-|\-\+', '-',values2[x]))
                    values = values1 + values2
                    for x in range(len(values)):
                        if values[x] == '' or values[x] == '+' :
                            values[x] = '1'
                        elif values[x] == '-' :
                     ...


Solve in Python:
To celebrate the start of the Rio Olympics (and the return of 'the Last Leg' on C4 tonight) this is an Olympic inspired kata.

Given a string of random letters, you need to examine each. Some letters naturally have 'rings' in them. 'O' is an obvious example, but 'b', 'p', 'e', 'A', etc are all just as applicable. 'B' even has two!! Please note for this kata you can count lower case 'g' as only one ring.

Your job is to count the 'rings' in each letter and divide the total number by 2. Round the answer down. Once you have your final score:

if score is 1 or less,  return 'Not even a medal!';
if score is 2, return 'Bronze!';
if score is 3, return 'Silver!';
if score is more than 3, return 'Gold!';

Dots over i's and any other letters don't count as rings.

def olympic_ring(string):
    return (['Not even a medal!'] * 2 + ['Bronze!', 'Silver!', 'Gold!'])[min(4, sum(map("abdegopqABBDOPQR".count, string)) // 2)]


Solve in Python:
To celebrate today's launch of my Hero's new book: Alan Partridge: Nomad, We have a new series of kata arranged around the great man himself.

Given an array of terms, if any of those terms relate to Alan Partridge, return Mine's a Pint!

The number of ! after the t should be determined by the number of Alan related terms you find in the provided array (x). The related terms are:

Partridge
PearTree
Chat
Dan
Toblerone
Lynn
AlphaPapa
Nomad

If you don't find any related terms, return 'Lynn, I've pierced my foot on a spike!!'

All Hail King Partridge

Other katas in this series:
Alan Partridge II - Apple Turnover
Alan Partridge III - London

related = {"Partridge", "PearTree", "Chat", "Dan", "Toblerone", "Lynn", "AlphaPapa", "Nomad"}

def part(arr):
    found = sum(1 for w in arr if w in related)
    return f"Mine's a Pint{'!' * found}" if found else "Lynn, I've pierced my foot on a spike!!"


Solve in Python:
To give credit where credit is due: This problem was taken from the ACMICPC-Northwest Regional Programming Contest. Thank you problem writers.

You are helping an archaeologist decipher some runes. He knows that this ancient society used a Base 10 system, and that they never start a number with a leading zero. He's figured out most of the digits as well as a few operators, but he needs your help to figure out the rest.

The professor will give you a simple math expression, of the form

```
[number][op][number]=[number]
```

He has converted all of the runes he knows into digits. The only operators he knows are addition (`+`),subtraction(`-`), and multiplication (`*`), so those are the only ones that will appear. Each number will be in the range from -1000000 to 1000000, and will consist of only the digits 0-9, possibly a leading -, and maybe a few ?s. If there are ?s in an expression, they represent a digit rune that the professor doesn't know (never an operator, and never a leading -). All of the ?s in an expression will represent the same digit (0-9), and it won't be one of the other given digits in the expression. No number will begin with a 0 unless the number itself is  0, therefore 00 would not be a valid number.

Given an expression, figure out the value of the rune represented by the question mark. If more than one digit works, give the lowest one. If no digit works, well, that's bad news for the professor - it means that he's got some of his runes wrong. output -1 in that case.

Complete the method to solve the expression to find the value of the unknown rune. The method takes a string as a paramater repressenting the expression and will return an int value representing the unknown rune or -1 if no such rune exists.

~~~if:php
**Most of the time, the professor will be able to figure out most of the runes himself, but sometimes, there may be exactly 1 rune present in the expression that the professor cannot figure out (resulting in all question marks where the digits are in the expression) so be...

def solve_runes(runes):
    massV = []
    massV_ind = []
    massD1 = []
    massD2 = []                # more lists to the god of lists!!!!!!!!!!!
    massD1_ind = []
    massD2_ind = []
    ex = []
    mat = []

    expr, value = runes.split('=')

    if expr.find('*',1) != -1:
        ind = expr.index('*',1)
        dig_1 = expr[:ind]
        dig_2 = expr[ind+1:]
        sign = '*'
    elif expr.find('+',1) != -1:
        ind = expr.index('+',1)
        dig_1 = expr[:ind]
        dig_2 = expr[ind+1:]
        sign = '+'
    else:
        ind = expr.index('-',1)
        dig_1 = expr[:ind]
        dig_2 = expr[ind+1:]
        sign = '-'

    for i in range(len(value)):
        if value[i] == "?":
            massV_ind.append(value.index(value[i],i))
            massV.append('0')
        else:
            massV.append(value[i])

    for i in range(len(dig_1)):
        if dig_1[i] == "?":
            massD1_ind.append(dig_1.index(dig_1[i],i))
            massD1.append('0')
        else:
            massD1.append(dig_1[i])

    for i in range(len(dig_2)):
        if dig_2[i] == "?":
            massD2_ind.append(dig_2.index(dig_2[i],i))
            massD2.append('0')
        else:
            massD2.append(dig_2[i])

    for i in range(0,10):
        for q in range(len(massD1_ind)):
            massD1[massD1_ind[q]] = str(i)
        for w in range(len(massD2_ind)):
            massD2[massD2_ind[w]] = str(i)
        for e in range(len(massV_ind)):
            massV[massV_ind[e]] = str(i)

        d1 = int(''.join(massD1))
        d2 = int(''.join(massD2))
        val = int(''.join(massV))

        if sign == '*':
            if d1 * d2 == val:
                ex.append(i)

        if sign == '-':
            if d1 - d2 == val:
                ex.append(i)

        if sign == '+':
            if d1 + d2 == val:
                ex.append(i)

                                                # hate
    if dig_1[0] == '-':
        if 1 in massD1_ind:
            if len(massD1)>1:                ...


Solve in Python:
To help Lavanya learn all about binary numbers and binary sequences, her father has bought her a collection of square tiles, each of which has either a 0 or a 1 written on it. Her brother Nikhil has played a rather nasty prank. He has glued together pairs of tiles with 0 written on them. Lavanya now has square tiles with 1 on them and rectangular tiles with two 0's on them, made up of two square tiles with 0 stuck together). Thus, she can no longer make all possible binary sequences using these tiles.
To amuse herself, Lavanya has decided to pick a number $N$ and try and construct as many binary sequences of length $N$ as possible using her collection of tiles. For example if $N$ = 1, she can only make the sequence 1. For $N$=2, she can make 11 and 00. For $N$=4, there are 5 possibilities: 0011, 0000, 1001, 1100 and 1111.
Lavanya would like you to write a program to compute the number of arrangements possible with $N$ tiles so that she can verify that she has generated all of them. Since she cannot count beyond 15746, it is sufficient to report this number modulo 15746.

-----Input:-----
A single line with a single integer $N$.

-----Output:-----
A single integer indicating the number of binary sequences of length $N$, modulo 15746, that Lavanya can make using her tiles.

-----Constraints:-----
You may assume that $N \leq$ 1000000.

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

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

-----Explanation:-----
This corresponds to the example discussed above.

n=int(input())
a,b=1,2
if n==1 :
    print(1)
elif n==2 :
    print(2)
else :
    for i in range (3 , n+1) :
        c=(a+b)%15746
        a=b
        b=c
    print(c%15746)


Solve in Python:
To introduce the problem think to my neighbor who drives a tanker truck.
The level indicator is down and he is worried
because he does not know if he will be able to make deliveries.
We put the truck on a horizontal ground and measured the height of the liquid in the tank.

Fortunately the tank is a perfect cylinder and the vertical walls on each end are flat.
The height of the remaining liquid is `h`, the diameter of the cylinder is `d`,
the total volume is `vt` (h, d, vt are positive or null integers).
You can assume that `h` <= `d`.

Could you calculate the remaining volume of the liquid?
Your function `tankvol(h, d, vt)` returns an integer which is the truncated result (e.g floor)
of your float calculation.

Examples:

```
tankvol(40,120,3500) should return 1021 (calculation gives about: 1021.26992027)

tankvol(60,120,3500) should return 1750

tankvol(80,120,3500) should return 2478 (calculation gives about: 2478.73007973)
```

Tank vertical section:

![alternative text](http://i.imgur.com/wmt0U43.png)

# see https://en.wikipedia.org/wiki/Circular_segment
# for the formulas used

from math import sin, acos, pi

def tankvol(h, d, vt):
    # radius
    r = d / 2.0
    # central angle of segment
    theta = 2 * acos(1 - h/r)
    # area of segment
    A_segment = r**2 / 2 * (theta - sin(theta))
    # area of circle
    A_circle = r**2 * pi
    # ratio of the areas
    ratio = A_segment / A_circle
    # remaining volume
    vol_remain = ratio * vt
    # return the truncated result
    return int(vol_remain)


Solve in Python:
To make Yalalovichik even more satisfied and happy, Jafar decided to invent Yalalovichik strings. A string is called a Yalalovichik string if the set of all of its distinct non-empty substrings is equal to the set of all of its distinct non-empty subsequences.
You are given a string S$S$. You need to find the number of its distinct non-empty substrings which are Yalalovichik strings.
Note: A string A$A$ is called a subsequence of a string B$B$ if A$A$ can be formed by erasing some characters (possibly none) from B$B$. A string A$A$ is called a substring of a string B$B$ if it can be formed by erasing some characters (possibly none) from the beginning of B$B$ and some (possibly none) from the end of B$B$. Two substrings or subsequences are considered different if they are different strings.

-----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 a single integer N=|S|$N = |S|$.
- The second line contains the string S$S$.

-----Output-----
For each test case, print a single line containing one integer — the number of distinct Yalalovichik substrings of S$S$.

-----Constraints-----
- 1≤T≤100$1 \le T \le 100$
- 1≤N≤106$1 \le N \le 10^6$
- the sum of N$N$ over all test cases does not exceed 2⋅106$2 \cdot 10^6$
- S$S$ contains only lowercase English letters

-----Example Input-----
1
3
xxx

-----Example Output-----
3

-----Explanation-----
Example case 1: The distinct Yalalovichik substrings are "x", "xx" and "xxx".

for _ in range(int(input())):
    n,s = int(input()),input().strip()
    previ,num,_s,dic = s[0],0,[],{}
    for i in s:
     if previ == i:
      num+=1
      continue
     _s.append((previ, num))
     if previ not in dic or dic[previ]<num:dic[previ] = num
     previ,num = i,1
    _s.append((previ, num))
    if previ not in dic or dic[previ]<num:dic[previ] = num
    sum1 = sum(dic.values())
    del dic, s
    l,dicc = [i for (i, j) in _s],{}
    congr = [(l[i], l[i+1]) for i in range(len(l)-1)]
    for i in range(len(congr)):
     if congr[i] not in dicc:dicc[congr[i]] = set()
     dicc[congr[i]].add( (_s[i][1], _s[i+1][1]) )
    sum2,ll = 0,[]
    for i in dicc.keys():
     sortedset,deleted =  sorted(list(dicc[i])),[]
     for k in range(1, len(sortedset)):
      j = sortedset[k]
      if j[1]>sortedset[k-1][1]:
       ind = k - 1


Solve in Python:
To participate in a prize draw each one gives his/her firstname.

Each letter of a firstname
has a value which is its rank in the English alphabet. `A` and `a` have rank `1`, `B` and `b` rank `2` and so on.

The *length* of the firstname is added to the *sum* of these ranks hence a number `som`.

An array of random weights is linked to the firstnames and each `som` is multiplied by
its corresponding weight to get what they call a `winning number`.

Example:
```
names: "COLIN,AMANDBA,AMANDAB,CAROL,PauL,JOSEPH"
weights: [1, 4, 4, 5, 2, 1]

PauL -> som = length of firstname + 16 + 1 + 21 + 12 = 4 + 50 -> 54
The *weight* associated with PauL is 2 so PauL's *winning number* is 54 * 2 = 108.
```
Now one can sort the firstnames in decreasing order of the `winning numbers`. When two
people have the same `winning number` sort them *alphabetically* by their firstnames.

### Task:

- parameters: `st` a string of firstnames, `we` an array of weights, `n` a rank

- return: the firstname of the participant whose rank is `n`
(ranks are numbered from 1)

### Example:
```
names: "COLIN,AMANDBA,AMANDAB,CAROL,PauL,JOSEPH"
weights: [1, 4, 4, 5, 2, 1]
n: 4

The function should return: "PauL"
```
# Notes:
- The weight array is at least as long as the number of names, it can be longer.

- If `st` is empty return "No participants".

- If n is greater than the number of participants then return "Not enough participants".

- See Examples Test Cases for more examples.

from string import ascii_lowercase

def rank(st, we, n):
    names = st.split(",")
    ranks = {}

    if st == "":
        return "No participants"

    if n > len(names):
        return "Not enough participants"

    for index, name in enumerate(names):
        som = len(name) + sum([ascii_lowercase.index(letter) + 1 for letter in name.lower()])
        ranks[name] = we[index] * som

    sort = sorted(list(ranks.items()), key=lambda x: (-x[1], x[0]))
    return [name for name, som in sort][n - 1]


Solve in Python:
To pass the series of gates guarded by the owls, Kenneth needs to present them each with a highly realistic portrait of one.  Unfortunately, he is absolutely rubbish at drawing, and needs some code to return a brand new portrait with a moment's notice.

All owl heads look like this:

    ''0v0''

Such beautiful eyes!
However, they differ in their plumage, which is always symmetrical, eg.:

       VVHVAV''0v0''VAVHVV

or

    YYAYAH8XH''0v0''HX8HAYAYY

So Kenneth needs a method that will take a garble of text generated by mashing at his keyboard (numbers and letters, but he knows how to avoid punctuation etc.) for a bit and give him a symmetrical owl with a lovely little face, with a truly symmetrical plumage made of uppercase letters and numbers.

(To be clear, the acceptable characters for the plumage are 8,W,T,Y,U,I,O,A,H,X,V and M.)

import re

def owl_pic(text):
    str = re.sub('[^ 8,W,T,Y,U,I,O,A,H,X,V,M]', '', text.upper())
    return str+"''0v0''"+str[::-1]


Solve in Python:
To protect people from evil,
a long and tall wall was constructed a few years ago.
But just a wall is not safe, there should also be soldiers on it,
always keeping vigil.
The wall is very long and connects the left and the right towers.
There are exactly N spots (numbered 1 to N) on the wall for soldiers.
The Kth spot is K miles far from the left tower and (N+1-K) miles from the right tower.

Given a permutation of spots P of {1, 2, ..., N}, soldiers occupy the N spots in that order.
The P[i]th spot is occupied before the P[i+1]th spot.
When a soldier occupies a spot, he is connected to his nearest soldier already placed to his left.
If there is no soldier to his left, he is connected to the left tower. The same is the case with right side.
A connection between two spots requires a wire of length equal to the distance between the two.

The realm has already purchased a wire of M miles long from Nokia,
possibly the wire will be cut into smaller length wires.
As we can observe, the total length of the used wire depends on the permutation of the spots P. Help the realm in minimizing the length of the unused wire. If there is not enough wire, output -1.

-----Input-----
First line contains an integer T (number of test cases, 1 ≤ T ≤ 10 ). Each of the next T lines contains two integers N M, as explained in the problem statement (1 ≤ N ≤ 30 , 1 ≤ M ≤ 1000).

-----Output-----
For each test case, output the minimum length of the unused wire, or -1 if the the wire is not sufficient.

-----Example-----
Input:
4
3 8
3 9
2 4
5 25

Output:
0
0
-1
5

Explanation:

In the 1st case, for example, the permutation P = {2, 1, 3} will use the exact 8 miles wires in total.

In the 2nd case, for example, the permutation P = {1, 3, 2} will use the exact 9 miles wires in total.

To understand the first two cases, you can see the following figures:

In the 3rd case, the minimum length of wire required is 5, for any of the permutations {1,2} or {2,1}, so length 4 is not sufficient.

In the 4th case, for the permutation...

import sys
first = True
memmin = {}
memmax = {}

def fmax(n):
 if n == 1: return 2
 if n == 0: return 0
 if n in memmax: return memmax[n]

 res = 0
 for i in range(n):
  cur = i + 1 + n - i + fmax(i) + fmax(n-i-1)
  if cur > res: res = cur

 memmax[n] = res
 return res

def fmin(n):
 if n == 1: return 2
 if n == 0: return 0
 if n in memmin: return memmin[n]

 res = 10 ** 9
 for i in range(n):
  cur = i + 1 + n - i + fmin(i) + fmin(n-i-1)
  if cur < res: res = cur

 memmin[n] = res
 return res

for line in sys.stdin:
 if first:
  first = False
  tc = int(line)
  continue

 tc -= 1
 if tc < 0: break

 n, m = list(map(int, line.split()))

 val1 = fmin(n)
 val2 = fmax(n)

 if m < val1: print(-1)
 else:
  if m > val2: print(m - val2)
  else: print(0)


Solve in Python:
To some string S, we will perform some replacement operations that replace groups of letters with new ones (not necessarily the same size).
Each replacement operation has 3 parameters: a starting index i, a source word x and a target word y.  The rule is that if x starts at position i in the original string S, then we will replace that occurrence of x with y.  If not, we do nothing.
For example, if we have S = "abcd" and we have some replacement operation i = 2, x = "cd", y = "ffff", then because "cd" starts at position 2 in the original string S, we will replace it with "ffff".
Using another example on S = "abcd", if we have both the replacement operation i = 0, x = "ab", y = "eee", as well as another replacement operation i = 2, x = "ec", y = "ffff", this second operation does nothing because in the original string S[2] = 'c', which doesn't match x[0] = 'e'.
All these operations occur simultaneously.  It's guaranteed that there won't be any overlap in replacement: for example, S = "abc", indexes = [0, 1], sources = ["ab","bc"] is not a valid test case.
Example 1:
Input: S = "abcd", indexes = [0,2], sources = ["a","cd"], targets = ["eee","ffff"]
Output: "eeebffff"
Explanation: "a" starts at index 0 in S, so it's replaced by "eee".
"cd" starts at index 2 in S, so it's replaced by "ffff".

Example 2:
Input: S = "abcd", indexes = [0,2], sources = ["ab","ec"], targets = ["eee","ffff"]
Output: "eeecd"
Explanation: "ab" starts at index 0 in S, so it's replaced by "eee".
"ec" doesn't starts at index 2 in the original S, so we do nothing.

Notes:

0 <= indexes.length = sources.length = targets.length <= 100
0 < indexes[i] < S.length <= 1000
All characters in given inputs are lowercase letters.

class Solution:
    def findReplaceString(self, S: str, indexes: List[int], sources: List[str], targets: List[str]) -> str:
        S = list(S)
        for i, s, t in sorted(zip(indexes,sources,targets),reverse=True):
            appl = all([(i + ind < len(S)) and (S[i+ind] == s[ind]) for ind in range(len(s))])
            if appl:
                S[i:i+len(s)] = list(t)
        return ''.join(S)


Solve in Python:
Toad Pimple has an array of integers $a_1, a_2, \ldots, a_n$.

We say that $y$ is reachable from $x$ if $x<y$ and there exists an integer array $p$ such that $x = p_1 < p_2 < \ldots < p_k=y$, and $a_{p_i}\, \&\, a_{p_{i+1}} > 0$ for all integers $i$ such that $1 \leq i < k$.

Here $\&$ denotes the bitwise AND operation.

You are given $q$ pairs of indices, check reachability for each of them.

-----Input-----

The first line contains two integers $n$ and $q$ ($2 \leq n \leq 300\,000$, $1 \leq q \leq 300\,000$) — the number of integers in the array and the number of queries you need to answer.

The second line contains $n$ space-separated integers $a_1, a_2, \ldots, a_n$ ($0 \leq a_i \leq 300\,000$) — the given array.

The next $q$ lines contain two integers each. The $i$-th of them contains two space-separated integers $x_i$ and $y_i$ ($1 \leq x_i < y_i \leq n$). You need to check if $y_i$ is reachable from $x_i$.

-----Output-----

Output $q$ lines. In the $i$-th of them print "Shi" if $y_i$ is reachable from $x_i$, otherwise, print "Fou".

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

Output
Fou
Shi
Shi

-----Note-----

In the first example, $a_3 = 0$. You can't reach it, because AND with it is always zero. $a_2\, \&\, a_4 > 0$, so $4$ is reachable from $2$, and to go from $1$ to $4$ you can use $p = [1, 2, 4]$.

from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop,heapify
import math
from collections import *
from functools import reduce,cmp_to_key
import sys
input = sys.stdin.readline

from itertools import accumulate
from functools import lru_cache

M = mod = 998244353
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)

def li():return [int(i) for i in input().rstrip('\n').split()]
def st():return input().rstrip('\n')
def val():return int(input().rstrip('\n'))
def li2():return [i for i in input().rstrip('\n')]
def li3():return [int(i) for i in input().rstrip('\n')]

n, q = li()

queue = [-1] * 20

ans = [[-1] * 20 for i in range(n + 1)]
l = li()
for i, curr in enumerate(l):

    for j in range(20):
        if curr >> j & 1:
            for k in range(20):
                ans[i][k] = max(ans[i][k], ans[queue[j]][k])
            ans[i][j] = i

    for j in range(20):queue[j] = max(queue[j], ans[i][j])

queries = []
for i in range(q):queries.append(li())
for i in range(q):
    a, b = queries[i]
    a -= 1
    b -= 1

    currans = 0

    for j in range(20):
        if (l[a] >> j) & 1 and ans[b][j] >= a:
            currans = 1
            break
    print('Shi' if currans else 'Fou')


Solve in Python:
Toad Rash has a binary string $s$. A binary string consists only of zeros and ones.

Let $n$ be the length of $s$.

Rash needs to find the number of such pairs of integers $l$, $r$ that $1 \leq l \leq r \leq n$ and there is at least one pair of integers $x$, $k$ such that $1 \leq x, k \leq n$, $l \leq x < x + 2k \leq r$, and $s_x = s_{x+k} = s_{x+2k}$.

Find this number of pairs for Rash.

-----Input-----

The first line contains the string $s$ ($1 \leq |s| \leq 300\,000$), consisting of zeros and ones.

-----Output-----

Output one integer: the number of such pairs of integers $l$, $r$ that $1 \leq l \leq r \leq n$ and there is at least one pair of integers $x$, $k$ such that $1 \leq x, k \leq n$, $l \leq x < x + 2k \leq r$, and $s_x = s_{x+k} = s_{x+2k}$.

-----Examples-----
Input
010101

Output
3

Input
11001100

Output
0

-----Note-----

In the first example, there are three $l$, $r$ pairs we need to count: $1$, $6$; $2$, $6$; and $1$, $5$.

In the second example, there are no values $x$, $k$ for the initial string, so the answer is $0$.

s = input()
le = len(s)
m = [le] * (le + 1)
ans = 0
for i in range(le - 1, -1, -1):
    m[i] = m[i + 1]
    k = 1
    while k * 2 + i < m[i]:
        if s[i] == s[i + k] and s[i] == s[i + 2 * k]:
            m[i] = i + 2 * k
        k += 1
    ans += le - m[i]
print(ans)


Solve in Python:
Toad Zitz has an array of integers, each integer is between $0$ and $m-1$ inclusive. The integers are $a_1, a_2, \ldots, a_n$.

In one operation Zitz can choose an integer $k$ and $k$ indices $i_1, i_2, \ldots, i_k$ such that $1 \leq i_1 < i_2 < \ldots < i_k \leq n$. He should then change $a_{i_j}$ to $((a_{i_j}+1) \bmod m)$ for each chosen integer $i_j$. The integer $m$ is fixed for all operations and indices.

Here $x \bmod y$ denotes the remainder of the division of $x$ by $y$.

Zitz wants to make his array non-decreasing with the minimum number of such operations. Find this minimum number of operations.

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \leq n, m \leq 300\,000$) — the number of integers in the array and the parameter $m$.

The next line contains $n$ space-separated integers $a_1, a_2, \ldots, a_n$ ($0 \leq a_i < m$) — the given array.

-----Output-----

Output one integer: the minimum number of described operations Zitz needs to make his array non-decreasing. If no operations required, print $0$.

It is easy to see that with enough operations Zitz can always make his array non-decreasing.

-----Examples-----
Input
5 3
0 0 0 1 2

Output
0

Input
5 7
0 6 1 3 2

Output
1

-----Note-----

In the first example, the array is already non-decreasing, so the answer is $0$.

In the second example, you can choose $k=2$, $i_1 = 2$, $i_2 = 5$, the array becomes $[0,0,1,3,3]$. It is non-decreasing, so the answer is $1$.

n,m = input().split()
n,m = int(n),int(m)
a = list(map(int, input().split()))
l,r = 0,m-1
def isOptimal(mid):
    prev = 0
    check=True
    for i in range(n):
            if prev<a[i]:
                if m-a[i]+prev>mid:
                    prev=a[i]
            else:
                if prev-a[i]>mid:
                    check=False
    return check
while l<=r:
    check=True
    mid=(l+r)//2
    prev=a[0]
    if isOptimal(mid):
        r=mid-1
    else:
        l=mid+1

check = isOptimal(l)
print(l*check+r*(not check))


Solve in Python:
Toby has found a game to entertain himself.The game is like this:

You are in a coordinate system initially at (0,0) and you are given a sequence of steps which lead to your destination.The steps are given in the form of directions: ’U’ ,’D’ , ’L’ and ‘R’ for up, down, left and right respectively.If you are at position (x,y) then:
- U:move to (x,y+1)
- D:move to (x,y-1)
- L:move to (x-1,y)
- R:move to (x+1,y)
The sequence is provided as a string ‘s’ of characters where $s_i$ $(1 \leq i \leq N)$ is one of the direction character as mentioned above.An example of a sequence of steps is:   UULRUDR

The destination according to this string is (1,2).

You want to remove maximum number of characters from the string such that the resulting string leads to the same destination as before.
For example in the example above we can remove characters at positions 1,3,4,6 and the resulting path will be UUR which will lead to the same destination i.e (1,2).so we reduced the number of steps by 4,and this is our score.
You need to get maximum score.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- First line of each testcase contains a single integer $N$,size of string.
- Second line of testcase contains a string $s$ of size $N$.

-----Output:-----
For each testcase, output a single line containing the maximum score possible.

-----Constraints-----
- $1 \leq T \leq 1000$
- $1 \leq N \leq 10^5$

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

7

ULUDLLU

4

RUUR

4

LRLR

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

0

4

-----EXPLANATION:-----
-
test case 1:
The final destination after moving according to the sequence is (-3,2).

One way is to remove characters at positions 3,4 and the resulting string will be ULLLU and destination still remains (-3,2).
-
test case 2: No character can be removed in this case.

from collections import Counter

x = int(input())
for i in range(0,x):
 len = int(input())
 string = str(input())
 dict = Counter(string)
 Ucount,Dcount,Lcount,Rcount = dict['U'],dict['D'],dict['L'],dict['R']
 ans = 0
 if Ucount>0:
  if Dcount>0:
   y = abs(Ucount-Dcount)
   ans += Ucount+Dcount - y
 if Lcount>0:
  if Rcount>0:
   y = abs(Rcount-Lcount)
   ans += Rcount + Lcount - y
 print(ans)


Solve in Python:
Today Chef wants to evaluate the dishes of his $N$ students. He asks each one to cook a dish and present it to him.
Chef loves his secret ingredient, and only likes dishes with at least $X$ grams of it.
Given $N$, $X$ and the amount of secret ingredient used by each student $A_i$, find out whether Chef will like at least one dish.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- The first line of each testcase contains two integers $N$
(number of students) and $X$ (minimum amount of secret ingredient that a dish must contain for Chef to like it).
- The next line contains $N$ space separated integers, $A_i$ denoting the amount of secret ingredient used by the students in their dishes.

-----Output:-----
For each testcase, print a single string "YES" if Chef likes at least one dish. Otherwise, print "NO". (Without quotes).

-----Constraints:-----
- $1 \leq T \leq 100$
- $1 \leq N \leq 1000$
- $1 \leq X \leq 1000000$
- $1 \leq A_i \leq 1000000$

-----Sample Input:-----
3
5 100
11 22 33 44 55
5 50
10 20 30 40 50
5 45
12 24 36 48 60

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

T=int(input())
for i in range(T):
 N,K=map(int,input().split())
 A=list(map(int,input().split()))[:N]
 for j in range(len(A)):
  if A[j]>=K:
   print("YES")
   break
 else:
  print("NO")


Solve in Python:
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:   +  a_{i} — add non-negative integer a_{i} to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.   -  a_{i} — delete a single occurrence of non-negative integer a_{i} from the multiset. It's guaranteed, that there is at least one a_{i} in the multiset.  ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left.

For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.

-----Input-----

The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform.

Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character c_{i} — the type of the corresponding operation. If c_{i} is equal to '+' or '-' then it's followed by a space and an integer a_{i} (0 ≤ a_{i} < 10^18) given without leading zeroes (unless it's 0). If c_{i} equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18.

It's guaranteed that there will be at least one query of type '?'.

It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.

-----Output-----

For each query of the third...


Solve in Python:
Today a plane was hijacked by a maniac. All the passengers of the flight are taken as hostage. Chef is also one of them.
He invited one of the passengers to play a game with him. If he loses the game, he will release all the passengers, otherwise he will kill all of them. A high risk affair it is.

Chef volunteered for this tough task. He was blindfolded by Hijacker. Hijacker brought a big black bag from his pockets. The contents of the bag is not visible. He tells Chef that the bag contains R red, G green and B blue colored balloons.

Hijacker now asked Chef to take out some balloons from the box such that there are at least K balloons of the same color and hand him over. If the taken out balloons does not contain at least K balloons of the same color, then the hijacker will shoot everybody. Chef is very scared and wants to leave this game as soon as possible, so he will draw the minimum number of balloons so as to save the passengers. Can you please help scared Chef to find out the minimum number of balloons he should take out.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.

The first line of each test case contains a three space-separated integers R, G and B.

The second line contains only one integer K.

-----Output-----
For each test case, output a single line containing one integer - the minimum number of balloons Chef need to take out from the bag.

-----Constraints-----
- 1 ≤ T ≤ 1000
- 1 ≤ R, G, B ≤ 109
- 1 ≤ K ≤ max{R, G, B}

-----Subtasks-----
- Subtask 1 (44 points): 1 ≤ R, G, B ≤ 10
- Subtask 2 (56 points):  No additional constraints

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

Output:
1
4

-----Explanation-----
Example case 2. In the worst-case scenario first three balloons will be of the three different colors and only after fourth balloon Chef will have two balloons of the same color. So, Chef might need to fetch 4 balloons

R=G=B=atmpt=counter=0
t=int(input())
for i in range(t):
 R,G,B=list(map(int,input().split()))
 k=int(input())
 if R<k:
  atmpt=R
 else:
  atmpt=k-1
 if G<k:
  atmpt=atmpt+G
 else:
  atmpt=atmpt+k-1
 if B<k:
  atmpt=atmpt+B
 else:
  atmpt=atmpt+k-1
 atmpt=atmpt+1
 print(atmpt)
 atmpt=0


Solve in Python:
Today is Chef's birthday. His mom decided to surprise him with a truly fantastic gift: his favourite binary string B. But, unfortunately, all the stocks of binary string B have been sold out, and only a binary string A (A ≠ B) is available in the market.
She purchases the string A and tries to convert it to string B by applying any of following three operations zero or more times.
AND Operation:
She will choose a pair of indices i and j such that i != j and perform following sequence of operations.

-  result = Ai & Aj
-  Ai = result & Ai
-  Aj = result & Aj

OR Operation:
She will choose a pair of indices i and j such that i != j and perform following sequence of operations.

-  result = Ai | Aj
-  Ai = result | Ai
-  Aj = result | Aj

XOR Operation:
She will choose a pair of indices i and j such that i != j and perform following sequence of operations.

-  result = Ai ^ Aj
-  Ai = result ^ Ai
-  Aj = result ^ Aj

Chef's mom is eagerly waiting to surprise him with his favourite gift and therefore, she wants to convert string A to string B as fast as possible. Can you please help her by telling her the minimum number of operations she will require? If it is impossible to do so, then let Chef's mom know about it.

-----Input-----
First line of input contains a single integer T denoting the number of test cases. T test cases follow.
First line of each test case, will contain binary string A.
Second line of each test case, will contain binary string B.

-----Output-----
For each test case, Print "Lucky Chef" (without quotes) in first line and minimum number of operations required to convert string A to sting B in second line if conversion is possible. Print "Unlucky Chef" (without quotes) in a new line otherwise.

-----Constraints-----
- 1 ≤ T ≤ 105
- 1 ≤ |A| ≤ 106
- 1 ≤ |B| ≤ 106
- A != B
- |A| = |B|
- sum of |A| over all test cases does not exceed 106
- sum of |B| over all test cases does not exceed 106

-----Subtasks-----
-  Subtask #1 (40 points) : Sum of |A| & |B| over all test cases does not...

# cook your dish here

t = int(input())
while t:
 A = input()
 B = input()
 mp1 = 0
 p1 = 0
 mp0 = 0
 p0 = 0
 for i in range(len(B)):
  if A[i]==B[i] and B[i]=='1':
   p1 += 1
  elif A[i]==B[i] and B[i]=='0':
   p0 += 1
  elif A[i]!=B[i] and B[i]=='1':
   mp0 += 1
  else:
   mp1 += 1
 #if A==B:
  #   con = True
  #  op = 0
 if mp0+p0==len(A) or mp1+p1==len(A):
  con = False
 elif mp1+p0>=mp0+p0:
  con = True
  op = mp1-mp0
  mp1 -= op
  op += mp1
 else:
  con = True
  op = mp0-mp1
  mp0 -= op
  op += mp0
 if con:
  print('Lucky Chef')
  print(op)
 else:
  print('Unlucky Chef')
 t -= 1


Solve in Python:
Today is Chef's birthday. His mom has surprised him with truly fruity gifts: 2 fruit baskets. The first basket contains N apples, and the second one contains M oranges. Chef likes apples and oranges very much but he likes them equally, and therefore, wants to have the minimum possible difference between the number of apples and oranges he has. To do so, he can purchase 1 apple or 1 orange by paying exactly 1 gold coin (that's some expensive fruit, eh?). Chef can purchase fruits at most K times (as he has only K gold coins in his pocket) to make the difference the minimum possible.
Our little Chef is busy in celebrating his birthday to the fullest, and therefore, he has handed this job to his best friend — you. Can you help him by finding the minimum possible difference he can achieve between the number of apples and orange he owns?

-----Input-----
The first line of input contains a single integer T denoting the number of test cases. The first and only line of each test case contains 3 space separated integers — N, M and K — denoting the number of apples, number of oranges, and number of gold coins our little Chef has.

-----Output-----
For each test case, output the minimum possible difference between the number of apples and oranges that Chef can achieve.

-----Constraints-----
- 1 ≤ T ≤ 100
- 1 ≤ N, M, K ≤ 100

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

Output
0
2
0

-----Explanation-----
- Test 1: Chef will buy 1 apple by paying 1 gold coin and will have equal number of apples and oranges.
- Test 2: Chef will buy 1 orange by paying 1 gold coin and will have 5 apples and 3 oranges.

t=int(input())
for i in range(t):
 a,o,g=map(int,input().split())
 diff=abs(a-o)
 if diff<=g:
  print(0)
 else:
  print(diff-g)


Solve in Python:
Today is Chocolate day and Kabir and Tara are visiting a Valentine fair. Upon arriving, they find a stall with an interesting game.
There are N$N$ jars having some chocolates in them. To win the game, one has to select the maximum number of consecutive jars such that the sum of count of chocolates in maximum and second maximum jar is less than or equal to k$k$ in that range.
Kabir wants to win the game so that he can gift the chocolates to Tara. You are a friend of Kabiir, help him win the game.
There will be at least one possible answer.
Note$Note$ :
- You have to select at least two jars.
- Count of chocolates in maximum and second maximum jar among selected consecutive jars may be equal.

-----Input:-----
- First line will contain T$T$, number of test cases.
- First line of each test case contains two space separated integers N,k$N, k$.
- Second line of each test case contains N$N$ space separated integer ai$a_i$ denotes number of chocolates in the jar.

-----Output:-----
For each test case print maximum number of jars.

-----Constraints:-----
- 1≤T≤10$1 \leq T \leq 10$
- 2≤N≤105$2 \leq N \leq 10^5$
- 1≤ai≤105$1 \leq a_i \leq 10^5$

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

1 3 3 1 1 5

-----Sample Output:-----
3

-----EXPLANATION:-----
You can select 3rd$3^{rd}$, 4th$4^{th}$, and 5th$5^{th}$ jar as the sum of max and second max is equal to 4 which is less then 5.

# cook your dish here
for _ in range(int(input())):
    n,k = list(map(int,input().split()))
    x = [int(i)for i in input().split()]
    a = []
    count = 0
    for i in x:
        a.append(i)
        t = a[:]
        t.sort()
        if len(t)>=2:
            if t[-1]+t[-2]<=k and len(t)>count:
                count = len(t)
            else:
                a.pop(0)
    print(count)


Solve in Python:
Today is rose day, batch mates of Kabir and Tara decided to celebrate this day by exchanging roses with each other.
Note:$Note:$ exchanging means both the boy and the girl will give rose to each other.
In the class there are B$B$ boys and G$G$ girls.
Exchange of rose will take place if and only if at least one of them hasn't received a rose from anyone else and a rose can be exchanged only once.
Tara has to bring maximum sufficient roses for everyone and is confused as she don't know how many roses to buy.You are a friend of Kabir, so help him to solve the problem so that he can impress Tara by helping her.

-----Input:-----
- First line will contain T$T$, number of test cases.
- Each test case contains two space separated integers B$B$ (Number of boys) and  G$G$ (Number of Girls).

-----Output:-----
For each test case, output in a single line the total number of roses exchanged.

-----Constraints:-----
- 1≤T≤105$1 \leq T \leq 10^5$
- 1≤B≤109$1 \leq B \leq 10^{9}$
- 1≤G≤109$1 \leq G \leq 10^{9}$

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

-----Sample Output:-----
8

n=int(input())
for i in range(n):
    l1=list(map(int,input().split()))
    b=min(l1[0],l1[1])
    g=max(l1[0],l1[1])
    sum1=g*2+(b-1)*2
    print(sum1)


Solve in Python:
Today is the planned day tor Thik and Ayvak's wedding. Kark is infatuated with Ayvak. He offers to play a game with Thik. Whosoever wins, will get to marry Ayvak. Ayvak, who values games of chance over all the other things in life, agrees to this.

Kark sets up an N by M grid (N rows, M columns), labelled from left to right and top to bottom consecutively with numbers from 1 to M*N, with 1 at the top left corner and M*N at the bottom right corner. For example, a labelled 3 by 6 grid looks as follows:

Kark has already painted K unit squares of the grid with a heart each. Next, Thik randomly picks a rectangle with sides on the grid lines, and having a positive area, with each valid rectangle having an equal probability of being chosen. Three distinct possibilities for Thik's rectangle in the 3 by 6 grid are shown below:

The nine different rectangles in a 2 by 2 grid are shown below:

If Thik's rectangle contains at least half of the hearts, Thik gets to marry Ayvak. Otherwise, Kark will marry Ayvak. Kark wants to know whether or not he has an advantage here, so he wants to know the expected value of the number of hearts a randomly chosen rectangle will cover. I'm sure that you have a good heart, so please, cover this job for him.

-----Input-----
The first line of input contains one integer T, the number of test cases.
For each test case, the first line contains 3 space-separated integers N, M, K, as described in the problem statement. The next line contains K space-separated integers, each a single number from 1 to M*N, representing a square that is painted with a heart. It is guaranteed that all K integers are distinct.

-----Output-----
Output T lines, each containing a single real number, containing the expected number of hearts that a randomly chosen rectangle will contain. The answer will be considered correct if its relative or absolute error does not exceed 10-6.

-----Constraints-----
- 1 ≤ T ≤ 5
- 1 ≤ N, M ≤ 107
- 1 ≤ K ≤ 105
- Each of the K integers representing a heart are between 1 and...

# cook your dish here
# cook your dish here
for i in range(int(input())):
    n,m,k=map(int,input().split())
    l,ans = list(map(int,input().split())),0
    for i in l:
        r=i//m + 1;c=i%m
        if(c==0):c=m;r-=1
        ans+=r*(n+1-r)*c*(m+1-c)
    ans/=((n+1)*(m+1)*n*m)//4
    print(ans)


Solve in Python:
Today the kindergarten has a new group of $n$ kids who need to be seated at the dinner table. The chairs at the table are numbered from $1$ to $4n$. Two kids can't sit on the same chair. It is known that two kids who sit on chairs with numbers $a$ and $b$ ($a \neq b$) will indulge if:   $gcd(a, b) = 1$ or,  $a$ divides $b$ or $b$ divides $a$.

$gcd(a, b)$ — the maximum number $x$ such that $a$ is divisible by $x$ and $b$ is divisible by $x$.

For example, if $n=3$ and the kids sit on chairs with numbers $2$, $3$, $4$, then they will indulge since $4$ is divided by $2$ and $gcd(2, 3) = 1$. If kids sit on chairs with numbers $4$, $6$, $10$, then they will not indulge.

The teacher really doesn't want the mess at the table, so she wants to seat the kids so there are no $2$ of the kid that can indulge. More formally, she wants no pair of chairs $a$ and $b$ that the kids occupy to fulfill the condition above.

Since the teacher is very busy with the entertainment of the kids, she asked you to solve this problem.

-----Input-----

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

Each test case consists of one line containing an integer $n$ ($1 \leq n \leq 100$) — the number of kids.

-----Output-----

Output $t$ lines, which contain $n$ distinct integers from $1$ to $4n$ — the numbers of chairs that the kids should occupy in the corresponding test case. If there are multiple answers, print any of them. You can print $n$ numbers in any order.

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

Output
6 4
4 6 10
14 10 12 8

# map(int, input().split())
def main():
    n = int(input())
    for i in range(4 * n, 2 * n, -2):
        print(i, end = ' ')
    print('')

rw = int(input())
for wewq in range(rw):
    main()


Solve in Python:
Today was a sad day. Having bought a new beard trimmer, I set it to the max setting and shaved away at my joyous beard. Stupidly, I hadnt checked just how long the max setting was, and now I look like Ive just started growing it!

Your task, given a beard represented as an arrayof arrays, is to trim the beard as follows:

['|', 'J', '|', '|'],
['|', '|', '|', 'J'],
['...', '...', '...', '...'];

To trim the beard use the following rules:

trim any curled hair --> replace 'J' with '|'
trim any hair from the chin (last array) --> replace '|' or 'J' with '...'

All sub arrays will be same length. Return the corrected array of arrays

def trim(a):
    return [["|" if y == "J" else y for y in x] for x in a[:-1]] + [["..."] * len(a[0])]