Solve in Python:
The Fibonacci numbers are the numbers in the following integer sequence (Fn):
>0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ...

such as
>F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1.

Given a number, say prod (for product), we search two Fibonacci numbers F(n) and F(n+1) verifying
>F(n) * F(n+1) = prod.

Your function productFib takes an integer (prod) and returns
an array:
```
[F(n), F(n+1), true] or {F(n), F(n+1), 1} or (F(n), F(n+1), True)
```
depending on the language if F(n) * F(n+1) = prod.

If you don't find two consecutive F(m) verifying `F(m) * F(m+1) = prod`you will return
```
[F(m), F(m+1), false] or {F(n), F(n+1), 0} or (F(n), F(n+1), False)
```
F(m) being the smallest one such as `F(m) * F(m+1) > prod`.

### Some Examples of Return:
(depend on the language)

```
productFib(714) # should return (21, 34, true),
                # since F(8) = 21, F(9) = 34 and 714 = 21 * 34

productFib(800) # should return (34, 55, false),
                # since F(8) = 21, F(9) = 34, F(10) = 55 and 21 * 34 < 800 < 34 * 55
-----
productFib(714) # should return [21, 34, true],
productFib(800) # should return [34, 55, false],
-----
productFib(714) # should return {21, 34, 1},
productFib(800) # should return {34, 55, 0},
-----
productFib(714) # should return {21, 34, true},
productFib(800) # should return {34, 55, false},
```

### Note:

- You can see examples for your language in "Sample Tests".

def productFib(prod):
    nums = [0,1]
    i = 0
    status = True
    while status:
        if nums[i]*nums[i+1] <= prod:
            nums.append(nums[i]+nums[i+1])
            i+=1
        else:
            status = False
    i = 0
    while i < len(nums):
        if nums[i]*nums[i+1] == prod:
            return [nums[i],nums[i+1],True]
        elif prod in range(nums[i-1]*nums[i],nums[i]*nums[i+1]):
            return [nums[i],nums[i+1],False]
        i+=1


Solve in Python:
The Fibonacci sequence $F_0, F_1, \ldots$ is a special infinite sequence of non-negative integers, where $F_0 = 0$, $F_1 = 1$ and for each integer $n \ge 2$, $F_n = F_{n-1} + F_{n-2}$.
Consider the sequence $D$ of the last decimal digits of the first $N$ Fibonacci numbers, i.e. $D = (F_0 \% 10, F_1 \% 10, \ldots, F_{N-1} \% 10)$. Now, you should perform the following process:
- Let $D = (D_1, D_2, \ldots, D_l)$.
- If $l = 1$, the process ends.
- Create a new sequence $E = (D_2, D_4, \ldots, D_{2 \lfloor l/2 \rfloor})$. In other words, $E$ is the sequence created by removing all odd-indexed elements from $D$.
- Change $D$ to $E$.
When this process terminates, the sequence $D$ contains only one number. You have to find this number.

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

-----Output-----
For each test case, print a single line containing one integer ― the last remaining number.

-----Constraints-----
- $1 \le T \le 10^5$
- $1 \le N \le 10^{18}$

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

-----Example Input-----
1
9

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

-----Explanation-----
Example case 1: The first $N$ Fibonacci numbers are $(0, 1, 1, 2, 3, 5, 8, 13, 21)$. The sequence $D$ is $(0, 1, 1, 2, 3, 5, 8, 3, 1) \rightarrow (1, 2, 5, 3) \rightarrow (2, 3) \rightarrow (3)$.


Solve in Python:
The Fibonacci sequence is defined as F(n) = F(n-1) + F(n-2). You have developed two sequences of numbers. The first sequence that uses the bitwise XOR operation instead of the addition method is called the Xoronacci number. It is described as follows:
X(n) = X(n-1) XOR X(n-2)
The second sequence that uses the bitwise XNOR operation instead of the addition method is called the XNoronacci number. It is described as follows:
E(n) = E(n-1) XNOR E(n-2)
The first and second numbers of the sequence are as follows:
X(1) = E(1) = a
X(2) = E(2) = b
Your task is to determine the value of max(X(n),E(n)), where n is the n th term of the Xoronacci and XNoronacci sequence.

-----Input:-----
The first line consists of a single integer T denoting the number of test cases.
The first and the only line of each test case consists of three space separated integers a, b and n.

-----Output:-----
For each test case print a single integer max(X(n),E(n)).

-----Constraints-----
- $1 \leq T \leq 1000$
- $2 \leq a,b,n \leq 1000000000000$

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

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

-----EXPLANATION:-----
Xoronacci Sequence : 3 4 7 …….
XNoronacci Sequence : 3 4 0 …….
Here n = 2. Hence max(X(2),E(2)) = 4

# Python3 program to find XNOR
# of two numbers
import math

def swap(a, b):
 temp = a
 a = b
 b = temp

# log(n) solution
def xnor(a, b):
 # Make sure a is larger
 if (a < b):
  swap(a, b)

 if (a == 0 and b == 0):
  return 1;

 # for last bit of a
 a_rem = 0

 # for last bit of b
 b_rem = 0

 # counter for count bit and
 # set bit in xnor num
 count = 0

 # for make new xnor number
 xnornum = 0

 # for set bits in new xnor
 # number
 while (a != 0):

  # get last bit of a
  a_rem = a & 1

  # get last bit of b
  b_rem = b & 1

  # Check if current two
  # bits are same
  if (a_rem == b_rem):
   xnornum |= (1 << count)

  # counter for count bit
  count = count + 1

  a = a >> 1
  b = b >> 1

 return xnornum;

t= int(input())
for o in range(t):
 a,b,n=map(int,input().split())
 c=a^b
 x=bin(c)
 x=x.split("b")
 x=x[1]
 x=len(x)
 d=xnor(a,b)
 p=[a,b,c];r=[a,b,d]
 k=n%3-1
 if p[k]>r[k]:
  print(p[k])
 else :
  print(r[k])


Solve in Python:
The GoC Timber Mafia is notorious for its deforestation
activities in the forests near Siruseri. These activities have
increased multifold after the death of the bandit who used to
lord over these jungles.  Having lost the battle to prevent the
Mafia from illegally felling the teak trees in this forest, the
government of Siruseri came up with a novel idea.  Why not
legalise the deforestation activity and at least make some money
in the process? So the Government decided to lease out parts of
the forest to the Timber Mafia.
Most of the teak trees in the forests of Siruseri were planted
during the colonial times, after the native trees had been cut.
Like everything European, the forest is very regular and
orderly. It is rectangular in shape and the trees are arranged in
uniformly spaced rows and coloumns.
Since the trees differ in height and girth, the timber value
differs from tree to tree.  The forest department has collected
data on each tree and knows the volume of wood (in cubic feet)
available in each tree in the forest.
The forest department maintains this information in the form of
an $M \times N$ array of integers, where the
$(i, j)$th entry is the volume, in cubic feet, of the
$i^{th}$ tree on the $i^{th}$ row (or, equivalently, the
$i^{th}$ tree on the $i^{th}$ column).  We assume that
our rows are numbered top to bottom and the columns are numbered
from left to right.  For example, such an array could look like

This array tells us that  the volume of the tree at position $(3,4)$ is $15$
cubic feet and so on.
Any rectangular piece of land with trees at each corner can be
leased out.  In order to fix the lease price for any rectangular
plot of the forest the forest department needs to know the amount
of wood available inside the plot.
A rectangular plot is described by the positions of the trees in
its top left corner and the bottom right corner. For example the
positions $(2,2)$ and $(3,4)$ describes the following part
rectangular part of the above forest.

The total amount of wood available in this...

# cook your dish here
from sys import stdin
n, m = map(int,stdin.readline().split())
forest=[]
matrix=[]
for _ in range(n):
 forest.append(list(map(int,stdin.readline().split())))
 matrix.append([0]*m)
matrix[0][0]=forest[0][0]
for j in range(1,m):
 matrix[0][j]=matrix[0][j-1]+forest[0][j]
for i in range(1,n):
 matrix[i][0]=matrix[i-1][0]+forest[i][0]
for i in range(1,n):
 for j in range(1,m):
  matrix[i][j]=matrix[i-1][j]+matrix[i][j-1]-matrix[i-1][j-1]+forest[i][j]
c=int(input())
for _ in range(c):
 x1, y1, x2, y2 = map(int,stdin.readline().split())
 x1-=1
 y1-=1
 x2-=1
 y2-=1
 appo=0
 if x1>0:
  appo+=matrix[x1-1][y2]
 if y1>0:
  appo+=matrix[x2][y1-1]
 if x1>0 and y1>0:
  appo-=matrix[x1-1][y1-1]
 print(matrix[x2][y2]-appo)


Solve in Python:
The Golomb sequence $G_1, G_2, \ldots$ is a non-decreasing integer sequence such that for each positive integer $n$, $G_n$ is the number of occurrences of $n$ in this sequence. The first few elements of $G$ are $[1, 2, 2, 3, 3, 4, 4, 4, 5, \ldots]$. Do you know the recurrence relation for the Golomb sequence? It is $G_1 = 1$ and $G_{n+1} = 1+G_{n+1-G_{G_n}}$ for each $n \ge 1$. A self-describing sequence, isn't it?
Mr. Strange wants to learn CP, so he asked Chef, who is one of the best competitive programmers in the world, to teach him. Chef decided to test his ability by giving him the following task.
Find the sum of squares of the $L$-th through $R$-th term of the Golomb sequence, i.e. $S = \sum_{i=L}^R G_i^2$. Since the sum can be quite large, compute it modulo $10^9+7$.
Can you help Mr. Strange carry out this task given to him by his teacher?

-----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 $L$ and $R$.

-----Output-----
For each test case, print a single line containing one integer $S$ modulo $10^9+7$.

-----Constraints-----
- $1 \le T \le 10^5$
- $1 \le L \le R \le 10^{10}$

-----Subtasks-----
Subtask #1 (50 points):
- $T \le 10^2$
- $R \le 10^9$
Subtask #2 (50 points): original constraints

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

-----Example Output-----
27
17
441

-----Explanation-----
Example case 1: $1^2 + 2^2 + 2^2 + 3^2 + 3^2 = 27$
Example case 2: $2^2 + 2^2 + 3^2 = 17$
Example case 3: $21^2 = 441$

# cook your dish here
import bisect as bi

temp_g = [0, 1, 2]
temp_s = [0, 1, 9]
temp_p = [0, 1, 3]
max_mod = (10 ** 9 + 7)

def find_gn(n):
 return (1 + temp_g[n - temp_g[temp_g[n - 1]]])

def find_sn(n, gn):
 return (temp_s[n - 1] + gn * n**2) % max_mod

def find_pn(n, gn):
 return (temp_p[n - 1] + gn)

def bisection(x):
 n = bi.bisect_right(temp_p, x)
 return (temp_s[n - 1] + (x - temp_p[n - 1]) * n**2 ) % max_mod

lr, max_ = [], 100

for _ in range(int(input())):
 l, r = list(map(int, input().split()))
 lr.append((l, r))
 max_ = max(max_, r + 1)

for n in range(3, 2 * (10 ** 8), 1):
 gn = find_gn(n)
 sn, pn = find_sn(n, gn), find_pn(n, gn)
 temp_g.append(gn)
 temp_p.append(pn)
 temp_s.append(sn)
 if (pn > max_):
  break

for pair in lr:
 print(bisection(pair[1]) - bisection(pair[0] - 1) % max_mod)


Solve in Python:
The Government of Siruseri is no different from any other when it comes to being "capital-centric" in its policies. Recently the government decided to set up a nationwide fiber-optic network to take Siruseri into the digital age. And as usual, this decision was implemented in a capital centric manner --- from each city in the country, a fiber optic cable was laid to the capital! Thus, traffic between any two cities had to go through the capital.
Soon, it became apparent that this was not quite a clever idea, since any breakdown at the capital resulted in the disconnection of services between other cities. So, in the second phase, the government plans to connect a few more pairs of cities directly by fiber-optic cables. The government has specified that this is to be done in such a way that the disruption of services at any one city will still leave the rest of the country connected.
The government has data on the cost of laying fiber optic cables between every pair of cities. You task is to compute the minimum cost of additional cabling required to ensure the requirement described above is met.
For example, if Siruseri has $4$ cities numbered $1,2,3$ and $4$ where $1$ is the capital and further suppose that the cost of laying cables between these cities are as given in the table below:

Note that the government has already connected the capital with every other city. So, if we connect the cities $2$ and $3$ as well as $3$ and $4$, you can check that disruption of service at any one city will still leave the other cities connected. The cost of connecting these two pairs is $4 + 6 = 10$. The same effect could have been achieved by connecting $2$ and $3$ as well as $2$ and $4$, which would have cost $4 + 5 = 9$. You can check that this is the best you can do.
Your task is to write a program that allows the government to determine the minimum cost it has to incur in laying additional cables to fulfil the requirement.

-----Input:-----
- The first line of the input contains a single integer $N$ indicating the...

n=int(input())
l=[]
for i in range(n):
	l.append([int(x) for x in input().split()])
d=[10**9]*(n)
q=set([int(x) for x in range(1,n)])
d[1]=0
#print(q)
def extract():
	mini=10**9
	o=0
	for i in range(1,len(d)):
		if d[i]<mini and i in q:
			mini=d[i]
			o=i
	q.remove(o)
	return o
while len(q)!=0:
	x=extract()
	for i in range(1,n):
		if i in q and l[x][i]<d[i]:
			d[i]=l[x][i]
print(sum(d[1:]))


Solve in Python:
The Gray code (see wikipedia for more details) is a well-known concept.
One of its important properties is that every two adjacent numbers have exactly one different digit in their binary representation.

In this problem, we will give you n non-negative integers in a sequence A[1..n] (0<=A[i]<2^64), such that every two adjacent integers have exactly one different digit in their binary representation, similar to the Gray code.

Your task is to check whether there exist 4 numbers A[i1], A[i2], A[i3], A[i4] (1 <= i1 < i2 < i3 < i4 <= n) out of the given n numbers such that A[i1] xor A[i2] xor A[i3] xor A[i4] = 0. Here xor is a bitwise operation which is same as ^ in C, C++, Java and xor in Pascal.

-----Input-----
First line contains one integer n (4<=n<=100000).
Second line contains n space seperated non-negative integers denoting the sequence A.

-----Output-----
Output “Yes” (quotes exclusive) if there exist four distinct indices i1, i2, i3, i4 such that A[i1] xor A[i2] xor A[i3] xor A[i4] = 0. Otherwise, output "No" (quotes exclusive) please.

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

5
1 0 2 3 7

Output:

Yes

n=int(input())
hit=list(map(int,input().split()))

d={}
for i in range(1,n):
 x1,x2=hit[i],hit[i-1]
 try: d[x1^x2]+=[i]
 except: d[x1^x2]=[i]

done=False
for i in d:
 x=d[i]
 if len(x)>2: done=True; break
 elif len(x)==2:
  x=sorted(x)
  if x[0]!=x[1]-1: done=True; break

if done: print('Yes')
else:
 v={}
 for i in hit:
  try: v[i]+=1
  except: v[i]=1
 x={}
 h=list(v.values())
 for i in h:
  try: x[i]+=1
  except: x[i]=1
 if ( 2 in x and x[2]==2 ) or ( 4 in x and x[4]==1 ): print('Yes')
 else: print('No')


Solve in Python:
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

Note:
0 ≤ x, y < 231.

Example:

Input: x = 1, y = 4

Output: 2

Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

The above arrows point to positions where the corresponding bits are different.

class Solution:
     def hammingDistance(self, x, y):
         """
         :type x: int
         :type y: int
         :rtype: int
         """
         xor_result = x^y
         count = 0
         while xor_result > 0:
             count += xor_result & 1
             xor_result = xor_result >> 1

         return count


Solve in Python:
The Head Chef is receiving a lot of orders for cooking the best of the problems lately. For this, he organized an hiring event to hire some talented Chefs. He gave the following problem to test the skills of the participating Chefs. Can you solve this problem and be eligible for getting hired by Head Chef.

A non-negative number n is said to be magical if it satisfies the following property. Let S denote the multi-set of numbers corresponding to the non-empty subsequences of the digits of the number n in decimal representation. Please note that the numbers in the set S can have leading zeros. Let us take an element s of the multi-set S, prod(s) denotes the product of all the digits of number s in decimal representation.
The number n will be called magical if sum of prod(s) for all elements s in S, is even.

For example, consider a number 246, its all possible non-empty subsequence will be S = {2, 4, 6, 24, 46, 26, 246}. Products of digits of these subsequences will be {prod(2) = 2, prod(4) = 4, prod(6) = 6, prod(24) = 8, prod(46) = 24, prod(26) = 12, prod(246) = 48, i.e. {2, 4, 6, 8, 24, 12, 48}. Sum of all of these is 104, which is even. Hence 246 is a magical number.

Please note that multi-set S can contain repeated elements, e.g. if number is 55, then S = {5, 5, 55}. Products of digits of these subsequences will be {prod(5) = 5, prod(5) = 5, prod(55) = 25}, i.e. {5, 5, 25}. Sum of all of these is 35 which is odd. Hence 55 is not a
magical number.

Consider a number 204, then S = {2, 0, 4, 20, 04, 24, 204}. Products of digits of these subsequences will be {2, 0, 4, 0, 0, 8, 0}. Sum of all these elements will be 14 which is even. So 204 is a magical number.

The task was to simply find the Kth magical number.

-----Input-----
- First line of the input contains an integer T denoting the number of test cases.
- Each of the next T lines contains a single integer K.

-----Output-----
For each test case, print a single integer corresponding to the Kth magical number.

-----Constraints-----
- 1 ≤ T ≤ 105
- 1 ≤...

def cheffun(k):
    return 10 * cheffun(k // 5) + (k % 5) * 2 if k else 0
g=eval(input())
while (g>0):
    a=eval(input())
    k=a-1
    print(cheffun(k))
    g=g-1


Solve in Python:
The Jones Trucking Company tracks the location of each of its trucks on a grid similar to an (x, y) plane. The home office is at the location (0, 0). Read the coordinates of truck A and the coordinates of truck B and determine which is closer to the office.

-----Input:-----
The first line of the data set for this problem is an integer representing the number of collections of data that follow. Each collection contains 4 integers: the x-coordinate and then the
y-coordinate of truck A followed by the x-coordinate and then the  y-coordinate of truck B.

-----Output:-----
All letters are upper case.
The output is to be formatted exactly like that for the sample output given below.

-----Assumptions:-----
The x-coordinate is in the range –20 .. 20. The y-coordinate is in the range –20 .. 20.

-----Discussion:-----
The distance between point #1 with coordinates (x1, y1) and point #2 with coordinates (x2, y2) is:

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

-----Sample Output:-----
A IS CLOSER
B IS CLOSER
B IS CLOSER
B IS CLOSER

t = int(input())
for x in range(t):
 a = [int(x) for x in input().split()]
 d1 = (a[0]**2 + a[1]**2)**0.5
 d2 = (a[2] ** 2 + a[2] ** 2) ** 0.5

 if d1 < d2:
  print("A IS CLOSER")
 else:
  print("B IS CLOSER")


Solve in Python:
The Leetcode file system keeps a log each time some user performs a change folder operation.
The operations are described below:

"../" : Move to the parent folder of the current folder. (If you are already in the main folder, remain in the same folder).
"./" : Remain in the same folder.
"x/" : Move to the child folder named x (This folder is guaranteed to always exist).

You are given a list of strings logs where logs[i] is the operation performed by the user at the ith step.
The file system starts in the main folder, then the operations in logs are performed.
Return the minimum number of operations needed to go back to the main folder after the change folder operations.

Example 1:

Input: logs = ["d1/","d2/","../","d21/","./"]
Output: 2
Explanation: Use this change folder operation "../" 2 times and go back to the main folder.

Example 2:

Input: logs = ["d1/","d2/","./","d3/","../","d31/"]
Output: 3

Example 3:
Input: logs = ["d1/","../","../","../"]
Output: 0

Constraints:

1 <= logs.length <= 103
2 <= logs[i].length <= 10
logs[i] contains lowercase English letters, digits, '.', and '/'.
logs[i] follows the format described in the statement.
Folder names consist of lowercase English letters and digits.

class Solution:
    def minOperations(self, logs: List[str]) -> int:
        c = 0
        i = 0
        while i<len(logs):
            if logs[i] == '../':
                if c != 0:
                    c -= 1
            elif logs[i] == './':
                pass
            else:
                c += 1
            i += 1
        return c


Solve in Python:
The Little Elephant and his friends from the Zoo of Lviv were returning from the party. But suddenly they were stopped by the policeman Big Hippo, who wanted to make an alcohol test for elephants.
There were N elephants ordered from the left to the right in a row and numbered from 0 to N-1. Let R[i] to be the result of breathalyzer test of i-th elephant.
Considering current laws in the Zoo, elephants would be arrested if there exists K consecutive elephants among them for which at least M of these K elephants have the maximal test result among these K elephants.
Using poor math notations we can alternatively define this as follows. The elephants would be arrested if there exists i from 0 to N-K, inclusive, such that for at least M different values of j from i to i+K-1, inclusive, we have R[j] = max{R[i], R[i+1], ..., R[i+K-1]}.

The Big Hippo is very old and the Little Elephant can change some of the results. In a single operation he can add 1 to the result of any elephant. But for each of the elephants he can apply this operation at most once.
What is the minimum number of operations that the Little Elephant needs to apply, such that the sequence of results, after all operations will be applied, let elephants to avoid the arrest? If it is impossible to avoid the arrest applying any number of operations, output -1.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains three space-separated integers N, K, M. The second line contains N space-separated integers  R[0], R[1], ..., R[N-1] denoting the test results of the elephants.

-----Output-----
For each test case, output a single line containing the minimum number of operations needed to avoid the arrest.

-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ M ≤ K ≤ N ≤ 17
- 1 ≤ R[i] ≤ 17

-----Example-----
Input:
4
5 3 2
1 3 1 2 1
5 3 3
7 7 7 7 7
5 3 3
7 7 7 8 8
4 3 1
1 3 1 2

Output:
0
1
1
-1

-----Explanation-----
Example case 1. Let's...

def magic():
 def check(art,k,m):
  n=len(art)
  for i in range(n-k+1):
   maxi=0
   maxi=max(art[i:i+k])

   total=0
   total=art[i:i+k].count(maxi)

   if total>=m:
    return False

  return True

 for _ in range(eval(input())):
  n,k,m=list(map(int,input().split()))
  arr=list(map(int,input().split()))
  dp=[]
  ans=100

  for mask in range(0,(1<<n)):
   size=bin(mask).count('1')

   if ans>size:
    art=list(arr)
    for i in range(n):
     if mask & (1<<i):
      art[i]+=1

    if check(art,k,m):
     ans=size

  print(ans if ans!=100 else -1)
magic()


Solve in Python:
The Little Elephant from the Zoo of Lviv currently is on the military mission. There are N enemy buildings placed in a row and numbered from left to right strating from 0. Each building i (except the first and the last) has exactly two adjacent buildings with indices i-1 and i+1. The first and the last buildings have just a single adjacent building.

Some of the buildings contain bombs. When bomb explodes in some building it destroys it and all adjacent to it buildings.

You are given the string S of length N, where Si is 1 if the i-th building contains bomb, 0 otherwise. Find for the Little Elephant the number of buildings that will not be destroyed after all bombs explode. Please note that all bombs explode simultaneously.

-----Input-----
The first line contains single integer T - the number of test cases. T test cases follow. The first line of each test case contains the single integer N - the number of buildings. The next line contains the string S of length N consisted only of digits 0 and 1.

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

-----Constraints-----

1 <= T <= 100

1 <= N <= 1000

-----Example-----
Input:
3
3
010
5
10001
7
0000000

Output:
0
1
7

inputs = int(input())
while inputs > 0:
 length = int(input())
 building = input()
 buildings = []
 if length != 0:
  for i in range(0,length):
   buildings.append(int(building[i]))
  if buildings[0] == 1:
   buildings[0] = 2
   if length > 1:
    if buildings[1] == 0:
     buildings[1] = 2
  for i in range(1, length-1):
   if buildings[i] == 1:
    buildings[i] = 2
    if buildings[i+1] == 0:
     buildings[i+1] = 2
    if buildings[i-1] == 0:
     buildings[i-1] = 2
  if buildings[length-1] == 1:
   buildings[length-1] = 2
   if buildings[length-2] == 0:
    buildings[length-2] = 2
  print(buildings.count(0))
 else:
  print(0)
 inputs = inputs - 1


Solve in Python:
The Little Elephant from the Zoo of Lviv has an array A that consists of N positive integers. Let A[i] be the i-th number in this array (i = 1, 2, ..., N).

Find the minimal number x > 1 such that x is a divisor of all integers from array A. More formally, this x should satisfy the following relations:

A[1] mod x = 0, A[2] mod x = 0, ..., A[N] mod x = 0,

where mod stands for the modulo operation. For example,  8 mod 3 = 2,  2 mod 2 = 0, 100 mod 5 = 0 and so on. If such number does not exist, output -1.

-----Input-----

The first line of the input contains a single integer T, the number of test cases. T test cases follow. The first line of each test case contains a single integer N, the size of the array A for the corresponding test case. The second line contains N space separated integers A[1], A[2], ..., A[N].

-----Output-----

For each test case output a single line containing the answer for the corresponding test case.

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

1 ≤ N ≤ 100000

The sum of values of N in each test file does not exceed 100000

1 ≤ A[i] ≤ 100000

-----Example-----
Input:
2
3
2 4 8
3
4 7 5

Output:
2
-1

-----Explanation-----
Case 1. Clearly 2 is a divisor of each of the numbers 2, 4 and 8. Since 2 is the least number greater than 1 then it is the answer.

Case 2. Let's perform check for several first values of x.

x4 mod x7 mod x5 mod x20113112403154206415740584759475

As we see each number up to 9 does not divide all of the numbers in the array. Clearly all larger numbers also will fail to do this. So there is no such number x > 1 and the answer is -1.

import math
def solve():
    n = int(input())
    a = list(map(int, input().split()))
    x = a[0]
    for i in a:
        x = math.gcd(i, x)
    if x == 1:
        k = -1
    else:
        k = x
        x1 = x ** 0.5
        t = int(x1)
        for i in range(2, t + 1):
            if x % i == 0:
                k = i
                break
    print(k)

def __starting_point():
    t = int(input())
    while t != 0:
        solve()
        t -= 1
__starting_point()


Solve in Python:
The Little Elephant from the Zoo of Lviv is going to the Birthday Party of  the Big Hippo tomorrow. Now he wants to prepare a gift for the Big Hippo.

He has N balloons, numbered from 1 to N. The i-th balloon has the color Ci and it costs Pi dollars. The gift for the Big Hippo will be any subset (chosen randomly, possibly empty) of the balloons such that the number of different colors in that subset is at least M.

Help Little Elephant to find the expected cost of the gift.

-----Input-----
The first line of the input contains a single integer T - the number of test cases. T test cases follow. The first line of each test case contains a pair of integers N and M. The next N lines contain N pairs of integers Ci and Pi, one pair per line.

-----Output-----
In T lines print T real numbers - the answers for the corresponding test cases. Your answer will considered correct if it has at most 10^-6 absolute or relative error.

-----Constraints-----
- 1 ≤ T ≤ 40
- 1 ≤ N,  Ci≤ 40
- 1 ≤ Pi ≤ 1000000
- 0 ≤ M ≤ K, where K is the number of different colors in the test case.

-----Example-----
Input:
2
2 2
1 4
2 7
2 1
1 4
2 7

Output:
11.000000000
7.333333333

# cook your dish here
for _ in range(int(input())):
    n,m = list(map(int,input().split()))
    colors = [0]*41; cost = [0]*41
    color = 0
    for i in range(n):
        cc,pp = list(map(int,input().split()))
        colors[cc] += 1
        cost[cc] += pp
    for i in colors:
        if i>0: color += 1
    dp2 = [[0]*41 for i in range(color+1)]
    dp2[0] = [1]*41
    for i in range(1,color+1):
        for j in range(1,41):
            dp2[i][j] = dp2[i][j-1]+dp2[i-1][j-1]*(2**colors[j]-1)
    dp1 = [[0]*41 for i in range(color+1)]
    for i in range(1,color+1):
        for j in range(1,41):
            dp1[i][j] = dp1[i][j-1]+dp1[i-1][j-1]*(2**colors[j]-1)+dp2[i-1][j-1]*cost[j]*(2**(colors[j]-1))
    num=den=0
    for i in range(m,color+1):
        num += dp1[i][40]
        den += dp2[i][40]
    print(num/den)


Solve in Python:
The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper.

To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of the remaining binary digits, written in the corresponding order (possible, with leading zeroes).

The Little Elephant wants the number he is going to write on the paper to be as large as possible. Help him find the maximum number that he can obtain after deleting exactly one binary digit and print it in the binary notation.

-----Input-----

The single line contains integer a, written in the binary notation without leading zeroes. This number contains more than 1 and at most 10^5 digits.

-----Output-----

In the single line print the number that is written without leading zeroes in the binary notation — the answer to the problem.

-----Examples-----
Input
101

Output
11

Input
110010

Output
11010

-----Note-----

In the first sample the best strategy is to delete the second digit. That results in number 11_2 = 3_10.

In the second sample the best strategy is to delete the third or fourth digits — that results in number 11010_2 = 26_10.

# coding: utf-8
a = input()
pos = a.find('0')
if pos==-1:
    print(a[:-1])
else:
    print(a[:pos]+a[pos+1:])


Solve in Python:
The Little Elephant likes permutations. This time he has a permutation A[1], A[2], ..., A[N] of numbers 1, 2, ..., N.

He calls a permutation A good, if the number of its inversions is equal to the number of its local inversions. The number of inversions is equal to the number of pairs of integers (i; j) such that 1 ≤ i < j ≤ N and A[i] > A[j], and the number of local inversions is the number of integers i such that 1 ≤ i < N and A[i] > A[i+1].

The Little Elephant has several such permutations. Help him to find for each permutation whether it is good or not. Print YES for a corresponding test case if it is good and NO otherwise.

-----Input-----

The first line of the input contains a single integer T, the number of test cases. T test cases follow. The first line of each test case contains a single integer N, the size of a permutation. The next line contains N space separated integers A[1], A[2], ..., A[N].

-----Output-----

For each test case output a single line containing the answer for the corresponding test case. It should be YES if the corresponding permutation is good and NO otherwise.

-----Constraints-----
1 ≤ T ≤ 474

1 ≤ N ≤ 100

It is guaranteed that the sequence A[1], A[2], ..., A[N] is a permutation of numbers 1, 2, ..., N.

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

Output:
YES
YES
NO
YES

-----Explanation-----
Case 1. Here N = 1, so we have no pairs (i; j) with 1 ≤ i < j ≤ N. So the number of inversions is equal to zero. The number of local inversion is also equal to zero. Hence this permutation is good.

Case 2. Here N = 2, and we have one pair (i; j) with 1 ≤ i < j ≤ N, the pair (1; 2). Since A[1] = 2 and A[2] = 1 then A[1] > A[2] and the number of inversions is equal to 1. The number of local inversion is also equal to 1 since we have one value of i for which 1 ≤ i < N (the value i = 1) and A[i] > A[i+1] for this value of i since A[1] > A[2]. Hence this permutation is also good.

Case 3. Here N = 3, and we have three pairs (i; j) with 1 ≤ i < j ≤ N. We have A[1] = 3, A[2] =...

from sys import stdin
t = int(stdin.readline())

def count(n, arr):
 loc = 0
 glob = 0
 for i in range(n-1):
  if arr[i] > arr[i+1]:
   loc += 1
 for i in range(n-1):
  for j in range(i+1, n):
   if glob > loc:
    return 0
   if arr[i] > arr[j]:
    glob += 1;
 if glob == loc:
  return 1
 return 0

for _ in range(t):
 n = int(stdin.readline())
 arr = list(map(int, stdin.readline().split()))
 result = count(n, arr)
 if result:
  print("YES")
 else:
  print("NO")


Solve in Python:
The Little Elephant loves lucky strings. Everybody knows that the lucky string is a string of digits that contains only the lucky digits 4 and 7. For example, strings "47", "744", "4" are lucky while "5", "17", "467" are not.

The Little Elephant has the strings A and B of digits. These strings are of equal lengths, that is |A| = |B|. He wants to get some lucky string from them. For this he performs the following operations. At first he arbitrary reorders digits of A. Then he arbitrary reorders digits of B. After that he creates the string C such that its i-th digit is the maximum between the i-th digit of A and the i-th digit of B. In other words, C[i] = max{A[i], B[i]} for i from 1 to |A|. After that he removes from C all non-lucky digits saving the order of the remaining (lucky) digits. So C now becomes a lucky string. For example, if after reordering A = "754" and B = "873", then C is at first "874" and then it becomes "74".

The Little Elephant wants the resulting string to be as lucky as possible. The formal definition of this is that the resulting string should be the lexicographically greatest possible string among all the strings that can be obtained from the given strings A and B by the described process.
Notes
- |A| denotes the length of the string A.
- A[i] denotes the i-th digit of the string A. Here we numerate the digits starting from 1. So 1 ≤ i ≤ |A|.
- The string A is called lexicographically greater than the string B if either there exists some index i such that A[i] > B[i] and for each j < i we have A[j] = B[j], or B is a proper prefix of A, that is, |A| > |B| and first |B| digits of A coincide with the corresponding digits of B.

-----Input-----

The first line of the input contains a single integer T, the number of test cases. T test cases follow. Each test case consists of two lines. The first line contains the string A. The second line contains the string B.

-----Output-----

For each test case output a single line containing the answer for the corresponding test case. Note, that the...


Solve in Python:
The Little Elephant loves permutations of integers from 1 to n very much. But most of all he loves sorting them. To sort a permutation, the Little Elephant repeatedly swaps some elements. As a result, he must receive a permutation 1, 2, 3, ..., n.

This time the Little Elephant has permutation p_1, p_2, ..., p_{n}. Its sorting program needs to make exactly m moves, during the i-th move it swaps elements that are at that moment located at the a_{i}-th and the b_{i}-th positions. But the Little Elephant's sorting program happened to break down and now on every step it can equiprobably either do nothing or swap the required elements.

Now the Little Elephant doesn't even hope that the program will sort the permutation, but he still wonders: if he runs the program and gets some permutation, how much will the result of sorting resemble the sorted one? For that help the Little Elephant find the mathematical expectation of the number of permutation inversions after all moves of the program are completed.

We'll call a pair of integers i, j (1 ≤ i < j ≤ n) an inversion in permutatuon p_1, p_2, ..., p_{n}, if the following inequality holds: p_{i} > p_{j}.

-----Input-----

The first line contains two integers n and m (1 ≤ n, m ≤ 1000, n > 1) — the permutation size and the number of moves. The second line contains n distinct integers, not exceeding n — the initial permutation. Next m lines each contain two integers: the i-th line contains integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ n, a_{i} ≠ b_{i}) — the positions of elements that were changed during the i-th move.

-----Output-----

In the only line print a single real number — the answer to the problem. The answer will be considered correct if its relative or absolute error does not exceed 10^{ - 6}.

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

Output
0.500000000

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

Output
3.000000000

inp = input().split(' ')
val=[];

totNums = int(inp[0]); totOpt = int(inp[1]);
inp = input().split(' '); #assert(len(inp) == totNums);
for it in inp: val.append(int(it))

dp = [[0.0 for _ in range(0,totNums)] for __ in range(0,totNums)]
for i in range(0,totNums):
    for j in range(0,totNums):
        if val[i]>val[j]: dp[i][j] = 1.0

while totOpt>0:
    totOpt -= 1

    inp = input().split(' ')
    fr = int(inp[0])-1; to = int(inp[1])-1;

    for i in range(0,totNums):
        if i!=fr and i!=to:
            dp[i][fr] = dp[i][to] = (dp[i][fr] + dp[i][to]) / 2;
            dp[fr][i] = dp[to][i] = (dp[fr][i] + dp[to][i]) / 2;

    dp[fr][to] = dp[to][fr] = (dp[fr][to] + dp[to][fr]) / 2;

ans = 0.0
for i in range(0,totNums):
    for j in range(i+1,totNums):
        ans += dp[i][j]

print('%.10f'%ans)


Solve in Python:
The MEX of a set of integers is defined as the smallest non-negative integer that does not belong to this set. For example, $\mathrm{MEX}(\{0,2,3\}) = 1$ and $\mathrm{MEX}(\{1,3\}) = 0$.
Chef has a tree with $N$ nodes (numbered $1$ through $N$). The tree is rooted at node $1$. Chef wants to assign a non-negative integer to each node in such a way that each integer between $0$ and $N-1$ (inclusive) is assigned to exactly one node.
For each node $u$, consider the integers assigned to the nodes in the subtree of $u$ (including $u$); let $a_u$ denote the MEX of these integers. Chef wants $a_1 + a_2 + \ldots + a_N$ to be as large as possible. Find the maximum possible value of this sum.

-----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-1$ space-separated integers $p_1, p_2, \ldots, p_{N-1}$. For each valid $i$, the node $p_i$ is the parent of the node $i+1$.

-----Output-----
For each test case, print a single line containing one integer ― the maximum sum of subtree MEX-s which can be obtained if you assign the weights optimally.

-----Constraints-----
- $1 \le T \le 5$
- $2 \le N \le 10^5$
- $1 \le p_i < i$ for each valid $i$

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

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

-----Example Output-----
4
9

# cook your dish here
# cook your dish here
from math import log2;
import sys;

sys.setrecursionlimit(10 ** 7)
from collections import defaultdict

inf = float("inf")
def find_height(node):
    nodes[node]=1
    for i in graph[node]:
        nodes[node]+=find_height(i)
    return nodes[node]
def find_sum(node):
    suma=nodes[node]
    maxa=0
    for i in graph[node]:
        maxa=max(find_sum(i),maxa)
    return maxa+suma
for i in range(int(input())):
    n=int(input())
    l=list(map(int,input().split()))
    graph=defaultdict(set)
    for i in range(len(l)):

        graph[l[i]].add(i+2)
    nodes=defaultdict(int)
    find_height(1)
    ans=find_sum(1)
    print(ans)


Solve in Python:
The MarkiT online virtual market startup wants to organize its grand opening in NIT Patna.
but they want maximum crowd for their inauguration. So the manager told  this  to Praveen a student in NITP who suggested them:
The first-year students come to campus  every x hour,
Second-year students come to campus every y hour,
Third-year students come to campus every z hour and
Fourth-year is very busy so they don't come regularly.
So Praveen being very clever told him the no of times in n days he can have an audience of all year student (1st,2nd & 3rd) at max. So can you code what Praveen has done?

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a 2 line of input, first line contain one  integers $N$ (No of Days).
-Next line contain 3 space separated integer the  value of x y z

-----Output:-----
For each testcase, output in a single line answer the no of times audience consists of all year.

-----Constraints-----
- $1 \leq T \leq 1000$
- $1 \leq N \leq 10^8$
- $1 \leq x,y,z \leq 10^5$

-----Sample Input:-----
1
10
8 10 6

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

-----EXPLANATION:-----
First favourable condition will come on 5th day and Second on 10th day.

def find_lcm(num1, num2):
 if(num1>num2):
  num = num1
  den = num2
 else:
  num = num2
  den = num1
 rem = num % den
 while(rem != 0):
  num = den
  den = rem
  rem = num % den
 gcd = den
 lcm = int(int(num1 * num2)/int(gcd))
 return lcm

def crowd(days,x,y,z):
 hrs=days*24
 abc=find_lcm(x,y)
 abc=find_lcm(abc,z)
 return hrs//abc

t=int(input())
nodays=[]
a=[]
b=[]
c=[]
for i in range(t):
 nodays.append(int(input()))
 d,e,f=map(int,input().split())
 a.append(d)
 b.append(e)
 c.append(f)
for i in range(t):
 print(crowd(nodays[i],a[i],b[i],c[i]))


Solve in Python:
The Menger Sponge is a three-dimensional fractal, first described by Karl Menger in 1926.

![Mengers Sponge (Level 0-3)](http://i.imgur.com/V6Rb4Za.jpg)
###### _An illustration of the iterative construction of a Menger sponge_

A method of constructing a Menger Sponge can be visualized as follows:
1. Start from a cube (first part of image).
2. Scale down the cube so that side length is 1/3 of its original, and make 20 copies of it.
3. Place the copies so that they measure the same size as the original cube but without its central parts (next part of image)
4. Repeat the process from step 2 for the new smaller cubes from the previous step.
5. In each iteration (e.g. repeating the last three steps), the effect will be that parts of the cube will be removed, they'll never be added. Menger sponge will always consist of parts will never be removed, regardless of how many iterations you do.

___

An alternative explanation:
1. Start from a cube (first part of image).
2. Devide each cube into 27 equal sized cubes.
3. Remove the middle-cube and the six cubes on each side of the group of 27 cubes (second part of image).
4. Repeat the process from step 2 for the smaller cubes (third and fourth part of image).

## Task
In this kata you will create a function that takes non negative integers (from 0 to n) and return the amount of cubes that the Menger Sponge would have in that specific iteration.

## Example
```
calc_ms(0) == 1
calc_ms(1) == 20
calc_ms(2) == 400
calc_ms(3) == 8000
calc_ms(4) == 160000
calc_ms(5) == 3200000
calc_ms(6) == 64000000
```

Happy coding!

def calc_ms(n):
    number = 1
    x = 0
    while x < n:
        number *= 20
        x += 1
    return number


Solve in Python:
The Monty Hall problem is a probability puzzle base on the American TV show "Let's Make A Deal".

In this show, you would be presented with 3 doors: One with a prize behind it, and two without (represented with goats).

After choosing a door, the host would open one of the other two doors which didn't include a prize, and ask the participant if he or she wanted to switch to the third door. Most wouldn't. One would think you have a fifty-fifty chance of winning after having been shown a false door, however the math proves that you significantly increase your chances, from 1/3 to 2/3 by switching.

Further information about this puzzle can be found on https://en.wikipedia.org/wiki/Monty_Hall_problem.

In this program you are given an array of people who have all guessed on a door from 1-3, as well as given the door which includes the price. You need to make every person switch to the other door, and increase their chances of winning. Return the win percentage (as a rounded int) of all participants.

def monty_hall(correct_door_number, participant_guesses):
    winners=0
    for x in participant_guesses:
        if x != correct_door_number:
            winners+=1
    return(round((winners / len(participant_guesses))*100))


Solve in Python:
The Mormons are trying to find new followers and in order to do that they embark on missions.

Each time they go on a mission, every Mormons converts a fixed number of people (reach) into followers. This continues and every freshly converted Mormon as well as every original Mormon go on another mission and convert the same fixed number of people each. The process continues until they reach a predefined target number of followers (input into the model).

Converted Mormons are unique so that there's no duplication amongst them.

Create a function Mormons(startingNumber, reach, target) that calculates how many missions Mormons need to embark on, in order to reach their target. While each correct solution will pass, for more fun try to make a recursive function.

All model inputs are valid positive integers.

def mormons(starting_number, reach, target):
    missions = 0
    while starting_number < target:
        starting_number += starting_number * reach
        missions += 1
    return missions

# def mormons(start, reach, target, missions=0):
#     if start >= target:
#         return missions
#     return mormons(start + (start * reach), reach, target, missions + 1)


Solve in Python:
The Padovan sequence is the sequence of integers `P(n)` defined by the initial values

`P(0)=P(1)=P(2)=1`

and the recurrence relation

`P(n)=P(n-2)+P(n-3)`

The first few values of `P(n)` are

`1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37, 49, 65, 86, 114, 151, 200, 265, ...`

### Task

The task is to write a method that returns i-th Padovan number

```python
> padovan(0) == 1
> padovan(1) == 1
> padovan(2) == 1
> padovan(n) = padovan(n-2) + padovan(n-3)
```

from functools import lru_cache

@lru_cache()
def padovan(n):
    return 1 if n < 3 else padovan(n-2) + padovan(n-3)


Solve in Python:
The Petrozavodsk camp takes place in about one month. Jafar wants to participate in the camp, but guess what? His coach is Yalalovichik.
Yalalovichik is a legendary coach, famous in the history of competitive programming. However, he is only willing to send to the camp students who solve really hard problems on Timus. The deadline that Yalalovichik set before has passed and he refuses to send Jafar to the camp.
Jafar decided to make Yalalovichik happy in hopes of changing his decision, so he invented a new sequence of numbers and named them Yalalovichik numbers. Jafar is writing a research paper about their properties and wants to publish it in the Science Eagle yearly journal.
A Yalalovichik number is created in the following way:
- Consider an integer $N$ in decimal notation; let's call it the base of the Yalalovichik number $Y_N$. $N$ may not contain the digit $0$.
- Treat $N$ as a decimal string. Compute all left shifts of this string $N_0, N_1, \ldots, N_{|N|-1}$ ($|N|$ denotes the number of digits of $N$); specifically, $N_k$ denotes the string formed by moving the first $k$ digits of $N$ to the end in the same order.
- Concatenate the strings $N_0, N_1, \ldots, N_{|N|-1}$. The resulting string is the decimal notation of $Y_N$.
For example, if $N = 123$, the left shifts are $123, 231, 312$ and thus $Y_N = 123231312$.
You are given the base $N$. Calculate the value of $Y_N$ 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 a single decimal integer $N$.

-----Output-----
For each test case, print a single line containing one integer — the value of the Yalalovichik number $Y_N$ modulo $10^9+7$.

-----Constraints-----
- $1 \le T \le 200$
- $|N| \le 10^5$
- $N$ does not contain the digit $0$
- the sum of $|N|$ over all test cases does not exceed $10^6$

-----Example Input-----
1
123

-----Example Output-----
123231312

from operator import mul

M = 10 ** 9 + 7
N = 100001

p10 = [None] * N
k = 1
for i in range(N):
    p10[i] = k
    k = k * 10 % M

t = int(input())
for _ in range(t):
    s = list(map(int, input()))
    m = p10[len(s)]
    p = sum(map(mul, reversed(s), p10))
    r = 0
    for d in s:
        r = (r * m + p) % M
        p = (p * 10 - (m - 1) * d) % M
    print(r)


Solve in Python:
The Quark Codejam's number QC(n, m) represents the number of ways to partition a set of n things into m nonempty subsets. For example, there are seven ways to split a four-element set into two parts:

{1, 2, 3} ∪ {4}, {1, 2, 4} ∪ {3}, {1, 3, 4} ∪ {2}, {2, 3, 4} ∪ {1},

{1, 2} ∪ {3, 4}, {1, 3} ∪ {2, 4}, {1, 4} ∪ {2, 3}.

We can compute QC(n, m) using the recurrence,

QC(n, m) = mQC(n − 1, m) + QC(n − 1, m − 1), for integers 1 < m < n.

but your task is a somewhat different: given integers n and m, compute the parity of QC(n, m), i.e. QC(n, m) mod 2.

Example :

QC(4, 2) mod 2 = 1.
Write a program that reads two positive integers n and m, computes QC(n, m) mod 2, and writes the

result.

-----Input-----
The input begins with a single positive integer on a line by itself indicating the number of the cases. This line is followed by the input cases.

The input consists two integers n and m separated by a space, with 1 ≤ m ≤ n ≤ 1000000000.

-----Output-----
For each test case, print the output.

The output should be the integer S(n, m) mod 2.
Sample Input
1

4 2
Sample Output
1

for i in range(eval(input())):
 n,k=input().strip().split()
 n=int(n)
 k=int(k)
 print(int( ((n-k)&(int((k-1)/2)))==0))


Solve in Python:
The Siruseri Singing Championship is going to start, and Lavanya wants to figure out the outcome before the tournament even begins! Looking at past tournaments, she realizes that the judges care only about the pitches that the singers can sing in, and so she devises a method through which she can accurately predict the outcome of a match between any two singers.
She represents various pitches as integers and has assigned a lower limit and an upper limit for each singer, which corresponds to their vocal range. For any singer, the lower limit will always be less than the upper limit. If a singer has lower limit $L$ and upper limit $U$ ($L < U$), it means that this particular singer can sing in all the pitches between $L$ and $U$, that is they can sing in the pitches {$L, L+1, L+2, \ldots, U$}.
The lower bounds and upper bounds of all the singers are distinct. When two singers $S_i$ and $S_j$ with bounds ($L_i$, $U_i)$ and ($L_j$, $U_j$) compete against each other, $S_i$ wins if they can sing in every pitch that $S_j$ can sing in, and some more pitches. Similarly, $S_j$ wins if they can sing in every pitch that $S_i$ can sing in, and some more pitches. If neither of those two conditions are met, the match ends up as a draw.
$N$ singers are competing in the tournament. Each singer competes in $N$-1 matches, one match against each of the other singers. The winner of a match scores 2 points, and the loser gets no points. But in case of a draw, both the singers get 1 point each.
You are given the lower and upper bounds of all the $N$ singers. You need to output the total scores of each of the $N$ singers at the end of the tournament.

-----Input-----
- The first line contains a single integer, $T$, which is the number of testcases. The description of each testcase follows.
- The first line of every testcase contains a single integer, $N$, which is the number of singers.
- $N$ lines follow, the i-th of which contains two integers: $L_i$ and $U_i$, which correspond to the lower bound and upper bound of the i-th...

t = int(input())

for _ in range(t):
	n = int(input())
	lower = []
	upper = []

	for __ in range(n):
		x,y = map(int, input().split())
		lower.append([x,__])
		upper.append([y,__])

	lower.sort(key = lambda x:x[0], reverse = True)
	upper.sort(key = lambda x:x[0])

	#print(lower, upper)

	dell = [0]*n

	for i in range(n):
		dell[upper[i][1]] += i
		dell[lower[i][1]] += i

	print(*dell)


Solve in Python:
The Siruseri amusement park has a new attraction. It consists of a rectangular array of discs. Each disc is divided into four equal sectors and the four sectors are coloured with the colours Red, Blue, Green and Yellow (in some order). The ordering may be different in different discs. Here is a possible arrangment of the discs:

You start at the top left disc. Your task is to walk down to the bottom right disc. In each step, you can rotate the current disc by $90$ degrees in the clockwise direction or move to a neighbouring disc. However, you can move to a neighbouring disc only if adjacent sectors of these two discs have the same colour. For example, in the figure above, you can move from the disc at position ($1$, $1$) to either of its neighbours. However, from the disc at position ($1$, $2$) you can only move to the disc at position ($1$, $1$). If you wish to move from ($1$, $2$) to ($1$, $3$) then you would have to rotate this disc three times so that the colour (red) on the adjacent sectors are the same.
For each rotate move, a penalty point is added to the score. The aim is to reach the bottom right with as few penalty points as possible. For example, in the arrangement described in the above figure, the best possible score is $2$, corresponding to the following path: Move from ($1$, $1$) to ($2$, $1$). Move from ($2$, $1$) to ($2$, $2$). Rotate. Rotate. Move from ($2$, $2$) to ($2$, $3$). Move from ($2$, $3$) to ($1$, $3$). Move from ($1$, $3$) to ($1$, $4$). Finally, move from ($1$, $4$) to ($2$, $4$).
Your task is to determine the minimum number of penalty points required to go from the top left disc to the bottom right disc for the given arrangement of discs.

-----Input:-----
The first line contains two integers $M$ and $N$. $M$ is the number of rows and $N$ is the number of columns in the given arrangment. This is followed by $M \times N$ lines of input. Lines $2$ to $N+1$, describe the colours on the discs on the first row, Lines $N+2$ to $2 \cdot N+1$ describe the colours on discs in the second...

from bisect import insort
class disk:
    def __init__(self):
        self.U = ''
        self.D = ''
        self.L = ''
        self.R = ''

m, n = map(int,input().split())
adj = [[] for _ in range(m*n)]
grid = [[disk() for _ in range(n)] for _ in range(m)]
for i in range(m):
    for j in range(n):
        grid[i][j].U,grid[i][j].R,grid[i][j].D,grid[i][j].L = input().split()
for i in range(m):
	for j in range(n):
		if (j!=0):

			if (grid[i][j].R == grid[i][j-1].R):
			    dist = 2
			if (grid[i][j].U == grid[i][j-1].R):
			    dist = 3
			if (grid[i][j].L == grid[i][j-1].R):
			    dist = 0
			if (grid[i][j].D == grid[i][j-1].R):
			    dist = 1
			adj[i*n + j].append((dist, i*n + j - 1))

		if (j!=n-1):

			if (grid[i][j].R == grid[i][j+1].L):
			    dist = 0
			if (grid[i][j].U == grid[i][j+1].L):
			    dist = 1
			if (grid[i][j].L == grid[i][j+1].L):
			    dist = 2
			if (grid[i][j].D == grid[i][j+1].L):
			    dist = 3
			adj[i*n + j].append((dist, i*n + j + 1))

		if (i!=0):

			if (grid[i][j].R == grid[i-1][j].D):
			    dist = 3
			if (grid[i][j].U == grid[i-1][j].D):
			    dist = 0
			if (grid[i][j].L == grid[i-1][j].D):
			    dist = 1
			if (grid[i][j].D == grid[i-1][j].D):
			    dist = 2
			adj[i*n + j].append((dist, i*n + j - n))

		if (i!=m-1):

			if (grid[i][j].R == grid[i+1][j].U):
			    dist = 1
			if (grid[i][j].U == grid[i+1][j].U):
			    dist = 2
			if (grid[i][j].L == grid[i+1][j].U):
			    dist = 3
			if (grid[i][j].D == grid[i+1][j].U):
			    dist = 0
			adj[i*n + j].append((dist, i*n + j + n))
q = []
q.append((0,0))
dists = [2147483647 for _ in range(m*n)]
visited = [False for _ in range(m*n)]
dists[0] = 0
while q:
    cur = q[-1]
    q.pop()
    if visited[cur[1]] == False:
        visited[cur[1]] = True
        dists[cur[1]] = -1*cur[0]
    for i in range(len(adj[cur[1]])):
        to = adj[cur[1]][i][1]
        dis = adj[cur[1]][i][0]
        if (not visited[to] and dists[cur[1]] + dis < dists[to]):
           ...


Solve in Python:
The Spelling Bee bees are back...

# How many bees are in the beehive?

* bees can be facing UP, DOWN, LEFT, RIGHT, and now also _diagonally_ up/down/left/right
* bees can share parts of other bees

## Examples

Ex1
```
bee.bee
.e..e..
.b..eeb
```
_Answer: 5_

Ex2
```
beee..
eeb.e.
ebee.b
```
_Answer: 7_


Solve in Python:
The Stack Arithmetic Machine
---------------------------

This time we're going to be writing a stack arithmetic machine, and we're going to call it Sam. Essentially, Sam is a very small virtual machine, with a simple intruction set, four general registers, and a stack. We've already given a CPU class, which gives you read and write access to registers and the stack, through `readReg()` and `writeReg()`, and `popStack()` and `writeStack()` respectively. All instructions on Sam are 32-bit (Java int), and either interact with the stack, or one of the 4 registers; `a`, `b`, `c`, or `d`.

The CPU API
-----------

The CPU instructions available through the CPU class, with a bit more detail:

```python
read_reg(self, name): Returns the value of the named register.
write_reg(self, name, value): Stores the value into the given register.

pop_stack(self): Pops the top element of the stack, returning the value.
write_stack(self, value): Pushes an element onto the stack.
```

Note that the registers have a default value of `0` and  that the sStack is printable (if needed).

The Instruction Set
-------------------

Instructions for same are done in assembly style, and are passed one by one into the `Exec|exec|execute` function (depending on your language). Each instruction begins with the name of the operation, and is optionally followed by either one or two operands. The operands are marked in the table below by either `[reg]`, which accepts a register name, or `[reg|int]` which accepts either a register, or an immediate integer value.

### Stack Operations

```
push [reg|int]: Pushes a register [reg] or an immediate value [int] to the stack.

pop: Pops a value of the stack, discarding the value.

pop [reg]: Pops a value of the stack, into the given register [reg].

pushr: Pushes the general registers onto the stack, in order. (a, b, c, d)

pushrr: Pushes the general registers onto the stack, in reverse order. (d, c, b, a)

popr: Pops values off the stack, and loads them into the general registers, in order so that...

import operator

class Machine(object):

    def __init__(self, cpu):
        self.cpu = cpu
        self.registers = ['a', 'b', 'c', 'd']
        self.operations = {'add': operator.add, 'adda': operator.add,
                          'sub': operator.sub, 'suba': operator.sub,
                          'mul': operator.mul, 'mula': operator.mul,
                          'div': operator.truediv, 'diva': operator.truediv,
                          'and': operator.and_, 'anda': operator.and_,
                          'or': operator.or_, 'ora': operator.or_,
                          'xor': operator.xor, 'xora':operator.xor}

    def execute(self, instr):
        instr_list = instr.split()
        command = instr_list[0]
        if command == 'push':
            val = int(instr_list[1]) if instr_list[1].isdigit() else self.cpu.read_reg(instr_list[1])
            self.cpu.write_stack(val)

        elif command == 'pop':
            val = self.cpu.pop_stack()
            if len(instr_list) == 2:
                reg_name = instr_list[1]
                self.cpu.write_reg(reg_name, val)

        elif command == 'pushr':
            for reg in self.registers:
                val = self.cpu.read_reg(reg)
                self.cpu.write_stack(val)

        elif command == 'pushrr':
            for reg in self.registers[::-1]:
                val = self.cpu.read_reg(reg)
                self.cpu.write_stack(val)

        elif command == 'popr':
            for reg in self.registers[::-1]:
                val = self.cpu.pop_stack()
                self.cpu.write_reg(reg, val)

        elif command == 'poprr':
            for reg in self.registers:
                val = self.cpu.pop_stack()
                self.cpu.write_reg(reg, val)

        elif command == 'mov':
            first_el = instr_list[1][:-1]
            if first_el.isdigit():
                self.cpu.write_reg(instr_list[2], int(first_el))
            else:
                val =...


Solve in Python:
The Story:
Aliens from Kepler 27b have immigrated to Earth! They have learned English and go to our stores, eat our food, dress like us, ride Ubers, use Google, etc. However, they speak English a little differently. Can you write a program that converts our English to their Alien English?

Task:

Write a function converting their speech to ours. They tend to speak the letter `a` like `o` and `o` like a `u`.
```python
>>> convert('hello')
'hellu'
>>> convert('codewars')
'cudewors'
```

def convert(st):
    return st.translate(str.maketrans('oa', 'uo'))


Solve in Python:
The T9 typing predictor helps with suggestions for possible word combinations on an old-style numeric keypad phone. Each digit in the keypad (2-9) represents a group of 3-4 letters. To type a letter, press once the key which corresponds to the letter group that contains the required letter. Typing words is done by typing letters of the word in sequence.

The letter groups and corresponding digits are as follows:
```
 -----------------
|  1  |  2  |  3  |
|     | ABC | DEF |
|-----|-----|-----|
|  4  |  5  |  6  |
| GHI | JKL | MNO |
|-----|-----|-----|
|  7  |  8  |  9  |
| PQRS| TUV | WXYZ|
 -----------------
```

The prediction algorithm tries to match the input sequence against a predefined dictionary of words. The combinations which appear in the dictionary are considered valid words and are shown as suggestions.

Given a list of words as a reference dictionary, and a non-empty string (of digits 2-9) as input, complete the function which returns suggestions based on the string of digits, which are found in the reference dictionary.

For example:
```python
T9(['hello', 'world'], '43556') returns ['hello']
T9(['good', 'home', 'new'], '4663') returns ['good', 'home']
```

Note that the dictionary must be case-insensitive (`'hello'` and `'Hello'` are same entries). The list returned must contain the word as it appears in the dictionary (along with the case).

Example:
```python
T9(['Hello', 'world'], '43556') returns ['Hello']
```

If there is no prediction available from the given dictionary, then return the string containing first letters of the letter groups, which correspond to the input digits.

For example:
```python
T9([], '43556') returns ['gdjjm']
T9(['gold', 'word'], '4663') returns ['gmmd']
```

def T9(words,seq):
    ans=[]
    for i in words:
        if i.lower().translate(str.maketrans('abcdefghijklmnopqrstuvwxyz','22233344455566677778889999')) == seq:
            ans += [i]
    return ans if ans else [seq.translate(str.maketrans('23456789','adgjmptw'))]


Solve in Python:
The Tower of Hanoi problem involves 3 towers.  A number of rings decreasing in size are placed on one tower.  All rings must then be moved to another tower, but at no point can a larger ring be placed on a smaller ring.

Your task:  Given a number of rings, return the MINIMUM number of moves needed to move all the rings from one tower to another.

Reference: Tower of Hanoi, Courtesy of Coolmath Games

NB:  This problem may seem very complex, but in reality there is an amazingly simple formula to calculate the minimum number.  Just Learn how to solve the problem via the above link (if you are not familiar with it), and then think hard.  Your solution should be in no way extraordinarily long and complex.  The Kata ranking is for figuring out the solution, but the coding skills required are minimal.

def tower_of_hanoi(rings):
    moves = 0
    for r in range(rings):
        moves *= 2
        moves += 1
    return moves


Solve in Python:
The Tribonacci sequence Tn is defined as follows:
T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.
Given n, return the value of Tn.

Example 1:
Input: n = 4
Output: 4
Explanation:
T_3 = 0 + 1 + 1 = 2
T_4 = 1 + 1 + 2 = 4

Example 2:
Input: n = 25
Output: 1389537

Constraints:

0 <= n <= 37
The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1.

class Solution:
    def tribonacci(self, n: int) -> int:
        t = [0,1,1]
        if n < 3:
            return t[n]

        for i in range(n-2):
            t.append(sum(t))
            t = t[1:]

        return t[2]


Solve in Python:
The USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of $n$ haybale piles on the farm. The $i$-th pile contains $a_i$ haybales.

However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices $i$ and $j$ ($1 \le i, j \le n$) such that $|i-j|=1$ and $a_i>0$ and apply $a_i = a_i - 1$, $a_j = a_j + 1$. She may also decide to not do anything on some days because she is lazy.

Bessie wants to maximize the number of haybales in pile $1$ (i.e. to maximize $a_1$), and she only has $d$ days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile $1$ if she acts optimally!

-----Input-----

The input consists of multiple test cases. The first line contains an integer $t$ ($1 \le t \le 100$)  — the number of test cases. Next $2t$ lines contain a description of test cases  — two lines per test case.

The first line of each test case contains integers $n$ and $d$ ($1 \le n,d \le 100$) — the number of haybale piles and the number of days, respectively.

The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 100$)  — the number of haybales in each pile.

-----Output-----

For each test case, output one integer: the maximum number of haybales that may be in pile $1$ after $d$ days if Bessie acts optimally.

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

Output
3
101
0

-----Note-----

In the first test case of the sample, this is one possible way Bessie can end up with $3$ haybales in pile $1$:   On day one, move a haybale from pile $3$ to pile $2$  On day two, move a haybale from pile $3$ to pile $2$  On day three, move a haybale from pile $2$ to pile $1$  On day four, move a haybale from pile $2$ to pile $1$  On day five, do nothing

In the second test case of the sample, Bessie can do nothing on the first day and move a...

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

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

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

for _ in range(val()):
    tot = 0
    n,d = li()
    l = li()
    tot = l[0]
    for i in range(1,n):
        while d >= i and l[i]:
            l[i] -= 1
            tot += 1
            d-=i
    print(tot)


Solve in Python:
The Ulam sequence `U` is defined by `u0 = u`, `u1 = v`, with the general term `uN` for `N > 2` given by the least integer expressible uniquely as the sum of two distinct earlier terms. In other words, the next number is always the smallest, unique sum of any two previous terms.

Complete the function that creates an Ulam Sequence starting with the given `u0` and `u1`, and contains `n` terms.

## Example

The first 10 terms of the sequence `U(u0=1, u1=2)` are: 1, 2, 3, 4, 6, 8, 11, 13, 16, 18.

Let's see it in details:
* The first term after the initial 1, 2 is obviously 3, because 1 + 2 = 3
* The next term is 1 + 3 = 4 (we don't have to worry about 4 = 2 + 2 since it is a sum of a *single term* instead of *distinct terms*)
* 5 is not a member of the sequence since it is representable in two ways: 1 + 4 and 2 + 3
* 6 is a memeber, as 2 + 4 = 6
* etc.

Description Reference: http://mathworld.wolfram.com/UlamSequence.html

---

Performance version: https://www.codewars.com/kata/ulam-sequences-performance-edition

def ulam_sequence(u0, u1, n):
    seq = [u0, u1]
    for _ in range(n - 2):
        sums = sorted([seq[i] + seq[j] for i in range(len(seq)) for j in range(i, len(seq)) if i != j])
        seq.append(next(s for s in sums if sums.count(s) == 1 and s not in seq))
    return seq


Solve in Python:
The Vigenère cipher is a classic cipher originally developed by Italian cryptographer Giovan Battista Bellaso and published in 1553. It is named after a later French cryptographer Blaise de Vigenère, who had developed a stronger autokey cipher (a cipher that incorporates the message of the text into the key).

The cipher is easy to understand and implement, but survived three centuries of attempts to break it, earning it the nickname "le chiffre indéchiffrable" or "the indecipherable cipher."

[From Wikipedia](https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher):

> The Vigenère cipher is a method of encrypting alphabetic text by using a series of different Caesar ciphers based on the letters of a keyword. It is a simple form of polyalphabetic substitution.
>
> . . .
>
> In a Caesar cipher, each letter of the alphabet is shifted along some number of places; for example, in a Caesar cipher of shift `3`, `A` would become `D`, `B` would become `E`, `Y` would become `B` and so on. The Vigenère cipher consists of several Caesar ciphers in sequence with different shift values.

Assume the key is repeated for the length of the text, character by character. Note that some implementations repeat the key over characters only if they are part of the alphabet -- **this is not the case here.**

The shift is derived by applying a Caesar shift to a character with the corresponding index of the key in the alphabet.

Visual representation:
Write a class that, when given a key and an alphabet, can be used to encode and decode from the cipher.

## Example
Any character not in the alphabet must be left as is. For example (following from above):

class VigenereCipher(object):
    cipherMap = {}
    invCipherMap = {}
    alphabet = ''
    lenAlphabet = -1
    key = ''
    lenKey = -1

    def __init__(self, key, alphabet):
        self.key = key
        self.lenKey = len(self.key)
        self.alphabet = alphabet
        self.lenAlphabet = len(self.alphabet)
        self.cipherMap = dict(list(enumerate(self.alphabet)))    #slick way learned @ stackExchange :)
        self.invCipherMap = {val: key for key, val in list(self.cipherMap.items())}   #invert the cipher map
    #-----end constructor

    #helper function to perform the cipher. Note, if a char (in the provided text) is not
    # in the provided alphabet, we are to leave it be; otherwise, based on the alphabet
    # and the key, we are to encode the character using the Vigenere Cipher
    def __performVigenereCipher__(self, text, performEncode):
        lenText = len(text)
        encodedText = ''

        for i in range(lenText):
            curChar = text[i]
            keyChar = self.key[i%self.lenKey]

            if curChar in self.alphabet:        #Scenario: Perform Vigenere Cipher
                charVal = self.invCipherMap[curChar]
                keyVal  = self.invCipherMap[keyChar]

                if performEncode:
                    valEncoded = (charVal + keyVal)%self.lenAlphabet
                else:
                    valEncoded = (charVal - keyVal)%self.lenAlphabet

                encodedChar = self.cipherMap[valEncoded]
            else:   #Scienario: The char is not in the alphabet; leave it be
                encodedChar = curChar

            encodedText += encodedChar
        #---end for loop

        return encodedText
    #-----end function

    def encode(self, text):
        performEncode = True
        encodedText = self.__performVigenereCipher__(text, performEncode)
        return encodedText
    #-----end function encode

    def decode(self, text):
        performEncode = False
        decodedText =...


Solve in Python:
The XOR pair representation (XPR) of a positive integer $N$ is defined as a pair of integers $(A, B)$ such that:
- $1 \le A \le B \le N$
- $A \oplus B = N$
- if there is no way to choose $A$ and $B$ satisfying the above conditions, $A = B = -1$
- otherwise, the value of $A$ should be the smallest possible
These conditions uniquely define the XPR. Next, we define a function $F(N)$ = the value of $B$ in $XPR(N)$, and a function $G(L, R) = \sum\limits_{i=L}^R F(i)$.
You are given $L$ and $R$. Compute $G(L, R)$.

-----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 $L$ and $R$.

-----Output-----
For each test case, print a single line containing one integer — the value of the function $G(L, R)$.

-----Constraints-----
- $1 \le T \le 10^5$
- $1 \le L \le R \le 10^9$

-----Example Input-----
5
1 10
3 6
4 10
10 17
100 159

-----Example Output-----
28
9
28
79
7485

import math
def count(N):
 if(N<1):
  return 0
 total=N*(N+1)//2
 a=1
 d=2
 while(N>=a):
  n=math.floor((N-a)/d)+1
  total-=(n*a+1)
  a*=2
  d*=2
 return total

T=int(input())
for _ in range(T):
 L,R=list(map(int,input().split()))
 print(count(R)-count(L-1))


Solve in Python:
The ZCO scholarship contest offers scholarships to first time ZCO participants. You are participating in it for the first time. So you want to know the number of participants who'll get the scholarship.
You know that the maximum number of scholarships offered is $R$ and there are a total of $N$ participants numbered from $1$ to $N$. Out of these, you know the set of people (denoted by $X$) who you know, had participated in previous year ZCOs and hence, they shall not get the scholarship.
Further, as the world isn't free from plagiarism, so is the case with the scholarship contest. And from your secret sources, you also know the set of people (denoted by set $Y$) who were involved in plagiarism and therefore aren't eligible for scholarship either.
Find out the number of participants who shall get the scholarship.
PS: Don't ask how so many scholarships are being offered when you see the constraints on $R$. You never questioned it when in mathematics classes, some person bought $80$ watermelons twice just to compare them and save $₹1$.

-----Input:-----
- The first line will contain a single integer, $T$, the number of testcases. Then the testcases follow.
- The first line of each test case contains four integers; $N$, $R$, $|X|$ and $|Y|$ denoting the number of participants, maximum number of scholarships offered, number of old participants, and the number of participants involved in plagiarism, respectively.
- The second line of each test case contains $|X|$ space separated integers $x_1, x_2 \ldots x_{|X|}$ denoting the indices of people who participated in previous years. If $X$ is empty, this line is skipped and no empty line is in the input.
- The third line of each test case contains $|Y|$ space separated integers $y_1, y_2 \ldots y_{|Y|}$  denoting the indices of people who are involved in plagiarism. If $Y$ is empty, this line is skipped and no empty line is in input.

-----Output:-----
For each testcase, print a single integer in a new line, denoting the number of participants who shall get the...

for _ in range(int(input())):
 n,r,x,y=map(int,input().split())
 if x>0:
  a=list(map(int,input().split()))
 if y>0:
  b=list(map(int,input().split()))
 if x>0 and y>0:
  a=a+b
  c=n-len(list(set(a)))
 else:
  l=x+y
  c=n-l
 x=min(c,r)
 print(x)


Solve in Python:
The [Chinese zodiac](https://en.wikipedia.org/wiki/Chinese_zodiac) is a repeating cycle of 12 years, with each year being represented by an animal and its reputed attributes. The lunar calendar is divided into cycles of 60 years each, and each year has a combination of an animal and an element. There are 12 animals and 5 elements; the animals change each year, and the elements change every 2 years. The current cycle was initiated in the year of 1984 which was the year of the Wood Rat.

Since the current calendar is Gregorian, I will only be using years from the epoch 1924.
*For simplicity I am counting the year as a whole year and not from January/February to the end of the year.*

##Task

Given a year, return the element and animal that year represents ("Element Animal").
For example I'm born in 1998 so I'm an "Earth Tiger".

```animals``` (or ```$animals``` in Ruby) is a preloaded array containing the animals in order:

```['Rat', 'Ox', 'Tiger', 'Rabbit', 'Dragon', 'Snake', 'Horse', 'Goat', 'Monkey', 'Rooster', 'Dog', 'Pig']```

```elements``` (or ```$elements``` in Ruby) is a preloaded array containing the elements in order:

```['Wood', 'Fire', 'Earth', 'Metal', 'Water']```

Tell me your zodiac sign and element in the comments. Happy coding :)

def chinese_zodiac(year):
    s = ''
    a = ['Rat','Ox', 'Tiger', 'Rabbit', 'Dragon', 'Snake', 'Horse', 'Goat', 'Monkey', 'Rooster', 'Dog', 'Pig']
    e = ['Wood', 'Fire', 'Earth', 'Metal', 'Water']

    e1 = (year - 1984) // 2 % 5
    a1 = (year - 1984) % 12

    s = e[e1] + ' ' + a[a1]
    return s


Solve in Python:
The [Floyd's triangle](https://en.wikipedia.org/wiki/Floyd%27s_triangle) is a right-angled triangular array of natural numbers listing them in order, in lines of increasing length, so a Floyds triangle of size 6 looks like:

```
1
2  3
4  5  6
7  8  9  10
11 12 13 14 15
16 17 18 19 20 21
    ...
```

In this kata you're given a number, and expected to return the line number it falls in, in the Floyd's triangle

```python
nth_floyd(3) # => 2 (i.e the number `3` falls in line 2 of the triangle)
nth_floyd(17) # => 6

nth_floyd(22) # => 7
nth_floyd(499502) # => 1000
```

```python
nth_floyd(n)
```

## Constraints

### 1 <= n <= 10^(9)

from math import sqrt

def nth_floyd(n):
    return round(sqrt(n * 2))


Solve in Python:
The [Linear Congruential Generator (LCG)](https://en.wikipedia.org/wiki/Linear_congruential_generator) is one of the oldest pseudo random number generator functions.

The algorithm is as follows:

## Xn+1=(aXn + c) mod m
where:
* `a`/`A` is the multiplier (we'll be using `2`)
* `c`/`C` is the increment (we'll be using `3`)
* `m`/`M` is the modulus (we'll be using `10`)

X0 is the seed.

# Your task

Define a method `random`/`Random` in the class `LCG` that provides the next random number based on a seed. You never return the initial seed value.

Similar to [random](https://docs.python.org/3/library/random.html#random.random) return the result as a floating point number in the range `[0.0, 1.0)`

# Example

```python
# initialize the generator with seed = 5
LCG(5)

# first random number (seed = 5)
LCG.random() = 0.3      # (2 * 5 + 3) mod 10 = 3 --> return 0.3

# next random number (seed = 3)
LCG.random() = 0.9      # (2 * 3 + 3) mod 10 = 9 --> return 0.9

# next random number (seed = 9)
LCG.random() = 0.1

# next random number (seed = 1)
LCG.random() = 0.5
```

class LCG:
    def __init__(self, n):
        self.n = n

    def random(self):
        self.n = (self.n * 2 + 3) % 10
        return self.n / 10


Solve in Python:
The [Ones' Complement](https://en.wikipedia.org/wiki/Ones%27_complement) of a binary number is the number obtained by swapping all the 0s for 1s and all the 1s for 0s. For example:

```
onesComplement(1001) = 0110
onesComplement(1001) = 0110
```

For any given binary number,formatted as a string, return the Ones' Complement of that number.


Solve in Python:
The [Sharkovsky's Theorem](https://en.wikipedia.org/wiki/Sharkovskii%27s_theorem) involves the following ordering of the natural numbers:
```math
3≺5≺7≺9≺ ...\\
≺2·3≺2·5≺2·7≺2·9≺...\\
≺2^n·3≺2^n·5≺2^n·7≺2^n·9≺...\\
≺2^{(n+1)}·3≺2^{(n+1)}·5≺2^{(n+1)}·7≺2^{(n+1)}·9≺...\\
≺2^n≺2^{(n-1)}≺...\\
≺4≺2≺1\\
```

Your task is to complete the function which returns `true` if `$a≺b$` according to this ordering, and `false` otherwise.

You may assume both `$a$` and `$b$` are non-zero positive integers.

def sharkovsky(a,b):

    def Answer(n):
        con = True
        p = 0
        while con == True:
            if n %2!=0:
                ans =  (p,n)
                con = False
            else:
                n= n /2
                p +=1
        return ans
    ans_a = Answer(a)
    ans_b = Answer(b)

    if ans_a[1]==1 and ans_b[1]!=1:
        return False
    elif ans_a[1]!=1 and ans_b[1]==1:
        return True
    elif ans_a[1]==1 and ans_b[1]==1:
        return ans_a[0]>ans_b[0]
    else:
        if ans_a[0]>ans_b[0]:
            return False
        elif ans_a[0]<ans_b[0]:
            return True
        else:
            return ans_a[1]<ans_b[1]


Solve in Python:
The [half-life](https://en.wikipedia.org/wiki/Half-life) of a radioactive substance is the time it takes (on average) for one-half of its atoms to undergo radioactive decay.

# Task Overview
Given the initial quantity of a radioactive substance, the quantity remaining after a given period of time, and the period of time, return the half life of that substance.

# Usage Examples

```if:csharp
Documentation:
Kata.HalfLife Method (Double, Double, Int32)

Returns the half-life for a substance given the initial quantity, the remaining quantity, and the elasped time.

Syntax

public
static
double HalfLife(
double quantityInitial,
    double quantityRemaining,
int time
    )

Parameters

quantityInitial

Type: System.Double
The initial amount of the substance.

quantityRemaining

Type: System.Double
The current amount of the substance.

time

Type: System.Int32
The amount of time elapsed.

Return Value

Type: System.Double
  A floating-point number representing the half-life of the substance.

```

import math
def half_life(q0, q1, t):
   return 1/(math.log(q0/q1)/(t*math.log(2)))


Solve in Python:
The __Hamming weight__ of a string is the number of symbols that are different from the zero-symbol of the alphabet used. There are several algorithms for efficient computing of the Hamming weight for numbers. In this Kata, speaking technically, you have to find out the number of '1' bits in a binary representation of a number. Thus,

The interesting part of this task is that you have to do it *without* string operation (hey, it's not really interesting otherwise)

 ;)

def hamming_weight(x):
  count = 0
  while x:
    x &= x-1
    count += 1
  return count


Solve in Python:
The `depth` of an integer `n` is defined to be how many multiples of `n` it is necessary to compute before all `10` digits have appeared at least once in some multiple.

example:
```
let see n=42

Multiple         value         digits     comment
42*1              42            2,4
42*2              84             8         4 existed
42*3              126           1,6        2 existed
42*4              168            -         all existed
42*5              210            0         2,1 existed
42*6              252            5         2 existed
42*7              294            9         2,4 existed
42*8              336            3         6 existed
42*9              378            7         3,8 existed

```
Looking at the above table under `digits` column you can find all the digits from `0` to `9`, Hence it required `9` multiples of `42` to get all the digits. So the depth of `42` is `9`. Write a function named `computeDepth` which computes the depth of its integer argument.Only positive numbers greater than zero will be passed as an input.

def compute_depth(n):
    i = 0
    digits = set()
    while len(digits) < 10:
        i += 1
        digits.update(str(n * i))
    return i


Solve in Python:
The `mystery` function is defined over the non-negative integers. The more common name of this function is concealed in order to not tempt you to search the Web for help in solving this kata, which most definitely would be a very dishonorable thing to do.

Assume `n` has `m` bits. Then `mystery(n)` is the number whose binary representation is the entry in the table `T(m)` at index position `n`, where `T(m)` is defined recursively as follows:

```
T(1) = [0, 1]
```

`T(m + 1)` is obtained by taking two copies of `T(m)`, reversing the second copy, prepending each entry of the first copy with `0` and each entry of the reversed copy with `1`, and then concatenating the two. For example:

```
T(2) = [ 00, 01, 11, 10 ]
```

and

```
T(3) = [ 000, 001, 011, 010, 110, 111, 101, 100 ]
```

`mystery(6)` is the entry in `T(3)` at index position 6 (with indexing starting at `0`), i.e., `101` interpreted as a binary number. So, `mystery(6)` returns `5`.

Your mission is to implement the function `mystery`, where the argument may have up to 63 bits. Note that `T(63)` is far too large to compute and store, so you'll have to find an alternative way of implementing `mystery`. You are also asked to implement `mystery_inv` ( or `mysteryInv` ), the inverse of `mystery`. Finally, you are asked to implement a function `name_of_mystery` ( or `nameOfMystery` ), which shall return the name that `mystery` is more commonly known as. After passing all tests you are free to learn more about this function on Wikipedia or another place.

Hint: If you don't know the name of `mystery`, remember there is information in passing as well as failing a test.

def mystery(n):
    return n^n>>1

def mystery_inv(n):
    i = n>>1
    while i > 0:
        n ^= i
        i >>= 1
    return n

def name_of_mystery():
    return "Gray code"


Solve in Python:
The accounts of the "Fat to Fit Club (FFC)" association are supervised by John as a volunteered accountant.
The association is funded through financial donations from generous benefactors. John has a list of
the first `n` donations: `[14, 30, 5, 7, 9, 11, 15]`
He wants to know how much the next benefactor should give to the association so that the
average of the first `n + 1` donations should reach an average of `30`.
After doing the math he found `149`. He thinks that he made a mistake.
Could you help him?

if `dons = [14, 30, 5, 7, 9, 11, 15]` then `new_avg(dons, 30) --> 149`

The function `new_avg(arr, navg)` should return the expected donation
(rounded up to the next integer) that will permit to reach the average `navg`.

Should the last donation be a non positive number `(<= 0)` John wants us to throw (or raise) an error or

- return Nothing in Haskell
- return None in F#, Ocaml, Scala
- return `-1` in C, Fortran,  Nim, PowerShell, Go, Prolog
- echo `ERROR` in Shell
- raise-argument-error in Racket

so that he clearly sees that his expectations are not great enough.

Notes:

- all donations and `navg` are numbers (integers or floats), `arr` can be empty.
- See examples below and "Test Samples" to see which return is to be done.

```
new_avg([14, 30, 5, 7, 9, 11, 15], 92) should return 645
new_avg([14, 30, 5, 7, 9, 11, 15], 2)
should raise an error (ValueError or invalid_argument or argument-error or DomainError)
or return `-1` or ERROR or Nothing or None depending on the language.
```

from math import ceil

def new_avg(arr, newavg):
    # calculate the required amount
    required = ceil(newavg * (len(arr) + 1) - sum(arr))
    # throw an error if non-positive
    assert required > 0
    # otherwise return result
    return required


Solve in Python:
The activity of a panipuri seller is "making a panipuri and putting it on the palte of his customer".
$N$ customers are eating panipuri, Given an array $A$ of length $N$, $i^{th}$ customer takes $A_i$ seconds to eat a panipuri.
The Speed of Panipuri seller refers to the number of customers served per second. Determine the minimum speed of panipuri seller so that no customer has to wait for panipuri after getting his/her first panipuri.
Assume that the plate can hold infinite panipuris, and customer starts eating next panipuri just after finishing the current one.    You would be provided with the time taken by each customer to eat a panipuri.
Panpuri seller serves panipuri in round robin manner (first to last and then again first).

-----Input:-----
- First line will contain $T$, number of testcases. Then the test cases follow.
- For each test case, the first line contains $N$ number of customers.
- Then the second line will contain $N$ space separated integers, $A_1$ to $A_N$, eating time taken by each customer(in seconds).

-----Output:-----
- For each test case, print a single line containing the minimum integral speed of panipuri seller so that no customer has to wait.

-----Constraints-----
- $0 < T \leq 100$
- $0 < N \leq 10^6$
- $0 < A_i \leq 10^9$
- Sum of $N$ over all test cases does not exceed $10^6$

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

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

3

-----EXPLANATION:-----
$Test case$ $1$:

Let's assume speed of panipuri seller be 1.

So starting from $0^{th}$ second, in $0$ to $1$ second seller make a panipuri and put it into the plate of first customer, and first customer completely eat it in $1$ to $3$ second as he takes $2$ second to eat a panipuri. But in $3$ to $4$ second panipuri seller is serving to $4^{th}$ customer, and hence first customer have to wait, so 1 cannot be our answer.

Next possible speed can be $2$ .

Starting from $0^{th}$ second, at half second seller make a panipuri and put it into the plate of first customer,  first customer...

import math
T=int(input())
for i in range(T):
	n=int(input())
	l=[int(x) for x in input().split()]
	s=math.ceil(n/min(l))
	print(s)


Solve in Python:
The aim is to calculate `exponential(x)` (written `exp(x)` in most math libraries) as an irreducible fraction, the numerator of this fraction having a given number of digits.

We call this function `expand`, it takes two parameters, `x` of which we want to evaluate the exponential, `digits` which is the required number of digits for the numerator.

The function `expand` will return an array of the form `[numerator, denominator]`; we stop the loop in the Taylor expansion (see references below) when the numerator has a number of digits `>=` the required number of digits

# Examples:
```
expand(1, 2) --> 65/24 (we will write this [65, 24] or (65, 24) in Haskell;
65/24 ~ 2.708...)

expand(2, 5) --> [20947, 2835]

expand(3, 10) --> [7205850259, 358758400]

expand(1.5, 10) --> [36185315027,8074035200]
```
**Note**
```expand(1,5) = [109601, 40320]``` is the same as ```expand(1, 6)```

#Method:
As said above the way here is to use `Taylor expansion` of the exponential function though it is not always the best approximation by a rational.

#References:
https://en.wikipedia.org/wiki/Exponential_function#Formal_definition

http://www.efunda.com/math/taylor_series/exponential.cfm

from fractions import Fraction

def expand(x, digit):
    step = 0
    fact = 1
    expo = Fraction(1)
    n = 10 ** len(str(x).split('.')[-1])
    x = Fraction(int(x * n), n)
    while expo.numerator < 10 ** (digit - 1):
        step += 1
        fact *= step
        expo += x ** step / fact
    return [expo.numerator, expo.denominator]


Solve in Python:
The aim of the kata is to decompose `n!` (factorial n) into its prime factors.

Examples:
```
n = 12; decomp(12) -> "2^10 * 3^5 * 5^2 * 7 * 11"
since 12! is divisible by 2 ten times, by 3 five times, by 5 two times and by 7 and 11 only once.

n = 22; decomp(22) -> "2^19 * 3^9 * 5^4 * 7^3 * 11^2 * 13 * 17 * 19"

n = 25; decomp(25) -> 2^22 * 3^10 * 5^6 * 7^3 * 11^2 * 13 * 17 * 19 * 23
```

Prime numbers should be in increasing order. When the exponent of a prime is 1 don't put the exponent.

Notes

- the function is `decomp(n)` and should return the decomposition of `n!` into its prime factors in increasing order of the primes, as a string.
- factorial can be a very big number (`4000! has 12674 digits`, n will go from 300 to 4000).
- 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`.

def decomp(n):
    out = []
    for d in range(2, n+1):
        if d==2 or (d&1 and d>2 and all(d%i for i in range(3, 1+int(d**0.5), 2))):
            a, x = 0, n
            while x >= d:
                x //= d
                a += x
            out.append((d,a))
    return ' * '.join([f'{i}^{j}' if j>1 else str(i) for i,j in out])


Solve in Python:
The aim of the kata is to try to show how difficult it can be to calculate decimals of an irrational number with a certain precision. We have chosen to get a few decimals of the number "pi" using
the following infinite series (Leibniz 1646–1716):

PI / 4 = 1 - 1/3 + 1/5 - 1/7 + ... which gives an approximation of PI / 4.

http://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80

To have a measure of the difficulty we will count how many iterations are needed to calculate PI with a given precision.

There are several ways to determine the precision of the calculus but to keep things easy we will calculate to within epsilon of your language Math::PI constant. In other words we will stop  the iterative process when the absolute value of the difference between our calculation and the Math::PI constant of the given language is less than epsilon.

Your function returns an array or an arrayList or a string or a tuple depending on the language (See sample tests) where your approximation of PI has 10 decimals

In Haskell you can use the function "trunc10Dble" (see "Your solution"); in Clojure you can use the function "round" (see "Your solution");in OCaml or Rust the function "rnd10" (see "Your solution") in order to avoid discussions about the result.

Example :
```
your function calculates 1000 iterations and 3.140592653839794 but returns:
iter_pi(0.001) --> [1000, 3.1405926538]
```

Unfortunately, this series converges too slowly to be useful,
as it takes over 300 terms to obtain a 2 decimal place precision.
To obtain 100 decimal places of PI, it was calculated that
one would need to use at least 10^50 terms of this expansion!

About PI : http://www.geom.uiuc.edu/~huberty/math5337/groupe/expresspi.html

from math import pi

def iter_pi(epsilon):
    my_pi = 0
    n = sign = 1

    while epsilon < abs(pi - my_pi):
        my_pi += 4.0 / n * sign
        n += 2
        sign *= -1

    return [n//2, round(my_pi, 10)]


Solve in Python:
The aim of this Kata is to write a function which will reverse the case of all consecutive duplicate letters in a string.  That is, any letters that occur one after the other and are identical.

If the duplicate letters are lowercase then they must be set to uppercase, and if they are uppercase then they need to be changed to lowercase.

**Examples:**
```python
reverse_case("puzzles")    Expected Result: "puZZles"
reverse_case("massive")    Expected Result: "maSSive"
reverse_case("LITTLE")     Expected Result: "LIttLE"
reverse_case("shhh")       Expected Result: "sHHH"
```

Arguments passed will include only alphabetical letters A–Z or a–z.


Solve in Python:
The aim of this kata is to determine the number of sub-function calls made by an unknown function.

You have to write a function named `count_calls` which:

* takes as parameter a function and its arguments (args, kwargs)
* calls the function
* returns a tuple containing:

 * the number of function calls made inside it and inside all the sub-called functions recursively
 * the function return value.

NB: The call to the function itself is not counted.

HINT: The sys module may come in handy.

import sys
def count_calls(f, *args, **kwargs):
    total = 0
    def count(frame, event, arg):
        nonlocal total
        if event == 'call':
            total += 1
    sys.settrace(count)
    ret = f(*args, **kwargs)
    return total -1, ret


Solve in Python:
The aim of this kata is to split a given string into different strings of equal size (note size of strings is passed to the method)

Example:

    Split the below string into other strings of size #3

    'supercalifragilisticexpialidocious'

    Will return a new string
    'sup erc ali fra gil ist ice xpi ali doc iou s'

Assumptions:

    String length is always greater than 0
    String has no spaces
    Size is always positive

def split_in_parts(s, p):
    l=[]
    i=0
    while i < len(s):
          k=s[i:i+p]
          l.append(k)
          i+=p
    res=" ".join(l)
    return res


Solve in Python:
The alphabetized kata
---------------------

Re-order the characters of a string, so that they are concatenated into a new string in "case-insensitively-alphabetical-order-of-appearance" order. Whitespace and punctuation shall simply be removed!

The input is restricted to contain no numerals and only words containing the english alphabet letters.

Example:

```python
alphabetized("The Holy Bible") # "BbeehHilloTy"
```

_Inspired by [Tauba Auerbach](http://www.taubaauerbach.com/view.php?id=73)_

def alphabetized(stg):
    return "".join(sorted((c for c in stg if c.isalpha()), key=str.lower))