Solve in Python:
Today, Chef decided to cook some delicious meals from the ingredients in his kitchen. There are $N$ ingredients, represented by strings $S_1, S_2, \ldots, S_N$. Chef took all the ingredients, put them into a cauldron and mixed them up.
In the cauldron, the letters of the strings representing the ingredients completely mixed, so each letter appears in the cauldron as many times as it appeared in all the strings in total; now, any number of times, Chef can take one letter out of the cauldron (if this letter appears in the cauldron multiple times, it can be taken out that many times) and use it in a meal. A complete meal is the string "codechef". Help Chef find the maximum number of complete meals he can make!

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- $N$ lines follow. For each $i$ ($1 \le i \le N$), the $i$-th of these lines contains a single string $S_i$.

-----Output-----
For each test case, print a single line containing one integer — the maximum number of complete meals Chef can create.

-----Constraints-----
- $1 \le T \le 100$
- $1 \le N \le 100$
- $|S_1| + |S_2| + \ldots + |S_N| \le 1,000$
- each string contains only lowercase English letters

-----Example Input-----
3
6
cplusplus
oscar
deck
fee
hat
near
5
code
hacker
chef
chaby
dumbofe
5
codechef
chefcode
fehcedoc
cceeohfd
codechef

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

-----Explanation-----
Example case 1: After mixing, the cauldron contains the letter 'c' 3 times, the letter 'e' 4 times, and each of the letters 'o', 'd', 'h' and 'f' once. Clearly, this is only enough for one "codechef" meal.
Example case 2: After mixing, the cauldron contains the letter 'c' 4 times, 'o' 2 times, 'd' 2 times, 'e' 4 times, 'h' 3 times and 'f' 2 times, which is enough to make 2 meals.

# cook your dish here
for i in range(int(input())):
 n = int(input())
 l = []
 c= 0
 o= 0
 d= 0
 e= 0
 h= 0
 f= 0
 for i in range(n):
  s = input()
  for i in range(len(s)):
   if(s[i] == "c"):
    c = c+1
   elif(s[i]== "o"):
    o = o+1
   elif(s[i] == "d"):
    d = d+1
   elif(s[i] == "e"):
    e = e+1
   elif(s[i] == "h"):
    h = h+1
   elif(s[i] == "f"):
    f = f+1
 c = c//2
 e = e//2
 l = [c,o,d,e,h,f]
 print(min(l))


Solve in Python:
Today, Chef has a fencing job at hand and has to fence up a surface covering N$N$ points.
To minimize his work, he started looking for an algorithm that had him fence the least amount of length.
He came up with the Convex Hull algorithm, but soon realized it gave him some random shape to fence. However, Chef likes rectangles and has a favourite number M$M$.
Help him find the minimum perimeter he has to fence if he wants to fence a rectangle, with slope of one of the sides as M$M$, to cover all the points.

-----Input:-----
- The first line contains two integers N$N$ and M$M$, the number of points and the Chef's favourite Number.
- The next n lines contain two space separated integers X$X$ and Y$Y$, the coordinates of the point.

-----Output:-----
Print a single decimal number, denoting the perimeter of the rectangle. Answer will considered correct if it has absolute error less than 10−6$10^{-6}$.

-----Constraints-----
- 2≤N≤1000000$2 \leq N \leq 1000000$
- −1000≤M≤1000$-1000 \leq M \leq 1000$
- −1000000≤X≤1000000$-1000000 \leq X \leq 1000000$
- −1000000≤Y≤1000000$-1000000 \leq Y \leq 1000000$

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

-----Sample Output:-----
5.656854249492380

-----Note:-----
- As the input size is large, it is recommended to use Fast IO.

import math
import numpy as np

n,m = map(int, input().split())
hyp = math.sqrt(1+m*m)
cosx = 1/hyp
sinx = m/hyp

pts = np.array([list(map(int, input().split())) for i in range(n)]).T

ptsx = cosx*pts[0]+sinx*pts[1]
ptsy = cosx*pts[1]-sinx*pts[0]

w = max(ptsx)-min(ptsx)
l = max(ptsy)-min(ptsy)

print(2*l+2*w)


Solve in Python:
Today, puppy Tuzik is going to a new dog cinema. He has already left his home and just realised that he forgot his dog-collar! This is a real problem because the city is filled with catchers looking for stray dogs.
A city where Tuzik lives in can be considered as an infinite grid, where each cell has exactly four neighbouring cells: those sharing a common side with the cell. Such a property of the city leads to the fact, that the distance between cells (xA, yA) and (xB, yB) equals |xA - xB| + |yA - yB|.
Initially, the puppy started at the cell with coordinates (0, 0). There are N dog-catchers located at the cells with the coordinates (xi, yi), where 1 ≤ i ≤ N. Tuzik's path can be described as a string S of M characters, each of which belongs to the set {'D', 'U', 'L', 'R'} (corresponding to it moving down, up, left, and right, respectively). To estimate his level of safety, Tuzik wants to know the sum of the distances from each cell on his path to all the dog-catchers. You don't need to output this sum for the staring cell of the path (i.e. the cell with the coordinates (0, 0)).

-----Input-----
The first line of the input contains two integers N and M.
The following N lines contain two integers xi and yi each, describing coordinates of the dog-catchers.
The last line of the input contains string S of M characters on the set {'D', 'U', 'L', 'R'}.
- 'D' - decrease y by 1
- 'U' - increase y by 1
- 'L' - decrease x by 1
- 'R' - increase x by 1

-----Output-----
Output M lines: for each cell of the path (except the starting cell), output the required sum of the distances.

-----Constraints-----
- 1 ≤ N ≤ 3 ✕ 105
- 1 ≤ M ≤ 3 ✕ 105
- -106 ≤ xi, yi ≤ 106

-----Example-----
Input:
2 3
1 2
0 1
RDL

Output:
4
6
6

-----Explanation-----

Initially Tuzik stays at cell (0, 0). Let's consider his path:

- Move 'R' to the cell (1, 0). Distance to the catcher (1, 2) equals 2, distance to the catcher (0, 1) equals 2, so the total distance equals 4
- Move 'D' to the cell (1, -1). Distance to the catcher (1, 2) equals 3,...

# cook your dish here
from sys import stdin,stdout
a,b=list(map(int,stdin.readline().split()))
left=[]
top=[]
for i in range(a):
 c,d=list(map(int,stdin.readline().split()))
 left.append(c)
 top.append(d)
left.sort()
top.sort()
from bisect import bisect_right as br
from bisect import bisect_left as bl
row=0
col=0
total=0
cons_x=0
cons_y=0
for i in range(len(left)):
 cons_x+=(abs(left[i]))
 cons_y+=(abs(top[i]))
total=cons_x+cons_y
cc=stdin.readline().rstrip()
for i in cc:
 if i=="R":
  kk=br(left,col)
  cons_x=(cons_x+kk-(a-kk))
  col+=1
 if i=="L":
  kk=bl(left,col)
  cons_x=(cons_x+(a-kk)-kk)
  col-=1
 if i=="U":
  kk=br(top,row)
  cons_y=(cons_y+kk-(a-kk))
  row+=1
 if i=="D":
  kk=bl(top,row)
  cons_y=(cons_y+(a-kk)-kk)
  row-=1
 stdout.write(str(cons_x+cons_y))
 stdout.write("\n")


Solve in Python:
Today, the bookstore owner has a store open for customers.length minutes.  Every minute, some number of customers (customers[i]) enter the store, and all those customers leave after the end of that minute.
On some minutes, the bookstore owner is grumpy.  If the bookstore owner is grumpy on the i-th minute, grumpy[i] = 1, otherwise grumpy[i] = 0.  When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise they are satisfied.
The bookstore owner knows a secret technique to keep themselves not grumpy for X minutes straight, but can only use it once.
Return the maximum number of customers that can be satisfied throughout the day.

Example 1:
Input: customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], X = 3
Output: 16
Explanation: The bookstore owner keeps themselves not grumpy for the last 3 minutes.
The maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16.

Note:

1 <= X <= customers.length == grumpy.length <= 20000
0 <= customers[i] <= 1000
0 <= grumpy[i] <= 1

class Solution:
    def maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int:
        start=0
        end=X
        ans=0
        for i in range(len(grumpy)):
            if grumpy[i]==0:
                ans+=customers[i]
        t=0
        for i in range(X):
            if grumpy[i]==1:
                t+=customers[i]
        maxs=0
        while end<len(grumpy)+1:
            if t>maxs:
                maxs=t
            if end==len(grumpy):
                break
            if grumpy[start]==1:
                t-=customers[start]
            if grumpy[end]==1:
                t+=customers[end]
            start+=1
            end+=1
        return ans+maxs


Solve in Python:
Tom  has finally taken over the business empire and now looking for
a new Name of the business to make a new start.

Joe  (Tom's dear friend)  suggested a string $S$  consisting of
Uppercase and lowercase letters

Tom wants to make some changes as per the following criteria:

1) String should $not$ have any vowels .

2) Every other uppercase consonant(other characters except vowels) should
be in lowercase

For ex:

If the consonant character is Z then it should be z

3)  There should be  a character "." before each consonant.

Help Tom to make the required Changes.

-----Input:-----
- First line will contain string  $S$,This string only consists of uppercase and lowercase letters.

-----Output:-----
Print the resulting string. It is guaranteed that this string is not empty.

-----Constraints-----
- Length of string is in [1 .. 100]

-----Sample Input:-----
$CodeSprInT$

-----Sample Output:-----
.c.d.s.p.r.n.t

-----EXPLANATION:-----
C is a consonant and it is in uppercase so turn it in lower case and add a “.” before it
o is a vowel so it is deleted
d  is a consonant and in lowercase so just  add a “.” before it
e  is a vowel so it is deleted
S is a consonant and it is in uppercase so turn it in lower case and add a “.” before it
p is a consonant and in lowercase so just  add a “.” before it
r is a consonant and in lowercase so just  add a “.” before it
I is a vowel so it is deleted
n is a consonant and in lowercase so just  add a “.” before it
T is a consonant and it is in uppercase so turn it in lower case and add a “.” before it

s = input().lower()
vow = ["a", "e", "i", "o", "u", "y"]
ans = ""
for ch in s:
    if ch in vow:
        continue
    if ch.isalpha():
        ans += "." + ch
print(ans)


Solve in Python:
Tomya is a girl. She loves Chef Ciel very much.

Today, too, Tomya is going to Ciel's restaurant.
Of course, Tomya would like to go to Ciel's restaurant as soon as possible.
Therefore Tomya uses one of the shortest paths from Tomya's house to Ciel's restaurant.
On the other hand, Tomya is boring now to use the same path many times.
So Tomya wants to know the number of shortest paths from Tomya's house to Ciel's restaurant.
Your task is to calculate the number under the following assumptions.

This town has N intersections and M two way roads.
The i-th road connects from the Ai-th intersection to the Bi-th intersection, and its length is

Ci.
Tomya's house is in the 1st intersection, and Ciel's restaurant is in the N-th intersection.

-----Input-----

The first line contains an integer T, the number of test cases.
Then T test cases follow.
The first line of each test case contains 2 integers N, M.
Then next M lines contains 3 integers denoting Ai, Bi and Ci.

-----Output-----

For each test case, print the number of shortest paths from Tomya's house to Ciel's restaurant.

-----Constraints-----

1 ≤ T ≤ 10

2 ≤ N ≤ 10

1 ≤ M ≤ N ∙ (N – 1) / 2

1 ≤ Ai, Bi ≤ N

1 ≤ Ci ≤ 10
Ai ≠ Bi

If i ≠ j and Ai = Aj, then Bi ≠ Bj

There is at least one path from Tomya's house to Ciel's restaurant.

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

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

-----Explanations-----

In the first sample, only one shortest path exists, which is 1-3.

In the second sample, both paths 1-2-3 and 1-3 are the shortest paths.

t=eval(input())
def func(k,n,x,dist,graph):
 if k==n:
  x+=[dist[n]]
  return
 for i in range(1,n+1):
  if graph[k][i]!=0 and dist[i]==-1:
   dist[i]=dist[k]+graph[k][i]
   func(i,n,x,dist,graph)
   dist[i]=-1

while t:
 graph=[[0 for i in range(11)]for j in range(11)]
 v,e=list(map(int,input().split()))
 for i in range(e):
  x,y,w=list(map(int,input().split()))
  graph[x][y]=w
  graph[y][x]=w
 x=[]
 dist=[-1]*(v+1)
 dist[1]=0
 func(1,v,x,dist,graph)
 x.sort()
 val=x[0]
 ans=0
 for i in range(len(x)):
  if val==x[i]:
   ans+=1
 print(ans)
 t-=1


Solve in Python:
Tomya is a girl. She loves Chef Ciel very much.

Tomya like a positive integer p, and now she wants to get a receipt of Ciel's restaurant whose total price is exactly p.
The current menus of Ciel's restaurant are shown the following table.
Name of Menupriceeel flavored water1deep-fried eel bones2clear soup made with eel livers4grilled eel livers served with grated radish8savory egg custard with eel16eel fried rice (S)32eel fried rice (L)64grilled eel wrapped in cooked egg128eel curry rice256grilled eel over rice512deluxe grilled eel over rice1024eel full-course2048

Note that the i-th menu has the price 2i-1 (1 ≤ i ≤ 12).

Since Tomya is a pretty girl, she cannot eat a lot.
So please find the minimum number of menus whose total price is exactly p.
Note that if she orders the same menu twice, then it is considered as two menus are ordered. (See Explanations for details)

-----Input-----

The first line contains an integer T, the number of test cases.
Then T test cases follow.
Each test case contains an integer p.

-----Output-----

For each test case, print the minimum number of menus whose total price is exactly p.

-----Constraints-----

1 ≤ T ≤ 5

1 ≤ p ≤ 100000 (105)

There exists combinations of menus whose total price is exactly p.

-----Sample Input-----
4
10
256
255
4096

-----Sample Output-----
2
1
8
2

-----Explanations-----

In the first sample, examples of the menus whose total price is 10 are the following:

1+1+1+1+1+1+1+1+1+1 = 10 (10 menus)

1+1+1+1+1+1+1+1+2 = 10 (9 menus)

2+2+2+2+2 = 10 (5 menus)

2+4+4 = 10 (3 menus)

2+8 = 10 (2 menus)

Here the minimum number of menus is 2.

In the last sample, the optimal way is 2048+2048=4096 (2 menus).
Note that there is no menu whose price is 4096.

N=int(input())
for i in range(N):
    p=[2048,1024,512,256,128,64,32,16,8,4,2,1]
    a=int(input())
    count=0
    for i in p:
        if(a>=i):
            count=count+a//i
            a=a%i
    print(count)


Solve in Python:
Tonight, Chef would like to hold a party for his $N$ friends.
All friends are invited and they arrive at the party one by one in an arbitrary order. However, they have certain conditions — for each valid $i$, when the $i$-th friend arrives at the party and sees that at that point, strictly less than $A_i$ other people (excluding Chef) have joined the party, this friend leaves the party; otherwise, this friend joins the party.
Help Chef estimate how successful the party can be — find the maximum number of his friends who could join the party (for an optimal choice of the order of arrivals).

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

-----Output-----
For each test case, print a single line containing one integer — the maximum number of Chef's friends who could join the party.

-----Constraints-----
- $1 \le T \le 1,000$
- $1 \le N \le 10^5$
- the sum of $N$ over all test cases does not exceed $10^6$

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

-----Example Output-----
2
4
0

-----Explanation-----
Example case 1: Chef has two friends. Both of them do not require anyone else to be at the party before they join, so they will both definitely join the party.
Example case 2: At the beginning, friends $3$ and $4$ can arrive and join the party, since they do not require anyone else to be at the party before they join. After that, friend $2$ can arrive; this friend would see that there are two people at the party and therefore also join. Then, friend $1$ will also join, so in the end, there would be $4$ people attending the party.
Example case 3: No one will attend the party because each of Chef's friends will find zero people at the party and leave, regardless of the order in which they arrive.

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

 tg=0
 for i in sorted(l):
  if(i<=tg):
   tg+=1
 print(tg)


Solve in Python:
Tracy loves Donuts. She purchased a lots of Donuts for her birthday party. She learnt to calculate the area of the circle a few days back and she is fascinated to know the area of the donuts as well !! Help her finding the area of the Donuts…..

-----Input:-----
- First line will contain, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, where in you have to provide the RADIUS of the Donuts.

-----Output:-----
For each testcase, output in a single line answer is the AREA of the Donut.

-----Constraints-----
1 <= Radius <= 20.

-----Sample Input:-----
2
5
12

-----Sample Output:-----
78.5

452.16

t=int(input())
while(t):
    r=int(input())
    print(3.14*r*r)
    t-=1


Solve in Python:
Tranform of input array of zeros and ones to array in which counts number of continuous ones:

[1, 1, 1, 0, 1] -> [3,1]

from itertools import groupby

def ones_counter(nums):
    return [sum(g) for k, g in groupby(nums) if k]


Solve in Python:
Transpose means is to interchange rows and columns of a two-dimensional array matrix.

[A^(T)]ij=[A]ji

ie:
Formally, the i th row, j th column element of AT is the j th row, i th column element of A:

Example :

```
[[1,2,3],[4,5,6]].transpose() //should return [[1,4],[2,5],[3,6]]
```

Write a prototype transpose to array in JS or add a .transpose method in Ruby or create a transpose function in Python so that any matrix of order ixj 2-D array returns transposed Matrix of jxi .

Link:  To understand array prototype

def transpose(arr):
    tran_each = []
    tran_com = []
    if len(arr) > 0 and len(arr[0]) > 0:
        n_row = len(arr[0])
        n_col = len(arr)
        for j in range(n_row):
            for i in range(n_col):
                tran_each.append(arr[i][j])
            tran_com.append(tran_each)
            tran_each = []
        return tran_com
    elif len(arr) > 0:
        return [[]]
    else:
        return []


Solve in Python:
Triangular number is the amount of points that can fill equilateral triangle.

Example: the number 6 is a triangular number because all sides of a triangle has the same amount of points.

```
Hint!
T(n) = n * (n + 1) / 2,
n - is the size of one side.
T(n) - is the triangular number.
```

Given a number 'T' from interval [1; 2147483646], find if it is triangular number or not.

from math import sqrt
def is_triangular(t):
    n = (sqrt(8 * t + 1)-1)/2
    return False if n - int(n) > 0 else True


Solve in Python:
Triangular numbers count the number of objects that can form an equilateral triangle. The nth triangular number forms an equilateral triangle with n dots on each side (including the vertices).
Here is a graphic example for the triangular numbers of 1 to 5:
```
n=1: triangular number: 1
*

n=2: triangular number: 3
 *
* *

n=3: triangular number: 6
  *
 * *
* * *

n=4: triangular number: 10
    *
   * *
  * * *
 * * * *

 n=5: triangular number: 15
      *
     * *
    * * *
   * * * *
  * * * * *
```

Your task is to implement a function ```triangular_range(start, stop)``` that returns a dictionary of all numbers as keys and the belonging triangular numbers as values, where the triangular number is in the range start, stop (including start and stop).
For example, ```triangular_range(1, 3)``` should return ```{1: 1, 2: 3}``` and ```triangular_range(5, 16)``` should return ```{3: 6, 4: 10, 5: 15}```.

from math import ceil

def root(n): return ((1+8*n)**.5-1)/2

def triangular_range(s,e):
    return {i: -~i*i>>1 for i in range(ceil(root(s)), int(root(e))+1)}


Solve in Python:
Trigrams are a special case of the n-gram, where n is 3. One trigram is a continious sequence of 3 chars in phrase. [Wikipedia](https://en.wikipedia.org/wiki/Trigram)

 - return all trigrams for the given phrase
 - replace spaces with \_
 - return an empty string for phrases shorter than 3

Example:

trigrams('the quick red') ==  the he\_ e\_q \_qu qui uic ick ck\_ k\_r \_re red

def trigrams(phrase):
    if len(phrase) < 3: return ''
    phrase = phrase.replace(" ", "_")
    chars = [x for x in phrase]
    trigram = []
    for x in range(1, len(chars) - 1):
        trigram.append(chars[x-1] + chars[x] + chars[x+1])
    return ' '.join(trigram)


Solve in Python:
Truncate the given string (first argument) if it is longer than the given maximum length (second argument). Return the truncated string with a `"..."` ending.

Note that inserting the three dots to the end will add to the string length.

However, if the given maximum string length num is less than or equal to 3, then the addition of the three dots does not add to the string length in determining the truncated string.

## Examples
```
('codewars', 9)  ==>  'codewars'
('codewars', 7)  ==>  'code...'
('codewars', 2)  ==>  'co...'
```

[Taken from FCC](https://www.freecodecamp.com/challenges/truncate-a-string)

def truncate_string(str,n):
    if len(str) <= n:
        return str
    if n <= 3:
        return str[:n] + '...'
    return str[:n-3] + '...'


Solve in Python:
Try guessing the statement from this picture:  $3$

You are given a non-negative integer $d$. You have to find two non-negative real numbers $a$ and $b$ such that $a + b = d$ and $a \cdot b = d$.

-----Input-----

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

Each test case contains one integer $d$ $(0 \le d \le 10^3)$.

-----Output-----

For each test print one line.

If there is an answer for the $i$-th test, print "Y", and then the numbers $a$ and $b$.

If there is no answer for the $i$-th test, print "N".

Your answer will be considered correct if $|(a + b) - a \cdot b| \le 10^{-6}$ and $|(a + b) - d| \le 10^{-6}$.

-----Example-----
Input
7
69
0
1
4
5
999
1000

Output
Y 67.985071301 1.014928699
Y 0.000000000 0.000000000
N
Y 2.000000000 2.000000000
Y 3.618033989 1.381966011
Y 997.998996990 1.001003010
Y 998.998997995 1.001002005


Solve in Python:
Tuzik and Vanya are playing the following game.
They have an N × M board and a chip to indicate the current game position. The chip can be placed on any one cell of the game board, each of which is uniquely identified by an ordered pair of positive integers (r, c), where 1 ≤ r ≤ N is the row number and 1 ≤ c ≤ M is the column number.
Initially, the chip is placed at the cell identified as (1, 1). For his move, a player can move it either 1, 2 or 3 cells up, or 1 or 2 cells to the right. The player who can not move the chip loses. In other words, a player suffers defeat if the chip is placed in the cell (N, M) at the start of his turn.
Tuzik starts the game. You have to determine who will win the game if both players play optimally.

-----Input-----
The first line contains an integer T denoting the number of tests. Each of the following T lines contain two integers N and M.

-----Output-----
For each test output "Tuzik" or "Vanya" on a separate line, indicating who will win the game.

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

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

Output:
Tuzik
Vanya

-----Explanation-----Test case 1: On his first turn Tuzik moves chip 3 cells up to the cell (4, 1). On his turn Vanya can move chip only right to the cell (4, 2) or to the cell (4, 3) and after that Tuzik moves it to (4, 4) and finishes the game.

Test case 2: On his first Turn Tuzik can move chip to the cell (2, 1) or (1, 2), but on his next turn Vanya moves it to (2, 2) and wins the game.

cases = int(input())
for _ in range(cases):
 rows, cols = map(int, input().split())
 if (cols - 1) % 3 == 0 and (rows - 1) % 4 == 0: print('Vanya')
 elif (cols - 1) % 3 != 0 and (rows - 1) % 4 == 0: print('Tuzik')
 elif (cols - 1) % 3 == 0 and (rows - 1) % 4 != 0: print('Tuzik')
 else:
  if (cols - 1) % 3 == 1 and (rows - 1) % 4 == 1: print('Vanya')
  elif (cols - 1) % 3 == 2 and (rows - 1) % 4 == 2: print('Vanya')
  else: print('Tuzik')


Solve in Python:
Tweedle-Dee and Tweedle-Dum are playing a fierce match of binary Nim. This novel game is played with $N$ stacks, each of them containing only $1$-s and $0$-s.
Just like in normal Nim, Tweedle-Dee and Tweedle-Dum alternate turns; in their turn, a player must choose one non-empty stack and remove a positive number of elements from the top of this stack. However, Tweedle-Dee may only choose a stack with $0$ at the top (and remove elements from it afterwards), and similarly, Tweedle-Dum may only choose a stack with $1$ at the top. the player that cannot make a move loses
Suzumo does not want to wait for the end of the game, so given the starting player he asks you to determine the winner. Remember that Tweedle-Dee and Tweedle-Dum are legendary grandmasters of combinatorial games, so both always play optimally.

-----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 an integer $N$, a string $S$ denoting the number of stacks, the player that starts the game, respectively.
- Each of the following $N$ lines contains a single binary string $B$ representing a stack; the first character of $B$ corresponds to the top element of the stack and the last character to the bottom element.

-----Output-----
For each test case, print a single line containing the string "Dee" if Tweedle-Dee wins the match or "Dum" if Tweedle-Dum wins.

-----Constraints-----
- $1 \le T \le 500$
- $1 \le N \le 50$
- $1 \le |B| \le 50$
- each character in $B$ is either '1' or '0'
- $S$ is either "Dee" or "Dum"

-----Example Input-----
2
2 Dee
101
010
2 Dum
101
010

-----Example Output-----
Dum
Dee

for _ in range(int(input())):
 a,b=input().split()
 a=int(a)
 onec=0
 zeroc=0
 for i in range(a):
  stk=input()
  if stk[0]=='0':
   zeroc+=stk.count('0')
  else:
   onec+=stk.count('1')
 if b=='Dee':
  if zeroc>onec:
   print('Dee')
  else:
   print('Dum')
 else:
  if onec>zeroc:
   print('Dum')
  else:
   print('Dee')


Solve in Python:
Two Joggers
===

Description
---
Bob and Charles are meeting for their weekly jogging tour. They both start at the same spot called "Start" and they each run a different lap, which may (or may not) vary in length. Since they know each other for a long time already, they both run at the exact same speed.

Illustration
---
Example where Charles (dashed line) runs a shorter lap than Bob:

![Example laps](http://www.haan.lu/files/7713/8338/6140/jogging.png "Example laps")

Task
---
Your job is to complete the function **nbrOfLaps(x, y)** that, given the length of the laps for Bob and Charles, finds the number of laps that each jogger has to complete before they meet each other again, at the same time, at the start.

The function takes two arguments:

1. The length of Bob's lap (larger than 0)
2. The length of Charles' lap (larger than 0)

The function should return an array (`Tuple` in C#) containing exactly two numbers:

1. The first number is the number of laps that Bob has to run
2. The second number is the number of laps that Charles has to run

Examples:
```python
nbr_of_laps(5, 3) # returns (3, 5)
nbr_of_laps(4, 6) # returns (3, 2)
```

def nbr_of_laps(x, y):
    a, b = x, y
    remain = a % b
    while remain > 0:
        a, b = b, remain
        remain = a % b
    lcm = x * y / b
    return lcm / x, lcm / y


Solve in Python:
Two cheeky thieves (Chef being one of them, the more talented one of course) have came across each other in the underground vault of the State Bank of Churuland. They are shocked! Indeed, neither expect to meet a colleague in such a place with the same intentions to carry away all the money collected during Churufest 2015.

They have carefully counted a total of exactly 1 billion (109) dollars in the bank vault. Now they must decide how to divide the booty. But there is one problem: the thieves have only M minutes to leave the bank before the police arrives. Also, the more time they spend in the vault, the less amount could carry away from the bank. Formally speaking, they can get away with all of the billion dollars right now, but after t minutes they can carry away only  1 billion * pt dollars, where p is some non-negative constant less than or equal to unity, and at t = M, they get arrested and lose all the money.
They will not leave the vault until a decision on how to divide the money has been made.

The money division process proceeds in the following way: at the beginning of each minute starting from the 1st (that is, t = 0), one of them proposes his own way to divide the booty. If his colleague agrees, they leave the bank with pockets filled with the proposed amounts of dollars. If not, the other one proposes his way at the next minute etc. To escape arrest, they can only propose plans till the beginning of the Mth minute (i.e., till t = M-1).
Each thief wants to maximize his earnings, but if there are two plans with the same amounts for him, he would choose the one which leads to a larger total amount of stolen dollars.

Chef is about to start this procedure, and he is the first to propose a plan. You are wondering what will be the final division of money, if each thief chooses the optimal way for himself and money is considering real.

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


Solve in Python:
Two fishing vessels are sailing the open ocean, both on a joint ops fishing mission.

On a high stakes, high reward expidition - the ships have adopted the strategy of hanging a net between the two ships.

The net is **40 miles long**. Once the straight-line distance between the ships is greater than 40 miles, the net will tear, and their valuable sea harvest will be lost! We need to know how long it will take for this to happen.

Given the bearing of each ship, find the time **in minutes** at which the straight-line distance between the two ships reaches **40 miles**. Both ships travel at **90 miles per hour**. At time 0, assume the ships have the same location.

Bearings are defined as **degrees from north, counting clockwise**.
These will be passed to your function as integers between **0 and 359** degrees.
Round your result to **2 decmal places**.

If the net never breaks, return float('inf')

Happy sailing!

from math import *

def find_time_to_break(a,b):
    vShips, netLength = 90/60, 40
    return float('inf') if a==b else netLength/2 / (vShips * sin(radians(abs(b-a)/2)))


Solve in Python:
Two friends David and Rojer were preparing for their weekly class-test.
The are preparing for the math test, but because of continuously adding big integers and solving equations they got exhausted. They decided to take break and play a game. They play a game which will help them in both(for having fun and will also help to prepare for math test).
There are N words and they have to find RESULT with the help of these words (just like they have N integers and they have to find integer RESULT=sum of N integers) . Since they are playing this game for the first time! They are not too good in this. Help them in finding weather their RESULT is correct or not.
NOTE:- Total number of unique characters in N words are not greater than 10. All input words and RESULT are in UPPER-CASE only!
Refer Here for how to add numbers : https://en.wikipedia.org/wiki/Verbal_arithmetic

-----Input:-----
- First line consist of an integer N (total number of words).
- Next N line contains words with which they have to find RESULT.
- Last line consist of the RESULT they found.

-----Output:-----
If RESULT is correct print true else print false.

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

THIS

IS

TOO

FUNNY

-----Sample Output:-----
true

-----Constraints-----
- $2 \leq N \leq 10$
- $1 \leq Length of The word \leq 10$
- $1 \leq Length of The Result \leq 11$

# Solution link: https://leetcode.com/problems/verbal-arithmetic-puzzle/discuss/939496/Python-Optimizations-to-beat-TLE-Top-Down-DP-(93)

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

import functools,collections
def isSolvable(words, result):

    @functools.lru_cache(None)
    def helper(i, total, nums):

        if i == len(chars):
            return total == 0

        if i - 1 in checkpoints:
            t = str(abs(total))[::-1]
            for j in checkpoints[i-1]:
                if (j < len(t)) and (t[j] != '0'):
                    return False

        for j in range(len(nums)):
            if (nums[j] == 0) and (chars[i] not in not_zero) and helper(i+1, total, nums[:j]+nums[j+1:]):
                return True
            elif (nums[j] != 0) and helper(i+1, total + nums[j] * mult[chars[i]], nums[:j] + nums[j+1:]):
                return True

        return False

    # 1. Check the lengths of each word and result
    longest_word = len(max(words, key = len))
    if (len(result) < longest_word) or (len(result) > longest_word + 1):
        return False

    # 2. Check if result is in words
    if result in words:
        return len(words) < 3 and all(word == result or len(word) == 1 for word in words)

    # 3. Leading letters cannot be zero unless the length of the word is 1
    not_zero = set((word[0] for word in words if len(word) > 1))
    if len(result) > 1: not_zero.add(result[0])

    # 4. Set of all letters
    chars = set(result + ''.join(words))

    # 5. Letters in words add to the total
    mult = {char:0 for char in chars}
    groups = collections.defaultdict(set)
    for word in words:
        for i,char in enumerate(reversed(word)):
            mult[char] += 10**i
            groups[i].add(char)

    # 6. And letters in result subtract from the total
    for i,char in enumerate(reversed(result)):
        mult[char] -=...


Solve in Python:
Two integers A and B are the inputs. Write a program to find GCD and LCM of A and B.

-----Input-----

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

-----Output-----
Display the GCD and LCM of A and B separated by space respectively. The answer for each test case must be displayed in a new line.

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

-----Example-----
Input
3
120 140
10213 312
10 30

Output

20 840
1 3186456
10 30

# cook your dish here
def GCD(x, y):
   while y:
    x, y = y, x % y
   return x

def LCM(x, y):
   lcm = (x*y)//GCD(x,y)
   return lcm

t = int(input())
while t>0:
    x,y = list(map(int,input().split()))
    print(GCD(x,y),LCM(x,y))
    t -=1


Solve in Python:
Two integers are coprimes if the their only greatest common divisor is 1.

## Task
In this kata you'll be given a number ```n >= 2``` and output a list with all positive integers less than ```gcd(n, k) == 1```, with ```k``` being any of the output numbers.

The list cannot include duplicated entries and has to be sorted.

## Examples
```
2 -> [1]
3 -> [1, 2]
6 -> [1, 5]
10 -> [1, 3, 7, 9]
20 -> [1, 3, 7, 9, 11, 13, 17, 19]
25 -> [1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19, 21, 22, 23, 24]
30 -> [1, 7, 11, 13, 17, 19, 23, 29]
```

from fractions import gcd

def coprimes(n):
  return [i for i in range(1,n+1) if gcd(n,i)==1]


Solve in Python:
Two moving objects A and B are moving accross the same orbit (those can be anything: two planets, two satellites, two spaceships,two flying saucers, or spiderman with batman if you prefer).
If the two objects start to move from the same point and the orbit is circular, write a function that gives the time the two objects will meet again, given the time the objects A and B need to go through a full orbit, Ta and Tb respectively, and the radius of the orbit r.
As there can't be negative time, the sign of Ta and Tb, is an indication of the direction in which the object moving: positive for clockwise and negative for anti-clockwise.

The function will return a string that gives the time, in two decimal points.
Ta and Tb will have the same unit of measurement so you should not expect it in the solution.

Hint: Use angular velocity "w" rather than the classical "u".

def meeting_time(Ta, Tb, r):
    if Ta == 0:
        return "{:.2f}".format(abs(Tb))
    elif Tb == 0:
        return "{:.2f}".format(abs(Ta))
    else:
        return "{:.2f}".format(abs(Ta * Tb / (Tb - Ta)))


Solve in Python:
Two numbers are **relatively prime** if their greatest common factor is 1; in other words: if they cannot be divided by any other common numbers than 1.

`13, 16, 9, 5, and 119` are all relatively prime because they share no common factors, except for 1. To see this, I will show their factorizations:
```python
 13: 13
 16: 2 * 2 * 2 * 2
  9: 3 * 3
  5: 5
119: 17 * 7
```

Complete the function that takes 2 arguments: a number (`n`), and a list of numbers (`arr`). The function should return a list of all the numbers in `arr` that are relatively prime to `n`. All numbers in will be positive integers.

## Examples

```python
relatively_prime(8, [1, 2, 3, 4, 5, 6, 7])
>> [1, 3, 5, 7]

relatively_prime(15, [72, 27, 32, 61, 77, 11, 40])
>> [32, 61, 77, 11]

relatively_prime(210, [15, 100, 2222222, 6, 4, 12369, 99])
>> []
```

from fractions import gcd

def relatively_prime (n, l):
    return [x for x in l if gcd(n, x) == 1]


Solve in Python:
Two players are playing a game. The game is played on a sequence of positive integer pairs. The players make their moves alternatively. During his move the player chooses a pair and decreases the larger integer in the pair by a positive multiple of the smaller integer in the pair in such a way that both integers in the pair remain positive. If two numbers in some pair become equal then the pair is removed from the sequence. The player who can not make any move loses (or in another words the player who encounters an empty sequence loses). Given the sequence of positive integer pairs determine whether the first player can win or not (assuming that both players are playing optimally).

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
Each test starts with an integer N denoting the number of pairs. Each of the next N lines contains a pair of positive integers.

-----Output-----
For each test case, output a single line containing "YES" if the first player can win and "NO" otherwise.

-----Constraints-----
- 1 ≤ T ≤ 100
- 1 ≤ N ≤ 100
- All other integers are between 1 to 108
- The integers in each pair will be different

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

Output:
NO
NO
YES

-----Explanation-----
Example case 1. The first player don't have any choice other subtracting 2 from 3. So during the turn of the second player integer pair will be (2,1). The second player will win by subtracting 1 from 2.
Example case 2. If the first player choose to move (4,5) to (4,1) the second player will make it to (1,1). If the first player choose to move (5,6) to (5,1) the second player will make it to (1,1). So regardless of the move of the first player, the second will always win.
Example case 3. The first player will select pair (3,5) and make it to (3,2). Now both pairs are equal. So whatever the move of second player he will just mirror that move in another pair. This will ensure his win.

import sys

t = int(input())

def g(a,b):
 if (a > b):
  tmp = a
  a = b
  b = tmp
 if (b == a):
  return 0
 if (b % a == 0):
  return int(b/a)-1
 r = g(b%a,a)
 q = int(b/a)
 if (r >= q):
  return q-1
 else:
  return q

def mex(x):
 n = len(list(x.keys()))
 for i in range(n):
  if (i not in x):
   return i
 return i

def g2(a,b):
 if (a == b):
  return 0
 if (a > b):
  tmp = a
  a = b
  b = tmp
 if (b % a == 0):
  return int(b/a)-1
 q = int(b/a)
 x = {}
 r = b % a
 for i in range(q):
  x[g2(r+i*a,a)] = True
 return mex(x)

#print(str(g(6,33))+" "+str(g2(6,33)))

while (t):

 n = int(input())
 x = 0
 while (n):
  line = input().split()
  a = int(line[0])
  b = int(line[1])
  x ^= g(a,b)
  n -= 1
 if (x):
  sys.stdout.write("YES\n")
 else:
  sys.stdout.write("NO\n")
 #print(str(g(a,b)) + " " + str(g2(a,b)))
 t -= 1


Solve in Python:
Two players decided to play one interesting card game.

There is a deck of $n$ cards, with values from $1$ to $n$. The values of cards are pairwise different (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that each player has at least one card.

The game goes as follows: on each turn, each player chooses one of their cards (whichever they want) and puts on the table, so that the other player doesn't see which card they chose. After that, both cards are revealed, and the player, value of whose card was larger, takes both cards in his hand. Note that as all cards have different values, one of the cards will be strictly larger than the other one. Every card may be played any amount of times. The player loses if he doesn't have any cards.

For example, suppose that $n = 5$, the first player has cards with values $2$ and $3$, and the second player has cards with values $1$, $4$, $5$. Then one possible flow of the game is:

The first player chooses the card $3$. The second player chooses the card $1$. As $3>1$, the first player gets both cards. Now the first player has cards $1$, $2$, $3$, the second player has cards $4$, $5$.

The first player chooses the card $3$. The second player chooses the card $4$. As $3<4$, the second player gets both cards. Now the first player has cards $1$, $2$. The second player has cards $3$, $4$, $5$.

The first player chooses the card $1$. The second player chooses the card $3$. As $1<3$, the second player gets both cards. Now the first player has only the card $2$. The second player has cards $1$, $3$, $4$, $5$.

The first player chooses the card $2$. The second player chooses the card $4$. As $2<4$, the second player gets both cards. Now the first player is out of cards and loses. Therefore, the second player wins.

Who will win if both players are playing optimally? It can be shown that one of the players has a winning strategy.

-----Input-----

Each test contains multiple test...

for _ in range(int(input())):
	n,k1,k2 = map(int,input().split())
	a = list(map(int,input().split()))
	b = list(map(int,input().split()))
	if n in a:
		print("YES")
	else: print("NO")


Solve in Python:
Two players play a turn based game on a binary tree.  We are given the root of this binary tree, and the number of nodes n in the tree.  n is odd, and each node has a distinct value from 1 to n.
Initially, the first player names a value x with 1 <= x <= n, and the second player names a value y with 1 <= y <= n and y != x.  The first player colors the node with value x red, and the second player colors the node with value y blue.
Then, the players take turns starting with the first player.  In each turn, that player chooses a node of their color (red if player 1, blue if player 2) and colors an uncolored neighbor of the chosen node (either the left child, right child, or parent of the chosen node.)
If (and only if) a player cannot choose such a node in this way, they must pass their turn.  If both players pass their turn, the game ends, and the winner is the player that colored more nodes.
You are the second player.  If it is possible to choose such a y to ensure you win the game, return true.  If it is not possible, return false.

Example 1:

Input: root = [1,2,3,4,5,6,7,8,9,10,11], n = 11, x = 3
Output: true
Explanation: The second player can choose the node with value 2.

Constraints:

root is the root of a binary tree with n nodes and distinct node values from 1 to n.
n is odd.
1 <= x <= n <= 100

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def btreeGameWinningMove(self, root: TreeNode, n: int, x: int) -> bool:
        #https://leetcode.com/problems/binary-tree-coloring-game/discuss/797574/Python-3-or-DFS-or-One-pass-and-Three-pass-or-Explanation

        if not root:
            return False

        from collections import defaultdict

        graph = defaultdict(list)

        def convert_tree_to_graph(root, parent=None):
            if not root:
                return None
            if parent:
                # creating bi-directional edges
                graph[parent].append(root)
                graph[root].append(parent)
            if root.left:
                convert_tree_to_graph(root.left, root)
            if root.right:
                convert_tree_to_graph(root.right, root)

        convert_tree_to_graph(root)

        # now we have the graph, we just need to find the node that player 1 selected
        # and count its trees in each direction
        node = None
        for g, v in list(graph.items()):
            if g.val == x:
                node = g
                break

        def count_nodes_in_subtree(node, visited):
            #return count
            if node in visited or node.val==x:
                return 0
            visited.add(node)
            count = 0
            for neighbor in graph[node]:
                if neighbor not in visited:
                    count += count_nodes_in_subtree(neighbor, visited)
            return count + 1

        subtrees = []
        max_subtree = -1
        #print (node, subtrees)
        for subtree in graph[node]:
            ans = count_nodes_in_subtree(subtree, set())
            subtrees.append(ans)
            max_subtree = max(max_subtree, ans)

        return n -...


Solve in Python:
Two red beads are placed between every two blue beads. There are N blue beads. After looking at the arrangement below work out the number of red beads.

@
@@
@
@@
@
@@
@
@@
@
@@
@

Implement count_red_beads(n) (in PHP count_red_beads($n); in Java, Javascript, TypeScript, C, C++ countRedBeads(n)) so that it returns the number of red beads.
If there are less than 2 blue beads return 0.

def count_red_beads(n):
    if n > 1:
        return n * 2 - 2
    elif n == 1:
        return 0
    elif n < 1:
        return 0


Solve in Python:
Two sisters, A and B, play the piano every day. During the day, they can play in any order. That is, A might play first and then B, or it could be B first and then A. But each one of them plays the piano exactly once per day. They maintain a common log, in which they write their name whenever they play.
You are given the entries of the log, but you're not sure if it has been tampered with or not. Your task is to figure out whether these entries could be valid or not.

-----Input-----
- The first line of the input contains an integer $T$ denoting the number of test cases. The description of the test cases follows.
- The first line of each test case contains a string $s$ denoting the entries of the log.

-----Output-----
- For each test case, output yes or no according to the answer to the problem.

-----Constraints-----
- $1 \le T \le 500$
- $2 \le |s| \le 100$
- $|s|$ is even
- Each character of $s$ is either 'A' or 'B'

-----Example Input-----
4
AB
ABBA
ABAABB
AA

-----Example Output-----
yes
yes
no
no

-----Explanation-----
Testcase 1: There is only one day, and both A and B have played exactly once. So this is a valid log. Hence 'yes'.
Testcase 2: On the first day, A has played before B, and on the second day, B has played first. Hence, this is also a valid log.
Testcase 3: On the first day, A played before B, but on the second day, A seems to have played twice. This cannot happen, and hence this is 'no'.

t=int(input())
for i in range (t):
 s=input()
 x=0
 y=2
 count=0
 for i in range(len(s)//2):
  a=s[x:y]
  if "A" in a and "B" in a :
   count=count+1
  else:
   count=count
  x=x+2
  y=y+2
 if count==len(s)//2:
  print("yes")
 else:
  print("no")


Solve in Python:
Two strings ```a``` and b are called isomorphic if there is a one to one mapping possible for every character of ```a``` to every character of ```b```. And all occurrences of every character in ```a``` map to same character in ```b```.

## Task

In this kata you will create a function that return ```True``` if two given strings are isomorphic to each other, and ```False``` otherwise. Remember that order is important.

Your solution must be able to handle words with more than 10 characters.

## Example
True:
```
CBAABC DEFFED
XXX YYY
RAMBUNCTIOUSLY THERMODYNAMICS
```

False:
```
AB CC
XXY XYY
ABAB CD
```

def isomorph(a, b):
    return len(a) == len(b) and len(set(a)) == len(set(b)) == len(set(zip(a, b)))


Solve in Python:
Two tortoises named ***A*** and ***B*** must run a race. ***A*** starts with an average speed of ```720 feet per hour```.
Young ***B*** knows she runs faster than ***A***, and furthermore has not finished her cabbage.

When she starts, at last, she can see that ***A*** has a `70 feet lead` but ***B***'s speed is `850 feet per hour`.
How long will it take ***B*** to catch ***A***?

More generally:
given two speeds `v1` (***A***'s speed, integer > 0) and `v2` (***B***'s speed, integer > 0) and a lead `g` (integer > 0)
how long will it take ***B*** to catch ***A***?

The result will be an array ```[hour, min, sec]``` which is the time needed in hours, minutes and seconds (round down to the nearest second)
or a string in some languages.

If `v1 >= v2` then return `nil`, `nothing`, `null`, `None` or `{-1, -1, -1}` for C++, C, Go, Nim, `[]` for Kotlin or "-1 -1 -1".

## Examples:
(form of the result depends on the language)
```
race(720, 850, 70) => [0, 32, 18] or "0 32 18"
race(80, 91, 37)   => [3, 21, 49] or "3 21 49"
```

** Note:

- See other examples in "Your test cases".

- In Fortran - as in any other language - the returned string is not permitted to contain any redundant trailing whitespace: you can use dynamically allocated character strings.

** Hints for people who don't know how to convert to hours, minutes, seconds:

- Tortoises don't care about fractions of seconds

- Think of calculation by hand using only integers (in your code use or simulate integer division)

- or Google: "convert decimal time to hours minutes seconds"


Solve in Python:
Two words rhyme if their last 3 letters are a match. Given N words, print the test case number (of the format Case : num) followed by the rhyming words in separate line adjacent to each other.

The output can be in anyorder.

-----Input-----
First line contains the number of test case T

The next line contains the number of words N

Next N words follow . They’ll contain only alphabets from ‘a’-‘z’.

-----Output-----
Print case number (for each test case) of the format Case : num followed by the words that rhyme in a new line.

-----Constraints-----
1 <= T <= 5

1 <= N <= 1000

3 <= length of each word <= 1000

-----Example-----
Input:
3
3
nope qwerty hope
5
brain drain request grain nest
4
these words dont rhyme

Output:
Case : 1
hope nope
qwerty
Case : 2
brain drain grain
nest request
Case : 3
these
dont
words
rhyme

-----Explanation-----
Case : 2

brain drain grain

nest request

Case : 3

these

dont

words

rhyme
Explanation for case 1: since hope and nope rhyme (suffix “ope” matches), we print them in the same line and qwerty In a new line.

Note that

qwerty

nope hope

is also correct (the output can be in any order )

t = int(input())
for i in range(t):
 n = int(input())
 suffixes = {}
 xx = input().split()
 for x in range(n):
  try:
   a = suffixes[xx[x][-3:]]
  except Exception as e:
   a = []
  a.append(xx[x])

  suffixes.update({xx[x][-3:]: a})

 print("Case : %d" % (i + 1))
 for a in sorted(suffixes):
  print("".join(b + " " for b in sorted(suffixes[a])).strip())


Solve in Python:
Two's company, three's a crowd!
It's been one year since Chef met his brother. Last year, his younger brother came to visit him during this time of the year. This year, the Chef is planning to go visit his brother. Chef's brother has planned to throw a "Welcome Party" for him. He wants to invite people from his neighbourhood (i.e. from the street where he lives). There are N houses on the street in a single line (not considering the brother's house). He wants the party to be fun and he will not like to invite people who might spoil the mood of the party. If people are invited from three consecutive houses on the street, they might create trouble. As they say, three's a crowd! He doesn't want to ruin the Chef's Welcome Party and so he will not want to send invites to any three consecutive houses. He wants you to tell him how many ways are there for him to go wrong. Note that he can play safe by not inviting anyone to avoid a crowd.

-----Input:-----
First line of the input contains a single integer T, the number of test cases.

Each test case contains a line containing a single integer N described above.

-----Output:-----
For each test case output a single integer denoting the number of ways the brother can go wrong with planning the party.

The answer can get quite large. So output the total number of ways modulo 109+7.

-----Constraints:-----
1<=T<=10000
1<=N<=1015

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

Output:
1
3

Explanation:
Case 1: The only way he can go wrong is by inviting all the houses.
Case 2: First way of getting wrong is by inviting houses (1,2,3). Second way to get wrong is by inviting houses (2,3,4). Third way of going wrong is by inviting all 4 houses i.e. (1,2,3,4).

MOD = int(1e9+7)

def mult(a, b):
 rsp = [[0, 0, 0],
   [0, 0, 0],
   [0, 0, 0]]

 for i in range(3):
  for j in range(3):
   for k in range(3):
    rsp[i][j] += a[i][k] * b[k][j]
    rsp[i][j] %= MOD

 return rsp

ident = [[1, 0, 0],
   [0, 1, 0],
   [0, 0, 1]]
m = [[1, 1, 0],
  [1, 0, 1],
  [1, 0, 0]]

powers = [m]
for _ in range(53):
 p = powers[-1]
 powers.append(mult(p ,p))

def pow2(e):
 y = ident
 i = 0
 for p in powers:
  if e & (1 << i):
   y = mult(p, y)
  i += 1
 return y

t = eval(input())

for _ in range(t):
 n = eval(input())

 if n < 3:
  print(0)
  continue

 r = pow(2, n, MOD)
 b = pow2(n - 2)
 # print(b)
 r -= (4 * b[0][0]) % MOD
 r -= (2 * b[1][0]) % MOD
 r -= b[2][0]
 r = (MOD + r) % MOD
 print(r)


Solve in Python:
Tzuyu gave Nayeon a strip of $N$ cells (numbered $1$ through $N$) for her birthday. This strip is described by a sequence $A_1, A_2, \ldots, A_N$, where for each valid $i$, the $i$-th cell is blocked if $A_i = 1$ or free if $A_i = 0$. Tzuyu and Nayeon are going to use it to play a game with the following rules:
- The players alternate turns; Nayeon plays first.
- Initially, both players are outside of the strip. However, note that afterwards during the game, their positions are always different.
- In each turn, the current player should choose a free cell and move there. Afterwards, this cell becomes blocked and the players cannot move to it again.
- If it is the current player's first turn, she may move to any free cell.
- Otherwise, she may only move to one of the left and right adjacent cells, i.e. from a cell $c$, the current player may only move to the cell $c-1$ or $c+1$ (if it is free).
- If a player is unable to move to a free cell during her turn, this player loses the game.
Nayeon and Tzuyu are very smart, so they both play optimally. Since it is Nayeon's birthday, she wants to know if she can beat Tzuyu. Find out who wins.

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

-----Output-----
For each test case, print a single line containing the string "Yes" if Nayeon wins the game or "No" if Tzuyu wins (without quotes).

-----Constraints-----
- $1 \le T \le 40,000$
- $2 \le N \le 3\cdot 10^5$
- $0 \le A_i \le 1$ for each valid $i$
- $A_1 = A_N = 1$
- the sum of $N$ over all test cases does not exceed $10^6$

-----Subtasks-----
Subtask #1 (50 points): $A_i = 0$ for each $i$ ($2 \le i \le N-1$)
Subtask #2 (50 points): original constraints

-----Example Input-----
4
7
1 1 0 0 0 1 1
8
1 0 1 1 1 0 0 1
4
1 1 0 1
4
1 1 1 1

-----Example...

test_case = int(input())
while test_case > 0:
 test_case -= 1
 n= int(input())
 arr = [int(x) for x in input().split()]
 c = list()
 temp = 0
 times = 0
 flag = True
 for a in arr:
  if a == 0:
   temp += 1
   if flag:
    flag = False
    times += 1
  else:
   # c = max(c,temp)
   c.append(temp)
   temp = 0
   flag = True
 # if c % 2 == 0 :
 #     print("No")
 # else:
 #     print("Yes")
 max1 = max(c)
 c.remove(max1)
 max2 = max(c)
 if max1 % 2 == 0 or max1 == max2 :
  print("No")
 else:
  print("Yes")


Solve in Python:
Uh oh, Someone at the office has dropped all these sequences on the floor and forgotten to label them with their correct bases.

We have to fix this before the boss gets back or we're all going to be fired!

This is what your years of coding have been leading up to, now is your time to shine!

## Task

You will have to create a function which takes in a sequence of numbers in **random order** and you will have to return the correct base of those numbers.

The base is the number of unique digits. For example, a base 10 number can have 10 unique digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and a base 2 number (Binary) can have 2 unique digits: 0 and 1.

### Constraints

The sequence will always be 10 numbers long and we know that the base is going to be between 2 and 10 inclusive so no need to worry about any letters. When sorted, the sequence is made up of consecutive numbers.

### Examples

```
[ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" ]     -->  10
[ "1", "2", "3", "4", "5", "6", "10", "11", "12", "13" ]  -->   7
```

**Good luck!**

def base_finder(seq):
    return int(max(''.join(seq))) +1


Solve in Python:
Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.

There are $k$ boxes numbered from $1$ to $k$. The $i$-th box contains $n_i$ integer numbers. The integers can be negative. All of the integers are distinct.

Ujan is lazy, so he will do the following reordering of the numbers exactly once. He will pick a single integer from each of the boxes, $k$ integers in total. Then he will insert the chosen numbers — one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box.

Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be?

-----Input-----

The first line contains a single integer $k$ ($1 \leq k \leq 15$), the number of boxes.

The $i$-th of the next $k$ lines first contains a single integer $n_i$ ($1 \leq n_i \leq 5\,000$), the number of integers in box $i$. Then the same line contains $n_i$ integers $a_{i,1}, \ldots, a_{i,n_i}$ ($|a_{i,j}| \leq 10^9$), the integers in the $i$-th box.

It is guaranteed that all $a_{i,j}$ are distinct.

-----Output-----

If Ujan cannot achieve his goal, output "No" in a single line. Otherwise in the first line output "Yes", and then output $k$ lines. The $i$-th of these lines should contain two integers $c_i$ and $p_i$. This means that Ujan should pick the integer $c_i$ from the $i$-th box and place it in the $p_i$-th box afterwards.

If there are multiple solutions, output any of those.

You can print each letter in any case (upper or lower).

-----Examples-----
Input
4
3 1 7 4
2 3 2
2 8 5
1 10

Output
Yes
7 2
2 3
5 1
10 4

Input
2
2 3 -2
2 -1 5

Output
No

Input
2
2 -10 10
2 0 -20

Output
Yes
-10 2
-20 1

-----Note-----

In the first sample, Ujan can put the number $7$ in the $2$nd box, the number $2$ in the $3$rd box, the number $5$ in the $1$st box and keep the number $10$ in the...

def main():
    k = int(input())
    n = []
    a = []
    for i in range(k):
        line = [int(x) for x in input().split()]
        ni = line[0]
        ai = []
        n.append(ni)
        a.append(ai)
        for j in range(ni):
            ai.append(line[1 + j])
    answer, c, p = solve(k, n, a)
    if answer:
        print("Yes")
        for i in range(k):
            print(c[i], p[i] + 1)
    else:
        print("No")

def solve(k, n, a):
    asum, sums = calc_sums(k, n, a)
    if asum % k != 0:
        return False, None, None
    tsum = asum / k
    num_map = build_num_map(k, n, a)
    masks = [None]*(1 << k)
    simple = [False]*(1 << k)
    answer = [False]*(1 << k)
    left = [0]*(1 << k)
    right = [0]*(1 << k)
    by_last_one = [[] for _ in range(k)]
    for i in range(k):
        for j in range(n[i]):
            found, mask, path = find_cycle(i, j, i, j, k, n, a, sums, tsum, num_map, 0, [])
            if found and not answer[mask]:
                answer[mask] = True
                masks[mask] = path
                simple[mask] = True
                by_last_one[calc_last_one(mask)].append(mask)
    if answer[(1 << k) - 1]:
        return build_answer(k, masks, left, right)
    for mask_right in range(2, 1 << k):
        if not simple[mask_right]:
            continue
        last_one = calc_last_one(mask_right)
        zeroes_count = 0
        alternative_sum = 0
        zero_list = []
        for u in range(last_one):
            if (mask_right & (1 << u)) == 0:
                zeroes_count += 1
                alternative_sum += len(by_last_one[u])
                zero_list.append(u)
        if zeroes_count == 0:
            continue
        if alternative_sum < (1 << zeroes_count):
            for fill_last_zero in zero_list:
                for mask_left in by_last_one[fill_last_zero]:
                    if (mask_left & mask_right) != 0:
                        continue
                    joint_mask = mask_left | mask_right
                    if not answer[joint_mask]:
         ...


Solve in Python:
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.

It is an undirected weighted graph on $n$ vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either $0$ or $1$; exactly $m$ edges have weight $1$, and all others have weight $0$.

Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?

-----Input-----

The first line of the input contains two integers $n$ and $m$ ($1 \leq n \leq 10^5$, $0 \leq m \leq \min(\frac{n(n-1)}{2},10^5)$), the number of vertices and the number of edges of weight $1$ in the graph.

The $i$-th of the next $m$ lines contains two integers $a_i$ and $b_i$ ($1 \leq a_i, b_i \leq n$, $a_i \neq b_i$), the endpoints of the $i$-th edge of weight $1$.

It is guaranteed that no edge appears twice in the input.

-----Output-----

Output a single integer, the weight of the minimum spanning tree of the graph.

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

Output
2

Input
3 0

Output
0

-----Note-----

The graph from the first sample is shown below. Dashed edges have weight $0$, other edges have weight $1$. One of the minimum spanning trees is highlighted in orange and has total weight $2$. [Image]

In the second sample, all edges have weight $0$ so any spanning tree has total weight $0$.

import sys
input = sys.stdin.readline

n, m = map(int, input().split())
e = set(tuple(map(int, input().split())) for _ in range(m))

unknown = set(range(1, n + 1))
to_check = []
ans = 0
while unknown:
    if to_check:
        u = to_check.pop()
    else:
        u = unknown.pop()
        ans += 1
    cur = []
    for v in unknown:
        if (u, v) in e or (v, u) in e:
            continue
        cur.append(v)
    for v in cur:
        unknown.remove(v)
    to_check += cur

print(ans - 1)


Solve in Python:
Under a grammar given below, strings can represent a set of lowercase words.  Let's use R(expr) to denote the set of words the expression represents.
Grammar can best be understood through simple examples:

Single letters represent a singleton set containing that word.

R("a") = {"a"}
R("w") = {"w"}

When we take a comma delimited list of 2 or more expressions, we take the union of possibilities.

R("{a,b,c}") = {"a","b","c"}
R("{{a,b},{b,c}}") = {"a","b","c"} (notice the final set only contains each word at most once)

When we concatenate two expressions, we take the set of possible concatenations between two words where the first word comes from the first expression and the second word comes from the second expression.

R("{a,b}{c,d}") = {"ac","ad","bc","bd"}
R("a{b,c}{d,e}f{g,h}") = {"abdfg", "abdfh", "abefg", "abefh", "acdfg", "acdfh", "acefg", "acefh"}

Formally, the 3 rules for our grammar:

For every lowercase letter x, we have R(x) = {x}
For expressions e_1, e_2, ... , e_k with k >= 2, we have R({e_1,e_2,...}) = R(e_1) ∪ R(e_2) ∪ ...
For expressions e_1 and e_2, we have R(e_1 + e_2) = {a + b for (a, b) in R(e_1) × R(e_2)}, where + denotes concatenation, and × denotes the cartesian product.

Given an expression representing a set of words under the given grammar, return the sorted list of words that the expression represents.

Example 1:
Input: "{a,b}{c,{d,e}}"
Output: ["ac","ad","ae","bc","bd","be"]

Example 2:
Input: "{{a,z},a{b,c},{ab,z}}"
Output: ["a","ab","ac","z"]
Explanation: Each distinct word is written only once in the final answer.

Constraints:

1 <= expression.length <= 60
expression[i] consists of '{', '}', ','or lowercase English letters.
The given expression represents a set of words based on the grammar given in the description.

class Solution:
    def braceExpansionII(self, expression: str) -> List[str]:
        groups = [[]]
        level = 0
        for i, c in enumerate(expression):
            if c == '{':
                if level == 0:
                    start = i+1
                level += 1
            elif c == '}':
                level -= 1
                if level == 0:
                    groups[-1].append(self.braceExpansionII(expression[start:i]))
            elif c == ',' and level == 0:
                groups.append([])
            elif level == 0:
                groups[-1].append([c])
        word_set = set()
        for group in groups:
            word_set |= set(map(''.join, itertools.product(*group)))
        return sorted(word_set)


Solve in Python:
Unicode Transformation Format – 8-bit
As the name suggests UTF-8 was designed to encode data in a stream of bytes.

It works by splitting the bits up in multiples of eight. This is achieved by inserting headers to mark in how many bytes the bits were split. If the bits need to be split in two, the header `110` is added as prefix leaving five bits of the byte for the rest of the data. Followed by a continuation byte.

A continuation byte always start with `10` leaving six bits for data.
For a three-way split: the header `1110` is added with two continuation bytes and for four: `11110` with three continuation bytes. The number of ones at the start of the first byte denotes the number of bytes the data was split in.
# Task
Your task is to write two functions:
1. `to_utf8_binary`: which encodes a string to a bitstring using UTF-8 encoding.
2. `from_utf8_binary`: which does the reverse.

- Layout of UTF-8 byte sequences:
```
# BYTES  FIRST CODE POINT  LAST CODE POINT    BYTE 1      BYTE 2      BYTE 3      BYTE 4
    1                   0              127    0xxxxxxx
    2                 128             2047    110xxxxx    10xxxxxx
    3                2048            65535    1110xxxx    10xxxxxx    10xxxxxx
    4               65536          1114111    11110xxx    10xxxxxx    10xxxxxx    10xxxxxx
```

# Examples
```
ENCODE
 A  -> 1000001         -> 01000001
 八 -> 101000101101011 -> 1110-0101 10-000101 10-101011

DECODE
 110-00010 10-100111                     -> 10100111          -> §
 11110-000 10-010000 10-001010 10-001100 -> 10000001010001100 -> 𐊌
```
* Spaces and hyphens just for clarity
- https://en.wikipedia.org/wiki/UTF-8#Encoding

def to_utf8_binary(string):
    return ''.join((bin(i)[2:]).zfill(8) for i in string.encode('utf-8'))

def from_utf8_binary(bitstr):
    byte_str = bytes(int(bitstr[i:i + 8], 2) for i in range(0, len(bitstr), 8))
    return byte_str.decode('utf-8')


Solve in Python:
Unscramble the eggs.

The string given to your function has had an "egg" inserted directly after each consonant.  You need to return the string before it became eggcoded.

## Example

Kata is supposed to be for beginners to practice regular expressions, so commenting would be appreciated.

import re
def unscramble_eggs(word):
    return re.sub('([^aeiouAEIOU])egg', r'\1', word)


Solve in Python:
Using his tip-top physique, Kim has now climbed up the mountain where the base is located. Kim has found the door to the (supposedly) super secret base. Well, it is super secret, but obviously no match for Kim's talents.
The door is guarded by a row of $N$ buttons. Every button has a single number $A_i$ written on it. Surprisingly, more than one button can have the same number on it. Kim recognises this as Soum's VerySafe door, for which you need to press two buttons to enter the password. More importantly, the sum of the two numbers on the buttons you press must be odd. Kim can obviously break through this door easily, but he also wants to know how many different pairs of buttons he can pick in order to break through the door.
Can you help Kim find the number of different pairs of buttons he can press to break through the door?
Note: Two pairs are considered different if any of the buttons pressed in the pair is different (by position of the button pressed). Two pairs are not considered different if they're the same position of buttons, pressed in a different order.
Please refer to the samples for more details.

-----Input:-----
- The first line contains a single integer $T$, representing the number of testcases. $2T$ lines follow, 2 for each testcase.
- For each testcase, the first line contains a single integer $N$, the number of buttons.
- The second line of each testcase contains $N$ space-separated integers, $A_1, A_2, \ldots, A_N$, representing the numbers written on each button.

-----Output:-----
Print a single number, $K$, representing the number of pairs of buttons in $A$ which have an odd sum.

-----Subtasks-----
For all subtasks,  $1 \leq T \leq 10$, $1 \leq N \leq 100000$, and $1 \leq A_i \leq 100000$ for all $A_i$.
Subtask 1 [15 points] : $N \leq 2$, There are at most 2 buttons
Subtask 2 [45 points] : $N \leq 1000$, There are at most 1000 buttons
Subtask 3 [40 points] : No additional constraints.

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

-----Sample...

# cook your dish here
try:
 t=int(input())
 for _ in range(t):
  n=int(input())
  l=list(map(int,input().split()))
  sum,c=0,0
  for i in range(len(l)):
   for j in range(i,len(l)-1):
    sum=sum+l[j]+l[j+1]
    if sum%2!=0:
     c=c+1
  print(c)
except:
 pass


Solve in Python:
Uttu got to know about an interesting two-player mobile game recently and invites his friend Gangwar to try it out with him. Gangwar, however, has been playing this game since it was out 5 years ago and is a Legendary Grandmaster at it. Uttu immediately thought of somehow cheating in this game to beat Gangwar.
But the most he could do was choose if he wanted to go "First" or if he wanted to go "Second" in this alternative turn based game. Help Uttu choose so that he will always win regardless of Gangwar's moves.Description of the game
You are playing on a continent name Tamriel. This continent have $N$ towns numbered from $1$ to $N$ where town $1$ is the capital. These towns are connected to each other by $N-1$ roads. Any two towns are connected by some series of roads, i.e., You can go from any town to any other town using these roads.
Each town $i$ some initial amout of soldiers $S_i$ in it. At every move, a player can choose a town other than the capital $i$ and move some non-zero amount of its current soldiers to a town which is one step closer towards the capital. After the first move, the moves are alternated between the players. The player who cannot make a move loses.Input
- The first line contains a single integer $N$
- The second line contains a $N$ space seperated integers denoting $S_1,S_2,\dots,S_n$
- The $N-1$ subsequent lines contain two space seperated integers $u$ and $v$, denoting that the town $u$ and town $v$ are connected by a road.Output
- Print "First" or "Second" based on what Uttu should choose to win.Constraints
- $ 2 \leq N \leq {2}\times{10}^{5}$
- $ 1 \leq S_i \leq {10}^{9}$ for each valid $i$
- $ 1 \leq u,v \leq N$Sample Input 1
2
10 10
1 2
Sample Output 1
First
Explanation 1
Uttu will move the $10$ soldiers at town $2$ to the capital (town $1$). After this Gangwar cannot make a move, so he loses.Sample Input 2
3
1 1 1
1 2
1 3
Sample Output 2
Second
Explanation 2
Gangwar has options: either move the soldier at town $2$, or move the soldier at town $3$.
Whatever he choses, Uttu...

'''     J A I ~ S H R E E ~ R A M     '''

# Title: cc-CKOJ20D.py
# created on: 20-07-2020 at 20:46:04
# Creator & Template : Udit Gupta "@luctivud"
# https://github.com/luctivud
# https://www.linkedin.com/in/udit-gupta-1b7863135/

import math; from collections import *
import sys; from functools import reduce
from itertools import groupby

# sys.setrecursionlimit(10**6)

def get_ints(): return map(int, input().strip().split())
def get_list(): return list(get_ints())
def get_string(): return list(input().strip().split())
def printxsp(*args): return print(*args, end="")
def printsp(*args): return print(*args, end=" ")

DIRECTIONS = [[0, 1], [0, -1], [1, 0], [1, -1]] #up, down, right, left
NEIGHBOURS = [(i, j) for i in range(-1, 2) for j in range(-1, 2) if (i!=0 or j!=0)]

OrdUnicode_a = ord('a'); OrdUnicode_A = ord('A')
CAPS_ALPHABETS = {chr(i+OrdUnicode_A) : i for i in range(26)}
SMOL_ALPHABETS = {chr(i+OrdUnicode_a) : i for i in range(26)}

MOD_JOHAN = int(1e9)+7; MOD_LIGHT = 998244353; INFINITY = float('inf')
MAXN_EYEPATCH = int(1e5)+1; MAXN_FULLMETAL = 501

# Custom input output is now piped through terminal commands.

def bfs(s):
    queue = deque()
    visited = set()
    visited.add(1)
    queue.append((1, 0))
    while len(queue):
        node, dep = queue.popleft()
        dep += 1
        for zen in tree[node]:
            if zen not in visited:
                visited.add(zen)
                if dep & 1:
                    global xorsum
                    xorsum ^= li[zen]
                queue.append((zen, dep))
        # print(queue)

# for _testcases_ in range(int(input())):
n = int(input())
li = [0] + get_list()
tree = defaultdict(list)
for _  in range(n-1):
    a, b = get_ints()
    tree[a].append(b)
    tree[b].append(a)
xorsum = 0
bfs(1)
# print(xorsum)
print("First" if xorsum else "Second")

'''
THE LOGIC AND APPROACH IS MINE ( UDIT GUPTA )
Link may be copy-pasted here, otherwise.
'''


Solve in Python:
VK gave a problem to Chef, but Chef is too lazy, so he asked you to solve the problem for him. The statement of the problem follows.
Consider an integer with $N$ digits (in decimal notation, without leading zeroes) $D_1, D_2, D_3, \dots, D_N$. Here, $D_1$ is the most significant digit and $D_N$ the least significant. The weight of this integer is defined as ∑i=2N(Di−Di−1).∑i=2N(Di−Di−1).\sum_{i=2}^N (D_i - D_{i-1})\,.
You are given integers $N$ and $W$. Find the number of positive integers with $N$ digits (without leading zeroes) and weight equal to $W$. Compute this number modulo $10^9+7$.

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

-----Output-----
For each test case, print a single line containing one integer — the number of $N$-digit positive integers with weight $W$, modulo $10^9+7$.

-----Constraints-----
- $1 \le T \le 10^5$
- $2 \le N \le 10^{18}$
- $|W| \le 300$

-----Subtasks-----
Subtask #1 (20 points):
- $1 \le T \le 10^3$
- $2 \le N \le 10^3$
Subtask #2 (80 points): original constraints

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

1
2 3

-----Example Output-----

6

-----Explanation-----
Example case 1: Remember that the digits are arranged from most significant to least significant as $D_1, D_2$. The two-digit integers with weight $3$ are $14, 25, 36, 47, 58, 69$. For example, the weight of $14$ is $D_2-D_1 = 4-1 = 3$. We can see that there are no other possible numbers.

# cook your dish here

mod=10**9+7

def power10(N):
 if N==0:
  return dp[0]
 if N%2==1:
  dp[N]=(10*power10(N-1))%mod
  return((10*power10(N-1))%mod)
 else:
  if dp[N//2]==-1:
   dp[N//2]=power10(N//2)%mod
  dp[N]=(dp[N//2]**2)%mod
  return(dp[N]%mod)

from sys import stdin, stdout
T=int(input().strip())

for _ in range(T):
 N,W=map(int,input().strip().split())
 dp=[-1]*(N+1)
 dp[0]=1
 if W>8 or W<-9:
  print(0)
 else:
  if W>=0:
   res=(9-W)*power10(N-2)
  else:
   res=(W+10)*power10(N-2)
  print(res%mod)


Solve in Python:
Validate if a given string is numeric.

Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true

Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.

class Solution:
     def isNumber(self, s):
         try:
             float(s)
             return True
         except:
             return False


Solve in Python:
Vanja and Miksi have already finished everything for this year at their university, so they decided to spend their free time playing a game with a binary sequence $A_1, A_2, \dots, A_N$ (i.e. a sequence containing only integers $0$ and $1$).
At the beginning of the game, Vanja and Miksi write down the expression $* A_1 * A_2 * A_3 * \ldots * A_N$ (note below that each $*$ is a placeholder and does not denote multiplication).
The players take turns alternately, starting with Vanja. The game lasts $N$ turns. In each turn, the current player must replace the first (leftmost) remaining $*$ by the sign $+$ or $-$ (or, equivalently, by the operation of addition or subtraction).
After the last turn, the boys calculate the resulting value $V$ of the expression. If $|V| \ge K$, the winner is Vanja; otherwise, the winner is Miksi.
Please predict the winner of the game if both players play optimally.

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

-----Output-----
For each test case, print a single line containing one integer — $1$ if Vanja (the first player) is the winner or $2$ if Miksi (the second player) is the winner.

-----Constraints-----
- $1 \le T \le 50$
- $1 \le N \le 3 \cdot 10^4$
- $0 \le K \le 3 \cdot 10^4$
- $0 \le A_i \le 1$ for each valid $i$

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

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

-----Explanation-----
Example case 1: $K = 1$, so if Vanja replaces the first $*$ by $+$, the value of the final expression will be $V = 1$; then, $K \le |V|$, so the winner is Vanja.
Example case 2: $K = 5$, but the absolute value of the final expression cannot be greater than $1$. The winner is Miksi.

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

for _ in range(t):
 n, k = list(map(int, input().split()))
 a = list(map(int, input().split()))
 sum = 0
 for i in range(n):
  if i % 2 == 0:
   if sum > 0:
    sum += a[i]
   else:
    sum -= a[i]
  else:
   if sum > 0:
    sum -= a[i]
   else:
    sum += a[i]
 if abs(sum) >= k:
  print(1)
 else:
  print(2)


Solve in Python:
Vanja and Miksi really like games. After playing one game for a long time, they decided to invent another game!
In this game, they have a sequence $A_1, A_2, \dots, A_N$ and two numbers $Z_1$ and $Z_2$. The rules of the game are as follows:
- The players take turns alternately, starting with Vanja.
- There is an integer $S$; at the beginning, $S = 0$.
- In each turn, the current player must choose an arbitrary element of $A$ and either add that number to $S$ or subtract it from $S$. Each element can be selected multiple times.
- Afterwards, if $S = Z_1$ or $S = Z_2$, the current player (the player who made $S$ equal to $Z_1$ or $Z_2$) is the winner of the game.
- If the game lasts for $10^{10}$ turns, Vanja and Miksi decide to declare it a tie.
Can you help the boys determine the winner of the game? Please note that the game can end in a tie (if nobody can make $S = Z_1$ or $S = Z_2$ in the first $10^{10}$ moves).
Both players play optimally, i.e. if there is a move which guarantees the current player's victory regardless of the other player's moves, the current player will make such a move. If the current player cannot win and there is a move which guarantees that the game will end in a tie, the current player will make such a move.

-----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 $N$, $Z_1$ and $Z_2$.
- The second line contains $N$ space-separated integers $A_1, A_2, \dots, A_N$.

-----Output-----
- For each test case, print a single line containing one integer — the final result of the game:
- $1$ if Vanja (the first player) has a winning strategy
- $2$ if Miksi (the second player) has a winning strategy
- $0$ if the game ends in a tie

-----Constraints-----
- $1 \le T \le 50$
- $1 \le N \le 50$
- $|Z_1|, |Z_2| \le 10^9$
- $|A_i| \le 10^9$ for each valid $i$

-----Subtasks-----
Subtask #1 (25 points): $N = 2$
Subtask #2 (75...

for i in range(int(input())):
 n,z1,z2 = map(int,input().split())
 arr = list(map(int,input().split()))
 m = dict()
 for item in arr:
  m[item]=1
  m[-item]=-1
 if z1 in m or z2 in m:
  print("1")
 else:
  cnt = 0
  for item in arr:
   if z1-item in m or z2-item in m:
    cnt+=1
   if z1+item in m or z2+item in m:
    cnt+=1
  if cnt==2*n:
   print("2")
  else: print("0")


Solve in Python:
Vanya wants to minimize a tree. He can perform the following operation multiple times: choose a vertex v, and two disjoint (except for v) paths of equal length a_0 = v, a_1, ..., a_{k}, and b_0 = v, b_1, ..., b_{k}. Additionally, vertices a_1, ..., a_{k}, b_1, ..., b_{k} must not have any neighbours in the tree other than adjacent vertices of corresponding paths. After that, one of the paths may be merged into the other, that is, the vertices b_1, ..., b_{k} can be effectively erased: [Image]

Help Vanya determine if it possible to make the tree into a path via a sequence of described operations, and if the answer is positive, also determine the shortest length of such path.

-----Input-----

The first line of input contains the number of vertices n (2 ≤ n ≤ 2·10^5).

Next n - 1 lines describe edges of the tree. Each of these lines contains two space-separated integers u and v (1 ≤ u, v ≤ n, u ≠ v) — indices of endpoints of the corresponding edge. It is guaranteed that the given graph is a tree.

-----Output-----

If it is impossible to obtain a path, print -1. Otherwise, print the minimum number of edges in a possible path.

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

Output
3

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

Output
-1

-----Note-----

In the first sample case, a path of three edges is obtained after merging paths 2 - 1 - 6 and 2 - 4 - 5.

It is impossible to perform any operation in the second sample case. For example, it is impossible to merge paths 1 - 3 - 4 and 1 - 5 - 6, since vertex 6 additionally has a neighbour 7 that is not present in the corresponding path.

import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

def LI(): return list(map(int, input().split()))
def II(): return int(input())
def LS(): return input().split()
def S(): return input()

def main():
    n = II()
    d = collections.defaultdict(set)
    for _ in range(n-1):
        a,b = LI()
        d[a].add(b)
        d[b].add(a)

    memo = [-1] * (n+1)
    def path(t,s):
        ps = set()
        dt = list(d[t])
        for k in dt:
            if memo[k] < 0:
                continue
            ps.add(memo[k])

        if s == -1 and len(ps) == 2:
            memo[t] = sum(ps) + 2
            return memo[t]

        if len(ps) > 1:
            return -t

        if len(ps) == 0:
            memo[t] = 0
            return 0

        memo[t] = list(ps)[0] + 1
        return memo[t]

    def _path(tt,ss):
        q = [(tt,ss)]
        tq = []
        qi = 0
        while len(q) > qi:
            t,s = q[qi]
            for k in d[t]:
                if k == s:
                    continue
                q.append((k,t))
            qi += 1
        for t,s in q[::-1]:
            r = path(t,s)
            if r < 0:
                return r
        return memo[tt]

    def _path2(tt,ss):
        q = [(tt,ss)]
        tq = []
        qi = 0
        while len(q) > qi:
            t,s = q[qi]
            for k in d[t]:
                if k == s or memo[k] >= 0:
                    continue
                q.append((k,t))
            qi += 1
        for t,s in q[::-1]:
            r = path(t,s)
            if r < 0:
                return r
        return memo[tt]

    t = _path(1,-1)
    if t < 0:
        t = _path2(-t,-1)

    if t > 0:
        while t%2 == 0:
            t//=2
        return t

    return -1

print(main())


Solve in Python:
Variation of this nice kata, the war has expanded and become dirtier and meaner; both even and odd numbers will fight with their pointy `1`s. And negative integers are coming into play as well, with, ça va sans dire, a negative contribution (think of them as spies or saboteurs).

Again, three possible outcomes: `odds win`, `evens win` and `tie`.

Examples:

```python
bits_war([1,5,12]) => "odds win" #1+101 vs 1100, 3 vs 2
bits_war([7,-3,20]) => "evens win" #111-11 vs 10100, 3-2 vs 2
bits_war([7,-3,-2,6]) => "tie" #111-11 vs -1+110, 3-2 vs -1+2
```

bits_war=lambda n: (lambda s: "evens win" if s>0 else "odds win" if s else "tie")(sum(bin(d)[2:].count("1")*(-1)**((d%2 or d<0)-(d%2 and d<0)) for d in n))


Solve in Python:
Vasily has a deck of cards consisting of n cards. There is an integer on each of the cards, this integer is between 1 and 100 000, inclusive. It is possible that some cards have the same integers on them.

Vasily decided to sort the cards. To do this, he repeatedly takes the top card from the deck, and if the number on it equals the minimum number written on the cards in the deck, then he places the card away. Otherwise, he puts it under the deck and takes the next card from the top, and so on. The process ends as soon as there are no cards in the deck. You can assume that Vasily always knows the minimum number written on some card in the remaining deck, but doesn't know where this card (or these cards) is.

You are to determine the total number of times Vasily takes the top card from the deck.

-----Input-----

The first line contains single integer n (1 ≤ n ≤ 100 000) — the number of cards in the deck.

The second line contains a sequence of n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 100 000), where a_{i} is the number written on the i-th from top card in the deck.

-----Output-----

Print the total number of times Vasily takes the top card from the deck.

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

Output
7

Input
1
1000

Output
1

Input
7
3 3 3 3 3 3 3

Output
7

-----Note-----

In the first example Vasily at first looks at the card with number 6 on it, puts it under the deck, then on the card with number 3, puts it under the deck, and then on the card with number 1. He places away the card with 1, because the number written on it is the minimum among the remaining cards. After that the cards from top to bottom are [2, 6, 3]. Then Vasily looks at the top card with number 2 and puts it away. After that the cards from top to bottom are [6, 3]. Then Vasily looks at card 6, puts it under the deck, then at card 3 and puts it away. Then there is only one card with number 6 on it, and Vasily looks at it and puts it away. Thus, in total Vasily looks at 7 cards.

from collections import deque
import heapq

n = int(input())
cards_help = list(map(int, input().split()))
cards = [ (cards_help[i],-1*i) for i in range(n) ]
heapq.heapify(cards)

draws = 0
removed = 0
while cards:
    prev = -1
    new_removals = 0
    current = cards[0]
    while cards and -1*current[1] > prev:
        new_removals += 1
        heapq.heappop(cards)
        temp_prev = -1*current[1]
        while cards and cards[0][0] == current[0] and -1*cards[0][1] > prev:
            current = cards[0]
            heapq.heappop(cards)
            new_removals += 1
        prev = temp_prev
        current = cards[0] if cards else 0
    draws += n - removed
    removed += new_removals
print(draws)

# Made By Mostafa_Khaled


Solve in Python:
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i. e. creates a new string t = s_{k} + 1s_{k} + 2... s_{n}s_1s_2... s_{k}. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.

Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability.

Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.

-----Input-----

The only string contains the string s of length l (3 ≤ l ≤ 5000), consisting of small English letters only.

-----Output-----

Print the only number — the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10^{ - 6}.

Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if $\frac{|a - b|}{\operatorname{max}(1,|b|)} \leq 10^{-6}$

-----Examples-----
Input
technocup

Output
1.000000000000000

Input
tictictactac

Output
0.333333333333333

Input
bbaabaabbb

Output
0.100000000000000

-----Note-----

In the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.

In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth...

def func(a):
    b=[0]*26
    for i in range(len(a)):
        b[ord(a[i])-ord("a")]+=1
    c=0
    for i in b:
        if i==1:
            c=c+1
    return c

s=input()
n=len(s)
a={}
for i in range(n):
    a[s[i]]=[]
for i in range(n):
    a[s[i]].append(i)
c=0
for i in a:
    if len(a[i])==1:
        c=c+1
    else:
        e=[]
        for j in range(n):
            b=[]
            d=0
            for k in a[i]:
                b.append((s[(k+j)%n]))
            d=d+func(b)
            e.append(d)
        c=c+max(e)

print(c/n)


Solve in Python:
Vasya and Petya are playing a simple game. Vasya thought of number x between 1 and n, and Petya tries to guess the number.

Petya can ask questions like: "Is the unknown number divisible by number y?".

The game is played by the following rules: first Petya asks all the questions that interest him (also, he can ask no questions), and then Vasya responds to each question with a 'yes' or a 'no'. After receiving all the answers Petya should determine the number that Vasya thought of.

Unfortunately, Petya is not familiar with the number theory. Help him find the minimum number of questions he should ask to make a guaranteed guess of Vasya's number, and the numbers y_{i}, he should ask the questions about.

-----Input-----

A single line contains number n (1 ≤ n ≤ 10^3).

-----Output-----

Print the length of the sequence of questions k (0 ≤ k ≤ n), followed by k numbers — the questions y_{i} (1 ≤ y_{i} ≤ n).

If there are several correct sequences of questions of the minimum length, you are allowed to print any of them.

-----Examples-----
Input
4

Output
3
2 4 3

Input
6

Output
4
2 4 3 5

-----Note-----

The sequence from the answer to the first sample test is actually correct.

If the unknown number is not divisible by one of the sequence numbers, it is equal to 1.

If the unknown number is divisible by 4, it is 4.

If the unknown number is divisible by 3, then the unknown number is 3.

Otherwise, it is equal to 2. Therefore, the sequence of questions allows you to guess the unknown number. It can be shown that there is no correct sequence of questions of length 2 or shorter.

import math
import array
def is_prime(x):
    i = 2
    while(i <= math.sqrt(x)):
        if(x % i == 0):
            return False
        i = i + 1
    return True
answer_list = []
n = int(input())
i = 2
answer = 0
while(i <= n):
    if(is_prime(i)):
        answer = answer + 1
        answer_list.append(i)
        j = i*i
        while(j <= n):
            answer = answer + 1
            answer_list.append(j)
            j = j * i
    i = i + 1
print(answer)
for x in answer_list:
    print(x, end = ' ')


Solve in Python:
Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rectangles.

-----Input-----

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

Each test case is given in two lines.

The first line contains two integers $a_1$ and $b_1$ ($1 \le a_1, b_1 \le 100$) — the dimensions of the first one obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length).

The second line contains two integers $a_2$ and $b_2$ ($1 \le a_2, b_2 \le 100$) — the dimensions of the second obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length).

-----Output-----

Print $t$ answers, each of which is a string "YES" (in the case of a positive answer) or "NO" (in the case of a negative answer). The letters in words can be printed in any case (upper or lower).

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

Output
Yes
Yes
No

import sys,bisect,string,math,time,functools,random
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
def Golf():*a,=map(int,open(0))
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
#h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0}) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in range(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def bit_combination(k,n=2):
    rt=[]
    for tb in range(n**k):
        s=[tb//(n**bt)%n for bt in range(k)];rt+=[s]
    return rt
def show(*inp,end='\n'):
    if...