Solve in Python:
	A valid parentheses sequence is a non-empty string where each character is either '(' or ')', which satisfies the following constraint:

You can find a way to repeat erasing adjacent pairs of parentheses '()' until it becomes empty.

	For example, '(())' and '()((()()))' are valid parentheses sequences, but ')()(' and '(()' are not.

	Mike has a valid parentheses sequence. He really likes everything about his sequence, except the fact that it is quite long. So Mike has recently decided that he will replace his parentheses sequence with a new one in the near future. But not every valid parentheses sequence will satisfy him. To help you understand his requirements we'll introduce the pseudocode of function F(S):

	FUNCTION F( S - a valid parentheses sequence )
	BEGIN
		balance = 0
		max_balance = 0
		FOR index FROM 1 TO LENGTH(S)
		BEGIN
			if S[index] == '(' then balance = balance + 1
			if S[index] == ')' then balance = balance - 1
			max_balance = max( max_balance, balance )
		END
		RETURN max_balance
	END

	In other words, F(S) is equal to the maximal balance over all prefixes of S.

	Let's denote A as Mike's current parentheses sequence, and B as a candidate for a new one. Mike is willing to replace A with B if F(A) is equal to F(B). He would also like to choose B with the minimal possible length amongst ones satisfying the previous condition. If there are several such strings with the minimal possible length, then Mike will choose the least one lexicographically, considering '(' to be less than ')'.

	Help Mike!

-----Input-----

	The first line of the input contains one integer T denoting the number of testcases to process.

	The only line of each testcase contains one string A denoting Mike's parentheses sequence. It is guaranteed that A only consists of the characters '(' and ')'. It is also guaranteed that A is a valid parentheses sequence.

-----Output-----

	The output should contain exactly T lines, one line per each testcase in the order of their appearance. The only line of each testcase should...

# cook your dish here
for _ in range(int(input())):
    b = 0
    mx = 0
    for i in input():
        if i == "(":
            b += 1
        else:
            b -= 1
        mx = max(b,mx)
    print("("*mx + ")"*mx)


Solve in Python:
	Chef has a cubic die with 6 faces kept on an infinite plane. Each face has a distinct integer in the range [1,6] written on it, but the exact arrangement of the numbers on the faces of the die is unknown to Chef. Curiosity gets the better of Chef and he wants to find out o(1), o(2), ..., o(6), where o(i) is the number written opposite to the number i.

	Chef performs the following N-1 steps to learn the exact arrangement of the numbers on the die. In the i-th step, Chef pushes the die in some direction (there are 4 possible directions), and the die rolls 90o in this direction. The picture below demonstrates a die and the result that it produced after rolling in each of the 4 directions respectively. For this die, we have o(1)=4, o(2)=5, o(3)=6, o(4)=1, o(5)=2, o(6)=3.

	Chef records N numbers A1, A2, ..., AN, where Ai is the number written on the top of the die before the i-th step. However, the information on the direction in which he pushes the die each time are lost. Can you help him determine the arrangement of 1-6? You need to output o(1), o(2), ..., o(6). If there are multiple solutions, output any one of them.

-----
	Input-----
- The first line of input contains a single integer T, the number of test cases.
- Each test case consists of two lines.
- The first line contains an integer N, and the second line contains N space-separated integers A1, A2, ..., AN.

-----
	Output-----

	For each test case, output one line. If a possible solution exists, then output 6 space-separated integers o(1), o(2), ..., o(6); otherwise, output -1.

-----
	Constraints-----

- 1 ≤ T, N ≤ 500
- 1 ≤ Ai ≤ 6

	Subtask #1 (17 points):

- N ≤ 2

	Subtask #2 (83 points):

- original constraints

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

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

-----
	Explanation-----
Example case 1: See below.

Example case 2: You can prove that there's no solution.
Example case 3: The solution is not unique. 3 5 1 6 2 4 is another valid solution.

from itertools import permutations

def solve(n,a):
 ans=[]

 for des in desire:
  check=1
  for i in range(n-1):

   if (a[i]==a[i+1]):
    return [-1]
   if a[i+1]==des[a[i]-1]:
    check=0
    break
  if check:
   ans=des
   break
 if ans:
  return ans
 return [-1]

per=permutations([1,2,3,4,5,6])
desire=[]
for p in per:
 check=1
 for i in range(1,7):
  if p[i-1]==i:
   check=0
   break
 if check:
  doublecheck=1
  for i in range(6):
   if p[p[i]-1]!=i+1:
    doublecheck=0
    break
  if doublecheck:
   desire.append(p)
#print(desire)
for _ in range(int(input())):

 n=int(input())
 a=list(map(int,input().split( )))
 print(*solve(n,a))


Solve in Python:
	DevuLand is a very strange place. There are n villages in it. Some of the villages are occupied by dinosaurs while the remaining ones by villagers.
	You are given the information of DevuLand
	by an array D of size n. If D[i] is non-negative, it means that there are D[i] villagers in that village.
	Otherwise, it means that are -D[i]
	dinosaurs in that village.

	It is also guaranteed that total number of villagers in DevuLand is equal to total number of dinosaurs.

Once dinosaurs got very hungry and started eating villagers. Frightened villagers gathered immediately and met their Sarpanch Deviji. Deviji, being a very daring and negotiable person, met to the head
of dinosaurs. Soon both parties called a truce. It was decided that the villagers will provide laddus to
the dinosaurs. So everyday, each villager will take exactly one laddu to one of the dinosaurs in such a way that no dinosaur remains hungry (note that this is possible because number of villagers is the same as the number of dinosaurs).

Actually, carrying laddus is a quite a tough job. Villagers have to use a bullock cart for that. It takes one unit of grass a bullock to
carry a cart with 1 laddu for 1 kilometre. Laddus used to be very heavy in DevuLand, so a bullock cart can not carry more than one laddu.

It is also given distance between village indexed i and j is |j - i| (the absolute value) kilometres.

Now villagers sat down and found a strategy to feed laddus to dinosaurs so that they need to buy the least amount of grass from the nearby market.
They are not very good in
calculations, please find out what is the minimum number of units of grass they need to buy.

-----Input-----

First line of the input contains an integer T denoting number of test cases.

For each test case, there are two lines.

First line contains a single integer denoting n: number of villages.

Second line contains n space separated integers denoting the array D.

-----Output-----

For each test case, print a single line containing the integer corresponding to...

# cook your dish here
for _ in range(int(input())):
 n = int(input())
 a = list(map(int, input().split()))
 curr = 0
 ans = 0
 for x in a:
  curr += x
  ans += abs(curr)
 print(ans)


Solve in Python:
	The following graph G is called a Petersen graph and its vertices have been numbered from 0 to 9. Some letters have also been assigned to vertices of G, as can be seen from the following picture:

	Let's consider a walk W in graph G, which consists of L vertices W1, W2, ..., WL, such that Wi is connected with Wi + 1 for 1 ≤ i < L. A string S of L letters 'A'-'E' is realized by walk W if the sequence of letters written along W is equal to S. Vertices can be visited multiple times while walking along W.

For example, S = 'ABBECCD' is realized by W = (0, 1, 6, 9, 7, 2, 3).
Your task is to determine whether there is a walk W which realizes a given string S in graph G, and if so, find the lexicographically least such walk.

-----Input-----

	The first line of the input contains one integer T denoting the number of testcases to process.

	The only line of each testcase contains one string S. It is guaranteed that S only consists of symbols 'A'-'E'.

-----Output-----

	The output should contain exactly T lines, one line per each testcase in the order of their appearance. For each testcase, if there is no walk W which realizes S, then output -1. Otherwise, you should output the least lexicographical walk W which realizes S. Since all of the vertices are numbered from 0 to 9, then it can be encoded as a string consisting of symbols '0'-'9' (see the "Examples" section for more details).

-----Constraints-----
1 ≤ T ≤ 8;
1 ≤ |S| ≤ 100000(105).

-----Examples-----
Input:
2
AAB
AABE

Output:
501
-1

let_to_num = {'A':[0,5], 'B':[1,6], 'C':[2,7], 'D':[3,8], 'E':[4,9]}

num_to_let = {0:'A', 1:'B', 2:'C', 3:'D', 4:'E',
              5:'A', 6:'B', 7:'C', 8:'D', 9:'E'}

connections = {0:(1,4,5), 1:(0,2,6), 2:(1,3,7), 3:(2,4,8), 4:(0,3,9), 5:(0,7,8),
               6:(1,8,9), 7:(2,5,9), 8:(3,5,6), 9:(4,6,7)}

T = int(input())

for i in range(T):
    s = input()
    out_1, out_2= [],[]
    flag1, flag2 = True, True
    for c in range(len(s)):
        #print out_1, out_2, flag1, flag2
        if c == 0:
            out_1.append(let_to_num[s[c]][0])
            out_2.append(let_to_num[s[c]][1])
            #print out_1, out_2, '\n'
        else:
            if flag1:
                conn_1 = set(connections[out_1[-1]])
                to_conn_1 = set(let_to_num[s[c]])

                if len(conn_1.intersection(to_conn_1))==0:
                    flag1 = False
                else:
                    out_1.extend(list(conn_1.intersection(to_conn_1)))

                #print 'out1',conn_1, to_conn_1, flag1, conn_1.intersection(to_conn_1)
            if flag2:
                conn_2 = set(connections[out_2[-1]])
                to_conn_2 = set(let_to_num[s[c]])

                if len(conn_2.intersection(to_conn_2))==0:
                    flag2 = False
                else:
                    out_2.extend(list(conn_2.intersection(to_conn_2)))
                #print 'out2', conn_2, to_conn_2, flag2, conn_2.intersection(to_conn_2)
            #print out_1, out_2, flag1, flag2, '\n'
            if (not flag1) and (not flag2):
                break
    if (not flag1) and (not flag2):
        print(-1)
        continue
    elif flag1 and (not flag2):
        print(''.join(str(k) for k in out_1))
        continue
    elif flag2 and (not flag1):
        print(''.join(str(k) for k in out_2))
        continue
    else:
        print(min(''.join(str(k) for k in out_1), ''.join(str(k) for k in out_2)))
        continue


Solve in Python:
	Three numbers A, B and C are the inputs. Write a program to find second largest among them.

-----Input-----

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

-----Output-----
For each test case, display the second largest among A, B and C, in a new line.

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

-----Example-----
Input
3
120 11 400
10213 312 10
10 3 450

Output

120
312
10

t=int(input())
for i in range(t):
    (x,y,z)=list(map(int, input().split()))
    if (x>y and x<z) or (x>z and x<y):
        print(x)
    elif (y>x and y<z) or (y>z and y<x):
        print(y)
    else:
        print(z)# cook your dish here


Solve in Python:
![](http://www.grindtv.com/wp-content/uploads/2015/08/drone.jpg)

The other day I saw an amazing video where a guy hacked some wifi controlled lightbulbs by flying a drone past them. Brilliant.

In this kata we will recreate that stunt... sort of.

You will be given two strings: `lamps` and `drone`. `lamps` represents a row of lamps, currently off, each represented by `x`. When these lamps are on, they should be represented by `o`.

The `drone` string represents the position of the drone `T` (any better suggestion for character??) and its flight path up until this point `=`. The drone always flies left to right, and always begins at the start of the row of lamps. Anywhere the drone has flown, including its current position, will result in the lamp at that position switching on.

Return the resulting `lamps` string. See example tests for more clarity.

def fly_by(lamps, drone):
    os = min(len(drone), len(lamps))
    xs = len(lamps) - len(drone)
    return os * "o" + xs * "x"


Solve in Python:
![alt text](https://2.bp.blogspot.com/-DNNiOXduuvQ/Vh-FR-qbKXI/AAAAAAAAEOA/HT0IzJ36zW4/s1600/voz.jpg)

Create a class called `Warrior` which calculates and keeps track of their level and skills, and ranks them as the warrior they've proven to be.

Business Rules:

- A warrior starts at level 1 and can progress all the way to 100.
- A warrior starts at rank `"Pushover"` and can progress all the way to `"Greatest"`.
- The only acceptable range of rank values is `"Pushover", "Novice", "Fighter", "Warrior", "Veteran", "Sage", "Elite", "Conqueror", "Champion", "Master", "Greatest"`.
- Warriors will compete in battles. Battles will always accept an enemy level to match against your own.
- With each battle successfully finished, your warrior's experience is updated based on the enemy's level.
- The experience earned from the battle is relative to what the warrior's current level is compared to the level of the enemy.
- A warrior's experience starts from 100. Each time the warrior's experience increases by another 100, the warrior's level rises to the next level.
- A warrior's experience is cumulative, and does not reset with each rise of level. The only exception is when the warrior reaches level 100, with which the experience stops at 10000
- At every 10 levels, your warrior will reach a new rank tier. (ex. levels 1-9 falls within `"Pushover"` tier, levels 80-89 fall within `"Champion"` tier, etc.)
- A warrior cannot progress beyond level 100 and rank `"Greatest"`.

Battle Progress Rules & Calculations:

- If an enemy level does not fall in the range of 1 to 100, the battle cannot happen and should return `"Invalid level"`.
- Completing a battle against an enemy with the same level as your warrior will be worth 10 experience points.
- Completing a battle against an enemy who is one level lower than your warrior will be worth 5 experience points.
- Completing a battle against an enemy who is two levels lower or more than your warrior will give 0 experience points.
- Completing a battle against an enemy who is one...

class Warrior:
    def __init__(self):
        self.xp = 100
        self.ranks = ["Pushover", "Novice", "Fighter", "Warrior", "Veteran", "Sage", "Elite", "Conqueror", "Champion", "Master", "Greatest"]
        self.achievements = []

    @property
    def experience(self):
        return min(self.xp, 10000)
    @property
    def level(self):
        return self.experience//100
    @property
    def rank(self):
        return self.ranks[self.level//10]

    def battle(self, level):
        diff = level - self.level
        if not (0<level<=100): return "Invalid level"
        elif diff>4 and self.ranks.index(self.ranks[level//10]) > self.ranks.index(self.rank): return "You've been defeated"
        elif diff>0:
            self.xp += 20*diff*diff
            return "An intense fight"
        elif not diff:
            self.xp += 10
            return 'A good fight'
        elif diff==-1:
            self.xp += 5
            return 'A good fight'
        return "Easy fight"

    def training(self, arr):
        if self.level >= arr[2]:
            self.xp += arr[1]
            self.achievements.append(arr[0])
            return arr[0]
        return "Not strong enough"


Solve in Python:
"Don't Drink and Drive, but when you do, Better Call Saul."
Once Jesse and Walter were fighting over extra cash, and Saul decided to settle it with a game of stone piles whose winner gets the extra money. The game is described as follows :
There are N$N$ piles of stones with A$A$1$1$,$,$ A$A$2$2$,$,$ ...$...$ A$A$N$N$ stones in each pile.
Jesse and Walter move alternately, and in one move, they remove one pile entirely.
After a total of X$X$ moves, if the Sum of all the remaining piles is odd, Walter wins the game and gets the extra cash, else Jesse is the winner.
Walter moves first.
Determine the winner of the game if both of them play optimally.

-----Input:-----
- The first line will contain T$T$, number of testcases. T$T$ testcases follow :
- The first line of each testcase contains two space-separated integers N,X$N, X$.
- The second line of each testcase contains N$N$ space-separated integers A$A$1$1$,$,$ A$A$2$2$,$,$ ...,$...,$A$A$N$N$.

-----Output:-----
For each test case, print a single line containing the string "Jesse" (without quotes), if Jesse wins the game or "Walter" (without quotes) if Walter wins.

-----Constraints-----
- 1≤T≤104$1 \leq T \leq 10^4$
- 2≤N≤105$2 \leq N \leq 10^5$
- 1≤X≤N−1$1 \leq X \leq N-1$
- 1≤A$1 \leq A$i$i$ ≤100$ \leq 100$
- The sum of N$N$ over all test cases does not exceed 106$10^6$

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

-----Sample Output:-----
Jesse
Walter

-----EXPLANATION:-----
-
For Test Case 1 : Playing optimally, Walter removes 4. Jesse removes 3 and then Walter removes 4. Jesse wins as 4+4=8$4 + 4 = 8$ is even.
-
For Test Case 2 : Playing optimally, Walter removes 4, Jesse removes 3, Walter removes 2 and Jesse removes 1. Walter wins as  3+3+1=7$3 + 3 + 1 = 7$ is odd.

# cook your dish here
def winner_is(x: int, n: int, stones: [int]) -> str:
    odd_piles = sum([j%2 for j in stones])
    if x % 2 == 1:
     if x // 2 >= odd_piles or (n % 2 == 1 and x // 2 >= n - odd_piles):
      return "Jesse"
     return "Walter"
    elif x // 2 >= n - odd_piles and n % 2 == 1:
     return "Walter"
    return "Jesse"

def driver():
    pile = []
    for i in range(int(input())):
     n, x = map(int,input().split())
     stones = list(map(int,input().split()))
     pile.append(winner_is(x, n, stones))
    print(*pile, sep="\n")

driver()


Solve in Python:
"Everything in the universe is balanced. Every disappointment you face in life will be balanced by something good for you! Keep going, never give up."
Let's call a string balanced if all characters that occur in this string occur in it the same number of times.
You are given a string $S$; this string may only contain uppercase English letters. You may perform the following operation any number of times (including zero): choose one letter in $S$ and replace it by another uppercase English letter. Note that even if the replaced letter occurs in $S$ multiple times, only the chosen occurrence of this letter is replaced.
Find the minimum number of operations required to convert the given string to a balanced string.

-----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 string $S$.

-----Output-----
For each test case, print a single line containing one integer ― the minimum number of operations.

-----Constraints-----
- $1 \le T \le 10,000$
- $1 \le |S| \le 1,000,000$
- the sum of $|S|$ over all test cases does not exceed $5,000,000$
- $S$ contains only uppercase English letters

-----Subtasks-----
Subtask #1 (20 points):
- $T \le 10$
- $|S| \le 18$
Subtask #2 (80 points): original constraints

-----Example Input-----
2
ABCB
BBC

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

-----Explanation-----
Example case 1: We can change 'C' to 'A'. The resulting string is "ABAB", which is a balanced string, since the number of occurrences of 'A' is equal to the number of occurrences of 'B'.
Example case 2: We can change 'C' to 'B' to make the string "BBB", which is a balanced string.

t = int(input())
while t:
 s = input()
 n = len(s)
 res = n
 freq = [0]*26
 for i in s:
  freq[ord(i) - 65] += 1
 freq.sort(reverse = True)
 for i in range(1,27):
  if(n%i == 0):
   x = 0
   y = n//i
   for j in range(i):
    x += min(y, freq[j])
   res = min(n-x,res)
 print(res)
 t -= 1


Solve in Python:
"How did you get the deal,how did he agree?"
"Its's simple Tom I just made him an offer he couldn't refuse"
Ayush is the owner of a big construction company and a close aide of Don Vito The Godfather, recently with the help of the Godfather his company has been assigned a big contract according to the contract he has to make n number of V shaped infinitely long roads(two V shaped roads may or  not intersect) on an infinitely large field.
Now the company assigning the contract needs to know the maximum number of regions they can get after making n such roads.
Help Ayush by answering the above question.

-----Input:-----
- The first line consists of the number of test cases $T$.
- Next T lines consists of the number of V shaped roads $n$.

-----Output:-----
For each test case print a single line consisting of the maximum regions obtained.

-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq n \leq 10^9$

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

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

-----EXPLANATION:-----
Test case 1:       For one V shaped road there will be 2 regions

Test case 2:       For n=2 the following figure depicts the case of maximum regions:

# cook your dish here
t=int(input())
while(t>0):
    n=int(input())
    print(2*(n*n) - n +1)
    t-=1


Solve in Python:
"Humankind cannot gain anything without first giving something in return. To obtain, something of equal value must be lost. That is alchemy's first law of Equivalent Exchange. In those days, we really believed that to be the world's one, and only truth."
-- Alphonse Elric
Now, here we have an equivalent exchange law for triangles which states that two right-angled isosceles triangles of the same color can be made into a square of the same color using Alchemy.
You are given N$N$ right-angled isosceles colored triangles numbered from 1$1$ to N$N$. For each triangle, the two equal sides have a length of 1$1$ unit. The Color of i$i$-th triangle is given by Ci$C_i$.
To create a tower, we choose some consecutive (2×k)+1$2 \times k)+1$ triangles for any k≥0$k \geq 0$. We then pick some 2×k$2 \times k$ of them (these need not be consecutive), and form k$k$ pairs of triangles such that both triangles in pair have the same color. Also, each of the 2×k$2 \times k$ should be in exactly one pair. Then the two triangles in each pair are joined using Alchemy (following the law of equivalent exchange for triangles) to form squares and these k$k$ squares are placed one upon other. The one remaining triangle is placed as a roof to the tower. This results in a tower of the height of k$k$.
Find the maximum height of the tower that can be formed.
In other words, you should select the largest consecutive segment of triangles, such that you can form a tower using every single one of those triangles. In particular, you leave out one triangle, which will form the roof, and the other triangles should all be paired up such that both triangles in a pair have the same colour.

-----Input:-----
- The first line contains T$T$, the number of test cases. Then the test cases follow.
- For every test case, the first line contains N$N$ denoting the number of triangles.
- For every test case, the second line contains N$N$ space-separated integers Ci$C_{i}$ denoting the color of the triangles. ( 1≤i≤N$1 \leq i \leq N$).

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

for t in range(int(input())):
    n = int(input())
    c = list(map(int,input().split()))
    dictionary = {0:0}
    parity = 0
    k = 0
    for i in range(n):
     parity ^= (1<<c[i]-1)
     if parity not in dictionary:
      dictionary[parity] = i+1;
     for j in range(30):
      x = parity ^ (1<<j);
      if x in dictionary:
       k=max(k,i-dictionary[x])

    print(k//2)


Solve in Python:
"I don't have any fancy quotes." - vijju123
Chef was reading some quotes by great people. Now, he is interested in classifying all the fancy quotes he knows. He thinks that all fancy quotes which contain the word "not" are Real Fancy; quotes that do not contain it are regularly fancy.
You are given some quotes. For each quote, you need to tell Chef if it is Real Fancy or just regularly fancy.

-----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 string $S$ denoting a quote.

-----Output-----
For each test case, print a single line containing the string "Real Fancy" or "regularly fancy" (without quotes).

-----Constraints-----
- $1 \le T \le 50$
- $1 \le |S| \le 100$
- each character of $S$ is either a lowercase English letter or a space

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

-----Example Input-----
2
i do not have any fancy quotes
when nothing goes right go left

-----Example Output-----
Real Fancy
regularly fancy

-----Explanation-----
Example case 1: "i do not have any fancy quotes"
Example case 2: The word "not" does not appear in the given quote.

t=int(input())
for i in range(t):
 s=input().split()
 if('not' in s):
  print("Real Fancy")
 else:
  print("regularly fancy")


Solve in Python:
"I'm a fan of anything that tries to replace actual human contact." - Sheldon.
After years of hard work, Sheldon was finally able to develop a formula which would diminish the real human contact.
He found k$k$ integers n1,n2...nk$n_1,n_2...n_k$ . Also he found that if he could minimize the value of m$m$ such that  ∑ki=1$\sum_{i=1}^k$n$n$i$i$C$C$m$m$i$i$ is even, where m$m$ = ∑ki=1$\sum_{i=1}^k$mi$m_i$, he would finish the real human contact.
Since Sheldon is busy choosing between PS-4 and XBOX-ONE, he want you to help him to calculate the minimum value of m$m$.

-----Input:-----
- The first line of the input contains a single integer T$T$ denoting the number of test cases. The
description of T$T$ test cases follows.
- The first line of each test case contains a single integer k$k$.
- Next line contains k space separated integers n1,n2...nk$n_1,n_2...n_k$ .

-----Output:-----
For each test case output the minimum value of m for which ∑ki=1$\sum_{i=1}^k$n$n$i$i$C$C$m$m$i$i$ is even, where  m$m$=m1$m_1$+m2$m_2$+. . . mk$m_k$   and  0$0$ <= mi$m_i$<= ni$n_i$ .  If no such answer exists print -1.

-----Constraints-----
- 1≤T≤1000$1 \leq T \leq 1000$
- 1≤k≤1000$1 \leq k \leq 1000$
- 1≤ni≤10$1 \leq n_i \leq 10$18$18$

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

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

-----EXPLANATION:-----
5$5$C$C$2$2$ = 10 which is even and m is minimum.

t = int(input())

def conv(n):
    k = bin(n)
    k = k[2:]
    z = len(k)
    c = '1'*z
    if c == k:
     return False

def find(n):

    x = bin(n)[2:]
    str = ''
    for i in x[::-1]:
     if i == '0':
      str+='1'
      break
     else:
      str+='0'

    return int(str[::-1],2)

for i in range(t):

    n = int(input())


Solve in Python:
"If you didn't copy assignments during your engineering course, did you even do engineering?"
There are $Q$ students in Chef's class. Chef's teacher has given the students a simple assignment:
Write a function that takes as arguments an array $A$ containing only unique elements and a number $X$ guaranteed to be present in the array and returns the ($1$-based) index of the element that is equal to $X$.
The teacher was expecting a linear search algorithm, but since Chef is such an amazing programmer, he decided to write the following binary search function:
integer binary_search(array a, integer n, integer x):
integer low, high, mid
low := 1
high := n
while low ≤ high:
mid := (low + high) / 2
if a[mid] == x:
break
else if a[mid] is less than x:
low := mid+1
else:
high := mid-1
return mid

All of Chef's classmates have copied his code and submitted it to the teacher.
Chef later realised that since he forgot to sort the array, the binary search algorithm may not work. Luckily, the teacher is tired today, so she asked Chef to assist her with grading the codes. Each student's code is graded by providing an array $A$ and an integer $X$ to it and checking if the returned index is correct. However, the teacher is lazy and provides the exact same array to all codes. The only thing that varies is the value of $X$.
Chef was asked to type in the inputs. He decides that when typing in the input array for each code, he's not going to use the input array he's given, but an array created by swapping some pairs of elements of this original input array. However, he cannot change the position of the element that's equal to $X$ itself, since that would be suspicious.
For each of the $Q$ students, Chef would like to know the minimum number of swaps required to make the algorithm find the correct answer.

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

def binarySearch(start, end, xindex,opList):
 if start <= end:
  midindex = int((start+end)/2)

  opList.append(midindex)
  if xindex < midindex :
   return binarySearch(start, midindex-1, xindex, opList)

  elif xindex > midindex :
   return binarySearch(midindex+1, end, xindex, opList)

  else:
   return opList

def counter(opList,a, x):
 small = 0
 big = 0
 rightSmall = 0
 rightBig = 0

 for i in range(len(opList)-1):
  # print("for oplist[",i,"]=",opList[i])
  if opList[i] < opList[i+1]:
   # print("traverse to right")
   if x < a[opList[i]]:
    # print("x is small")
    small += 1
   else:
    rightSmall += 1
  else:
   # print("traverse to left")
   if x> a[opList[i]]:
    # print("x is big")
    big += 1
   else:
    rightBig += 1
 flag = isBigSmallAvailable(small,big,x,a,rightBig,rightSmall)
 if flag:
  total = small + big
  total = total - min(small,big)
  return total
 else:
  return -1

def isBigSmallAvailable(small,big,x,a,rightBig,rightSmall):
 s = 0
 b = 0
 for i in range(len(a)):
  if a[i] < x:
   s += 1
  if a[i] > x:
   b += 1
 s = s - rightSmall
 b = b - rightBig
 # print("big ",b)
 if s>=small and b>=big:
  return True
 return False

t = int(input())
swapCount = 0
swaped = []
visited = []
for z in range(t):
 l = list(map(int,input().split()))
 n = int(l[0])
 q = int(l[1])
 aa = list(map(int,input().split()))
 for i in range(q):
  swapCount = 0
  swaped.clear()
  visited.clear()
  a = aa[:]
  # print("aa is",aa)

  x = int(input())
  # a.sort()
  xindex = a.index(x)
  opList = []
  result = binarySearch(0, n-1, xindex, opList)
  count = counter(opList, a, x)

  # print(result)
  print(count)
  # else:
  #     print(swapCount)


Solve in Python:
"It does not matter how slowly you go as long as you do not stop." - Confucius
You are given an array $A_1, A_2, \ldots, A_N$ and an integer $K$. For each subarray $S = [A_l, A_{l+1}, \ldots, A_r]$ ($1 \le l \le r \le N$):
- Let's define an array $B$ as $S$ concatenated with itself $m$ times, where $m$ is the smallest integer such that $m(r-l+1) \ge K$.
- Next, let's sort $B$ and define $X = B_K$, i.e. as a $K$-th smallest element of $B$. Note that $|B| \ge K$.
- Then, let's define $F$ as the number of occurrences of $X$ in $S$.
- The subarray $S$ is beautiful if $F$ occurs in $S$ at least once.
Find the number of beautiful subarrays of $A$. Two subarrays $A_l, A_{l+1}, \ldots, A_r$ and $A_p, A_{p+1}, \ldots, A_q$ are different if $l \neq p$ or $r \neq q$.

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

-----Output-----
For each test case, print a single line containing one integer - the number of beautiful subarrays.

-----Constraints-----
- $1 \le T \le 5$
- $1 \le N \le 2,000$
- $1 \le K \le 10^9$
- $1 \le A_i \le 2000$ for each valid $i$

-----Subtasks-----
Subtask #1 (20 points): $1 \le N \le 200$
Subtask #2 (80 points): original constraints

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

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

-----Explanation-----
Example case 1: There are six subarrays of $A$: $[1]$, $[2]$, $[3]$, $[1, 2]$, $[2, 3]$, $[1, 2, 3]$. The corresponding arrays $B$ are $[1, 1, 1]$, $[2, 2, 2]$, $[3, 3, 3]$, $[1, 2, 1, 2]$, $[2, 3, 2, 3]$, $[1, 2, 3]$.
Three of the subarrays are beautiful: $[1]$, $[1, 2]$ and $[1, 2, 3]$. For these subarrays, $X$ is $1$, $2$ and $3$ respectively (for example, for $S = [1, 2]$, $B = [1, 2, 1, 2]$ is sorted to $[1, 1, 2, 2]$ and $X = 2$ is the $3$-rd element). Then, $F = 1$ for each of these subarrays, and each...

from math import ceil
def Beauty(array,f,n):
 i=0
 j=i
 ans=0
 while i<n and j<n:
  if array[j]==f:
   ans+=(n-j)*(j-i)+(n-j)
   i=j+1
   j=i
  else:
   j+=1
 return ans
from collections import defaultdict
for _ in range(int(input())):
 n,k=map(int,input().split( ))
 array=list(map(int,input().split( )))
 s=defaultdict(int)
 for v in array:
  s[v]+=1
 res=0
 for i in range(n):
  for j in range(i,n):
   b=array[i:j+1]
   b.sort()
   m=ceil(k/(j-i+1))
   t=ceil(k/m)
   x=b[t-1]
   f=b.count(x)
   if f in b:
    res+=1
   #res+=Beauty(array,f,n)
 print(res)


Solve in Python:
"Point reflection" or "point symmetry" is a basic concept in geometry where a given point, P, at a given position relative to a mid-point, Q has a corresponding point, P1, which is the same distance from Q but in the opposite direction.

## Task

Given two points P and Q, output the symmetric point of point P about Q.
Each argument is a two-element array of integers representing the point's X and Y coordinates.  Output should be in the same format, giving the X and Y coordinates of point P1.  You do not have to validate the input.

This kata was inspired by the Hackerrank challenge [Find Point](https://www.hackerrank.com/challenges/find-point)

def symmetric_point(p, q):
    dx = q[0] - p[0]
    dy = q[1] - p[1]
    return [q[0]+dx, q[1]+dy]


Solve in Python:
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.

Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!). $8$ illustration by 猫屋 https://twitter.com/nekoyaliu

Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact.

-----Input-----

The only line contains a string of length n (1 ≤ n ≤ 100). It's guaranteed that the string only contains uppercase English letters.

-----Output-----

Print a single integer — the number of subsequences "QAQ" in the string.

-----Examples-----
Input
QAQAQYSYIOIWIN

Output
4

Input
QAQQQZZYNOIWIN

Output
3

-----Note-----

In the first example there are 4 subsequences "QAQ": "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN".

s = input()
count = 0
for i in range(len(s)):
	if s[i] == 'Q':
		for j in range(i + 1, len(s)):
			if s[j] == 'A':
				for k in range(j + 1, len(s)):
					if s[k] == 'Q':
						count += 1
print(count)


Solve in Python:
"Ring Ring!!"
Sherlock's phone suddenly started ringing. And it was none other than Jim Moriarty..
"Long time no see ! You miss me right ? Anyway we'll talk about it later . Let me first tell you something. Dr.Watson is with me . And you've got only one chance to save him . Here's your challenge:.
Given a number N and another number M, tell if the remainder of N%M is odd or even. If it's odd, then print "ODD" else print "EVEN"

If Sherlock can answer the query correctly, then Watson will be set free. He has approached you for help since you being a programmer.Can you help him?

-----Input-----
The first line contains, T, the number of test cases..
Each test case contains an integer, N and M

-----Output-----
Output the minimum value for each test case

-----Constraints-----
1 = T = 20
1 <= N <= 10^18
1 <= M<= 10^9

-----Subtasks-----
Subtask #1 : (20 points)
1 = T = 20
1 <= N <= 100
1 <= M<= 100

Subtask 2 : (80 points)

1 = T = 20
1 <= N <= 10^18
1 <= M<= 10^9

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

Output:
EVEN
ODD

t=int(input())
for i in range(t):
 a=input().split(" ")
 n=int(a[0])
 m=int(a[1])
 if((n%m)%2==0):
  print("EVEN")
 else:
  print("ODD")


Solve in Python:
"Say my Name".
Todd Alquist is being taught the process of cooking methamphetamine, but to see whether he's really capable of learning it, Walt gives him a problem to solve. Since he can't solve it, he asks you for help.
You are given a tree with $N$ vertices (numbered $1$ through $N$), rooted at the vertex $1$. There is an integer written at each vertex; for each valid $i$, the value of vertex $i$ is $A$$i$.There also exists a special integer $K$.
Choose any leaf node, denoted by $X$, and go down a simple path from $root$ to $X$.
Let $S$ denote the set of all nodes lying on the simple path from $root$ to $X$.
For all $ i $ $\epsilon $ $ S $, choose an integer $D$ $\epsilon$ $[2^{A[i]-1},2^{A[i]})$.

Informally, for every node $i$ lying on the simple path from $root$ to $X$, you have to choose an integer $D$ such that  $2^{A[i]-1}\leq D < 2^{A[i]}$.
You now have to perform one of the two following operations :
- Bitwise XOR of all chosen integers.
- Bitwise AND of all chosen integers.
You have to determine whether you can choose the values in such a way that after performing one of the given operations you can get an integer equal to $K$.
- Note : A leaf is a node of the tree without any child nodes.
Determine if it is possible to obtain the value $K$ by performing the given operations.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- First line of each testcase contains two space separated integers $N, K$ denoting the number of nodes and the value of the special integer .
- $N-1$ lines follow , each line contains two space separated integers $u,v$ denoting an edge between $u$ and $v$.
- A single line follows containing $N$ space separated integers denoting the value of nodes.

-----Output:-----
For each testcase, output in a single line "YES"(without quotes) or "NO"(without quotes).

-----Constraints-----
- $1 \leq T \leq 10000$
- $2 \leq N \leq 5*10^5$
- $1 \leq K \leq 10^{18}$
- $1 \leq u,v \leq N$
- $ 1\leq A[i] \leq 64$
- Sum of $N$ over...

import sys,collections
input=sys.stdin.readline
def main():
 T=int(input())
 for _ in range(T):
  N,K=map(int,input().split())
  Tree={}
  for j in range(N):
   Tree[j]=[]

  for i in range(N-1):
   u,v=map(int,input().split())
   Tree[u-1].append(v-1)
   Tree[v-1].append(u-1)

  A=list(map(int,input().split()))

  vis=[0 for i in range(N)] #to mark visited vertices 0 for visited and             1 for not visited
  maxval=[[0,0] for i in range(N)] #Nx2 list where each i stores max             value till now and its count
  minval=[0 for i in range(N)] #Nx2 list where each i stores min value             till now
  lfnode=[] #list to store leaf nodes

  #Appending node 1
  vis[0]=1
  Q=collections.deque([0])
  maxval[0][0],maxval[0][1]=A[0],1
  minval[0]=A[0]

  while(len(Q)!=0):
   a=Q.pop()
   mv1=maxval[a][0]
   mv2=minval[a]

   flag=0 #to check leaf node

   for i in Tree[a]:
    if (vis[i]==0):
     vis[i]=1
     flag=1 #not a leaf node
     v=A[i]
     Q.append(i)

     #Comparing maximum value of parent node
     if (mv1<v):
      maxval[i][0],maxval[i][1]=v,1

     elif(mv1==v):
      maxval[i][0],maxval[i][1]=mv1,maxval[a][1]+1

     else:
      maxval[i][0],maxval[i][1]=maxval[a][0],maxval[a][1]

     #Comparing minimum value of parent node
     if (mv2>v):
      minval[i]=v
     elif(v==mv2):
      minval[i]=mv2
     else:
      minval[i]=minval[a]

   if (flag==0):
    lfnode.append(a)

  flag=0 #For answer if 0 then NO else YES

  K1=len(bin(K))-2 #length of K

  #print(lfnode,val)
  for i in lfnode:
   v1,v2=maxval[i][0],maxval[i][1]

   if (v1>K1 and v2%2==0):
    flag=1
   elif(v1==K1 and v2%2==1):
    flag=1

   v11=minval[i]
   if (v11>K1 and v11!=v1):
    flag=1
   elif(v11==K1):
    flag=1

   if(flag==1):
    break

  if (flag==1):
   print("YES")
  else:
   print("NO")
main()


Solve in Python:
"The Shell Game" involves cups upturned on a playing surface, with a ball placed underneath one of them.  The index of the cups are swapped around multiple times. After that the players will try to find which cup contains the ball.

Your task is as follows.  Given the cup that the ball starts under, and list of swaps, return the location of the ball at the end.  Cups are given like array/list indices.

For example, given the starting position `0` and the swaps `[(0, 1), (1, 2), (1, 0)]`:

 * The first swap moves the ball from `0` to `1`
 * The second swap moves the ball from `1` to `2`
 * The final swap doesn't affect the position of the ball.

 So

```python
find_the_ball(0, [(0, 1), (2, 1), (0, 1)]) == 2
```

There aren't necessarily only three cups in this game, but there will be at least two.  You can assume all swaps are valid, and involve two distinct indices.

def find_the_ball(pos, swaps):
    for swap in swaps:
        if pos in swap:
            pos = swap[1 - swap.index(pos)]
    return pos


Solve in Python:
"What do you know about happiness?" — Yoda
Chef is happy only if three conditions hold:
- Chef finished cooking a delicious meal
- Chef got AC for a programming problem with an almost correct code
- Chef got a new problem with a sequence of integers
Today, all three conditions are satisfied. Chef would like you to feel his happiness and provide him with a solution for this new problem with a sequence of integers. The problem is as follows.
You are given a sequence $A_1, A_2, \dots, A_N$. You need to determine if it is possible to choose two indices $i$ and $j$ such that $A_i \neq A_j$, but $A_{A_i}$ = $A_{A_j}$. (If it was possible, Chef would be truly happy.)

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

-----Output-----
For each test case, print a single line containing the string "Truly Happy" if it is possible to choose required indices or "Poor Chef" otherwise.

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

-----Subtasks-----
Subtask #1 (27 points): $1 \le N \le 1,000$
Subtask #2 (73 points): original constraints

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

-----Example Output-----
Truly Happy
Poor Chef
Poor Chef
Truly Happy

-----Explanation-----
Example case 1: Chef is truly happy because $A_{A_3} = A_{A_1}$ and $A_3 \neq A_1$.
Example case 2: There is no pair of indices which would make Chef truly happy. For instance, $A_{A_3} = A_{A_4}$, but $A_3 = A_4$,

for _ in range(int(input())):
 a = int(input())
 array = list(map(int,input().split()))
 common = list()
 for x in array:
  if array.count(x)>1:
   common.append(x)

 if len(common)==0:
  print("Poor Chef")
  continue

 ind = dict()
 for x in common:
  if x not in ind:
   ind[x]=list()
  for y in range(len(array)):
   if array[y]==x:
    ind[x].append(y+1)

 flag = 0
 for x in ind:
  lis = ind[x]
  for m in lis:
   for n in lis:
    if m!=n and m in array and n in array:
     print("Truly Happy")
     flag = 1
     break
   if flag == 1:
    break
  if flag == 1:
   break
 else:
  if flag == 0:
   print("Poor Chef")


Solve in Python:
# # Task:
  * #### Complete the pattern, using the special character ```■   □```
  * #### In this kata, we draw some histogram of the sound performance of ups and downs.

# # Rules:
  -  parameter ```waves```  The value of sound waves, an array of number, all number in array >=0.
  -  return a string, ```■``` represents the sound waves, and ```□``` represents the blank part, draw the histogram from bottom to top.

# # Example:

```
draw([1,2,3,4])

□□□■
□□■■
□■■■
■■■■

draw([1,2,3,3,2,1])

□□■■□□
□■■■■□
■■■■■■

draw([1,2,3,3,2,1,1,2,3,4,5,6,7])

□□□□□□□□□□□□■
□□□□□□□□□□□■■
□□□□□□□□□□■■■
□□□□□□□□□■■■■
□□■■□□□□■■■■■
□■■■■□□■■■■■■
■■■■■■■■■■■■■

draw([5,3,1,2,4,6,5,4,2,3,5,2,1])

□□□□□■□□□□□□□
■□□□□■■□□□■□□
■□□□■■■■□□■□□
■■□□■■■■□■■□□
■■□■■■■■■■■■□
■■■■■■■■■■■■■

draw([1,0,1,0,1,0,1,0])

■□■□■□■□
```

def draw(waves):
    m       = max(waves)
    rotHist = [ ('■'*v).rjust(m, '□') for v in waves ]
    return '\n'.join( map(''.join, zip(*rotHist)) )


Solve in Python:
# 'Magic' recursion call depth number

This Kata was designed as a Fork to the one from donaldsebleung Roboscript series with a reference to:

https://www.codewars.com/collections/roboscript

It is not more than an extension of Roboscript infinite "single-" mutual recursion handling to a "multiple-" case.

One can suppose that you have a machine that works through a specific language. It uses the script, which consists of 3 major commands:

 - `F` - Move forward by 1 step in the direction that it is currently pointing.

 - `L` - Turn "left" (i.e. rotate 90 degrees anticlockwise).

 - `R` - Turn "right" (i.e. rotate 90 degrees clockwise).

The number n afterwards enforces the command to execute n times.

To improve its efficiency machine language is enriched by patterns that are containers to pack and unpack the script.

The basic syntax for defining a pattern is as follows:

`pnq`

Where:

 - `p` is a "keyword" that declares the beginning of a pattern definition

 - `n` is a non-negative integer, which acts as a unique identifier for the pattern (pay attention, it may contain several digits).

 - `` is a valid RoboScript code (without the angled brackets)

 - `q` is a "keyword" that marks the end of a pattern definition

For example, if you want to define `F2LF2` as a pattern and reuse it later:

```
p333F2LF2q
```

To invoke a pattern, a capital `P` followed by the pattern identifier `(n)` is used:

```
P333
```

It doesn't matter whether the invocation of the pattern or the pattern definition comes first. Pattern definitions should always be parsed first.

```
P333p333P11F2LF2qP333p11FR5Lq
```

# ___Infinite recursion___

As we don't want a robot to be damaged or damaging someone else by becoming uncontrolable when stuck in an infinite loop, it's good to considere this possibility in the programs and to build a compiler that can detect such potential troubles before they actually happen.

* ### Single pattern recursion infinite loop

This is the simplest case, that occurs when the pattern is invoked...

import re
from collections import defaultdict, deque
def magic_call_depth_number(s):
    adjacent = defaultdict(list)
    for i, j, k in re.findall(r'(p\d+)(.+?)(q)', s):
        for n in re.findall(r'P\d+', j):
            adjacent[i.upper()].append(n)

    s, depths = re.sub(r'p.+?q', '', s), []

    def BFS(start):
        Q = deque([[start, 1, []]])
        while Q:
            node, depth, path = Q.popleft()
            path.append(node)
            if not adjacent[node] : depths.append(0)
            for i in adjacent[node]:
                if i not in path : Q.append([i, depth + 1, path[:]])
                else : depths.append(depth)

    [BFS(i) for i in re.findall(r'P\d+', s)]
    return [min(depths), max(depths)] if depths else [0,0]


Solve in Python:
# A History Lesson

Soundex is an interesting phonetic algorithm developed nearly 100 years ago for indexing names as they are pronounced in English. The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling.

Reference: https://en.wikipedia.org/wiki/Soundex

# Preface

I first read about Soundex over 30 years ago. At the time it seemed to me almost  like  A.I. that you could just type in somebody's name the way it sounded and there was still a pretty good chance it could match the correct person record. That was about the same year as the first "Terminator" movie so it was easy for me to put 2 and 2 together and conclude that Arnie must have had some kind of futuristic Soundex chip in his titanium skull helping him to locate ```Serah Coner```... or was it ```Sarh Connor```... or maybe ```Sayra Cunnarr```...

:-)

# Task

In this Kata you will encode strings using a Soundex variation called "American Soundex" using the following (case insensitive) steps:

* Save the first letter. Remove all occurrences of ```h``` and ```w``` except first letter.
* Replace all consonants (include the first letter) with digits as follows:
 * ```b```, ```f```, ```p```, ```v``` = 1
 * ```c```, ```g```, ```j```, ```k```, ```q```, ```s```, ```x```, ```z``` = 2
 * ```d```, ```t``` = 3
 * ```l``` = 4
 * ```m```, ```n``` = 5
 * ```r``` = 6
* Replace all adjacent same digits with one digit.
* Remove all occurrences of ```a```, ```e```, ```i```, ```o```, ```u```, ```y``` except first letter.
* If first symbol is a digit replace it with letter saved on step 1.
* Append 3 zeros if result contains less than 3 digits. Remove all except first letter and 3 digits after it

## Input

A space separated string of one or more names. E.g.

```Sarah Connor```

## Output

Space separated string of equivalent Soundex codes (the first character of each code must be uppercase). E.g.

```S600 C560```

from itertools import groupby

tr = [  (0,), ('b','f','p','v'), ('c','g','j','k','q','s','x','z'), ('d','t'), ('l'), ('m','n'), ('r')  ]

def soundex(name):
    name = name.lower().split(' ')

    first_l = [ e[0].upper() for e in name ]

    let_to_dig = loop( lambda x: indx(x, tr), loop( lambda x: x, name, lambda x: x not in 'hw' ) )

    del_duble = loop( lambda x: x[0], let_to_dig, funk2 = lambda x:groupby(x) )

    del_vowel = [[e[0],''.join([ x for i,x in enumerate(e) if x.isdigit() and i  ])] for e in del_duble ]

    return ' '.join((([first_l[i] ,e[0].upper()][all((e[0].isalpha(), e[0] == first_l[i]))] + ['',e[0]][all((e[0].isdigit(), first_l[i] in 'HW'))]) + e[1]).ljust(4,"0")[:4]
              for i,e in enumerate(del_vowel) )

def indx(elem, arr):
    for i, x in enumerate(arr):
        if elem in x:
            return str(i)
    return elem

def loop(func1, arr, excuse1=lambda x:x , excuse2=lambda x:x, funk2=lambda x:x):
    return [ [func1(x) for x in funk2(e) if excuse1(x)] for e in arr if excuse2(e) ]


Solve in Python:
# A History Lesson

Tetris is a puzzle video game originally designed and programmed by Soviet Russian software engineer Alexey Pajitnov. The first playable version was completed on June 6, 1984. Pajitnov derived its name from combining the Greek numerical prefix tetra- (the falling pieces contain 4 segments) and tennis, Pajitnov's favorite sport.

# About scoring system

The scoring formula is built on the idea that more difficult line clears should be awarded more points. For example, a single line clear is worth `40` points, clearing four lines at once (known as a Tetris) is worth `1200`.

A level multiplier is also used. The game starts at level `0`. The level increases every ten lines you clear. Note that after increasing the level, the total number of cleared lines is not reset.

For our task you can use this table:

        .demo {
    width:70%;
                border:1px solid #C0C0C0;
                border-collapse:collapse;
                padding:5px;
        }
        .demo th {
                border:1px solid #C0C0C0;
                padding:5px;
        }
        .demo td {
                border:1px solid #C0C0C0;
                padding:5px;
        }

Level
Points for 1 line
Points for 2 lines
Points for 3 lines
Points for 4 lines

0
40
100
300
1200

1
80
200
600
2400

2
120
300
900
3600

3
160
400
1200
4800

...

7
320
800
2400
9600

...
For level n you must determine the formula by yourself using given examples from the table.

# Task

Calculate the final score of the game using original Nintendo scoring system

# Input

Array with cleaned lines.
Example: `[4, 2, 2, 3, 3, 4, 2]`
Input will always be valid: array of random length (from `0` to `5000`) with numbers from `0` to `4`.

# Ouput

Calculated final score.
`def get_score(arr) -> int: return 0`

# Example
```python
get_score([4, 2, 2, 3, 3, 4, 2]); # returns 4900
```
Step 1: `+1200` points for 4 lines (current level `0`). Score: `0+1200=1200`;\
Step 2: `+100` for 2 lines. Score: `1200+100=1300`;\
Step 3: `+100`....

def get_score(arr) -> int:
    return sum([0, 40, 100, 300, 1200][n] * (1 + (sum(arr[:i]) // 10)) for i, n in enumerate(arr))


Solve in Python:
# A History Lesson

The Pony Express was a mail service operating in the US in 1859-60.

It reduced the time for messages to travel between the Atlantic and Pacific coasts to about 10 days, before it was made obsolete by the transcontinental telegraph.

# How it worked

There were a number of *stations*, where:

* The rider switched to a fresh horse and carried on, or

* The mail bag was handed over to the next rider

# Kata Task

`stations` is a list/array of distances (miles) from one station to the next along the Pony Express route.

Implement the `riders` method/function, to return how many riders are necessary to get the mail from one end to the other.

##  Missing rider

In this version of the Kata a rider may go missing. In practice, this could be for a number of reasons - a lame horse, an accidental fall, foul play...

After some time, the rider's absence would be noticed at the **next** station, so the next designated rider from there would have to back-track the mail route to look for his missing colleague. The missing rider is then safely escorted back to the station he last came from, and the mail bags are handed to his rescuer (or another substitute rider if necessary).

`stationX` is the number (2..N) of the station where the rider's absence was noticed.

# Notes

* Each rider travels as far as he can, but never more than 100 miles.

# Example

GIven

* `stations = [43, 23, 40, 13]`

* `stationX = 4`

So

`S1` ...  ... 43 ...  ... `S2` ...  ... 23 ...  ... `S3` ...  ... 40 ...  ... `S4` ...  ... 13 ...  ... `S5`

* Rider 1 gets as far as Station S3
* Rider 2 (at station S3) takes mail bags from Rider 1
* Rider 2 never arrives at station S4
* Rider 3 goes back to find what happened to Rider 2
* Rider 2 and Rider 3 return together back to Station S3
* Rider 3 takes mail bags from Rider 2
* Rider 3 completes the journey to Station S5

**Answer:**
3 riders

*Good Luck.
DM.*

---

See also
* The Pony Express
* The Pony Express (missing rider)

def riders(sts, x):
    st, x, back, n = 0, x-1, 0, 1
    while True:
        remain, back = 100 - back, 0
        while remain >= sts[st]:
            remain -= sts[st]
            st += 1
            if st == x:
                st -= 1
                x = -1
                back = sts[st]
                break
            elif st == len(sts):
                return n
        n += 1


Solve in Python:
# A History Lesson

The Pony Express was a mail service operating in the US in 1859-60.

It reduced the time for messages to travel between the Atlantic and Pacific coasts to about 10 days, before it was made obsolete by the [transcontinental telegraph](https://en.wikipedia.org/wiki/First_transcontinental_telegraph).

# How it worked

There were a number of *stations*, where:

* The rider switched to a fresh horse and carried on, or
* The mail bag was handed over to the next rider

# Kata Task

`stations` is a list/array of distances (miles) from one station to the next along the Pony Express route.

Implement the `riders` method/function, to return how many riders are necessary to get the mail from one end to the other.

**NOTE:** Each rider travels as far as he can, but never more than 100 miles.

---
*Good Luck.
DM.*

---

See also

* The Pony Express
* The Pony Express (missing rider)

def riders(A):
    Z=[0]
    for x in A:
        if Z[-1]+x<=100:Z[-1]+=x
        else:Z.append(x)
    return len(Z)


Solve in Python:
# A wolf in sheep's clothing

Wolves have been reintroduced to Great Britain. You are a sheep farmer, and are now plagued by wolves which pretend to be sheep. Fortunately, you are good at spotting them.

Warn the sheep in front of the wolf that it is about to be eaten. Remember that you are standing **at the front of the queue** which is at the end of the array:

```
[sheep, sheep, sheep, sheep, sheep, wolf, sheep, sheep]      (YOU ARE HERE AT THE FRONT OF THE QUEUE)
   7      6      5      4      3            2      1
```

If the wolf is the closest animal to you, return `"Pls go away and stop eating my sheep"`. Otherwise, return `"Oi! Sheep number N! You are about to be eaten by a wolf!"` where `N` is the sheep's position in the queue.

**Note:** there will always be exactly one wolf in the array.

## Examples

```python
warn_the_sheep(["sheep", "sheep", "sheep", "wolf", "sheep"]) == 'Oi! Sheep number 1! You are about to be eaten by a wolf!'

warn_the_sheep(['sheep', 'sheep', 'wolf']) == 'Pls go away and stop eating my sheep'
```

def warn_the_sheep(queue):
    if queue.index('wolf') == len(queue) - 1:
        return 'Pls go away and stop eating my sheep'
    else:
        sheep = queue[::-1].index('wolf')
        return f'Oi! Sheep number {sheep}! You are about to be eaten by a wolf!'


Solve in Python:
# ASC Week 1 Challenge 5 (Medium #2)

Create a function that takes a 2D array as an input, and outputs another array that contains the average values for the numbers in the nested arrays at the corresponding indexes.

Note: the function should also work with negative numbers and floats.

## Examples
```
[ [1, 2, 3, 4], [5, 6, 7, 8] ]  ==>  [3, 4, 5, 6]

1st array: [1, 2, 3, 4]
2nd array: [5, 6, 7, 8]
            |  |  |  |
            v  v  v  v
average:   [3, 4, 5, 6]

```

And another one:
```
[ [2, 3, 9, 10, 7], [12, 6, 89, 45, 3], [9, 12, 56, 10, 34], [67, 23, 1, 88, 34] ]  ==>  [22.5, 11, 38.75, 38.25, 19.5]

1st array: [  2,   3,    9,   10,    7]
2nd array: [ 12,   6,   89,   45,    3]
3rd array: [  9,  12,   56,   10,   34]
4th array: [ 67,  23,    1,   88,   34]
              |    |     |     |     |
              v    v     v     v     v
average:   [22.5, 11, 38.75, 38.25, 19.5]
```

def avg_array(arrs):

    return [sum(a)/len(a) for a in list(zip(*arrs))]


Solve in Python:
# An introduction to propositional logic

Logic and proof theory are fields that study the formalization of logical statements and the structure of valid proofs. One of the most common ways to represent logical reasonings is with **propositional logic**.

A propositional formula is no more than what you normally use in your *if statements*, but without functions or predicates. The basic unit for these formulas are **literals**. Let's see some examples:

```
f = p ∧ q
```

Here ```p``` and ```q``` would be the literals. This formula means that *f* evaluates to ```True``` only when both ```p``` **and** ```q``` are True too. The ```∧``` operator is formally called **conjunction** and is often called **and**.

```
f = p ∨ q
```

This formula means that *f* evaluates to ```True``` only when any of ```p``` **or** ```q``` are  True. This includes the case when both are True. The ```∨``` operator is formally called **disjunction** and is often called **or**.

```
f = ¬p
```

The ```¬``` operator is analogous to the **not** operation. it evaluates to True only when its argument evaluates to False.

Normally, there are also two other operators called **implication** and **biconditional**, but we will ignore them for this kata (they can be expressed in terms of the other three anyways).

Once we know this, can construct what is called an **interpretation** in order to evaluate a propositional formula. This is a fancy name for any structure that tells us which literals are False and which ones are True. Normally, interpretations are given as a set:

```python
p = Literal('p')
q = Literal('q')
r = Literal('r')

f = p ∨ q ∨ ¬r

i_1 = {p, q} # p and q are True, r is False
i_2 = {r}    # r is True, p and q are False
i_3 = {}     # p, q and r are False

# Note: the 'evaluate' function is not given
evaluate(f, i_1) == True
evaluate(f, i_2) == False
evaluate(f, i_3) == True
```

As you can see, if the literal is in the set, we say it evaluates to True, else it is False.

As a final note, an interpretation that makes a formula...

from itertools import combinations
from typing import Iterable, List

def literals(f: Formula) -> List[Literal]:
    if f.is_literal():
        return [f]
    return [x for g in f.args for x in literals(g)]

def evaluate(f: Formula, i: Iterable[Literal]) -> bool:
    if f.is_literal():
        return f in i
    if f.is_not():
        return not evaluate(f.args[0], i)
    args = (evaluate(g, i) for g in f.args)
    if f.is_and():
        return all(args)
    if f.is_or():
        return any(args)

def sat(f: Formula):
    lits = set(literals(f))
    n = len(lits)
    for r in range(0, n + 1):
        for i in combinations(lits, r):
            if evaluate(f, set(i)):
                return set(i)
    return False


Solve in Python:
# Back-Story

Every day I travel on the freeway.

When I am more bored than usual I sometimes like to play the following counting game I made up:

* As I join the freeway my count is ```0```
* Add ```1``` for every car that I overtake
* Subtract ```1``` for every car that overtakes me
* Stop counting when I reach my exit

What an easy game! What fun!

# Kata Task

You will be given
* The distance to my exit (km)
* How fast I am going (kph)
* Information about a lot of other cars
 * Their time (relative to me) as I join the freeway. For example,
   * ```-1.5``` means they already passed my starting point ```1.5``` minutes ago
   * ```2.2``` means they will pass my starting point ```2.2``` minutes from now
 * How fast they are going (kph)

Find what is my "score" as I exit the freeway!

# Notes

* Assume all cars travel at a constant speeds

 Safety Warning

If you plan to play this "game" remember that it is not really a game. You are in a **real** car.

There may be a temptation to try to beat your previous best score.

Please don't do that...

def freeway_game(dist_km_to_exit, my_speed_kmph, other_cars):
    my_time_to_exit = dist_km_to_exit / my_speed_kmph
    return sum(
        + (lead < 0 and my_time_to_exit * speed < dist_km_to_exit + lead / 60 * speed)
        - (lead > 0 and my_time_to_exit * speed > dist_km_to_exit + lead / 60 * speed)
        for lead, speed in other_cars)


Solve in Python:
# Background

My TV remote control has arrow buttons and an `OK` button.

I can use these to move a "cursor" on a logical screen keyboard to type words...

# Keyboard

The screen "keyboard" layout looks like this

  #tvkb {
    width : 400px;
    border: 5px solid gray; border-collapse: collapse;
  }
  #tvkb td {
    color : orange;
    background-color : black;
    text-align : center;
    border: 3px solid gray; border-collapse: collapse;
  }

abcde123
fghij456
klmno789
pqrst.@0
uvwxyz_/
aASP

* `aA` is the SHIFT key. Pressing this key toggles alpha characters between UPPERCASE and lowercase
* `SP` is the space character
* The other blank keys in the bottom row have no function

# Kata task

How many button presses on my remote are required to type the given `words`?

## Hint

This Kata is an extension of the earlier ones in this series. You should complete those first.

## Notes

* The cursor always starts on the letter `a` (top left)
* The alpha characters are initially lowercase (as shown above)
* Remember to also press `OK` to "accept" each letter
* Take the shortest route from one letter to the next
* The cursor wraps, so as it moves off one edge it will reappear on the opposite edge
* Although the blank keys have no function, you may navigate through them if you want to
* Spaces may occur anywhere in the `words` string
* Do not press the SHIFT key until you need to. For example, with the word `e.Z`, the SHIFT change happens **after** the `.` is pressed (not before)

# Example

words = `Code Wars`

* C => `a`-`aA`-OK-`A`-`B`-`C`-OK = 6
* o => `C`-`B`-`A`-`aA`-OK-`u`-`v`-`w`-`x`-`y`-`t`-`o`-OK = 12
* d => `o`-`j`-`e`-`d`-OK = 4
* e => `d`-`e`-OK = 2
* space => `e`-`d`-`c`-`b`-`SP`-OK = 5
* W => `SP`-`aA`-OK-`SP`-`V`-`W`-OK = 6
* a => `W`-`V`-`U`-`aA`-OK-`a`-OK = 6
* r => `a`-`f`-`k`-`p`-`q`-`r`-OK = 6
* s => `r`-`s`-OK = 2

Answer = 6 + 12 + 4 + 2 + 5 + 6 + 6 + 6 + 2 = 49

*Good Luck!
DM.*

Series
* TV Remote
* TV Remote (shift and space)
* TV Remote (wrap)
* TV Remote (symbols)

D = {v:[r, c] for r, row in enumerate(['abcde123', 'fghij456', 'klmno789', 'pqrst.@0', 'uvwxyz_/','* ']) for c, v in enumerate(row)}

def manhattan_dist(*points):
    print('points md: ', points)
    return  [abs(z2-z1) for z1,z2 in zip(*points)]

def wrap_manhattan_dist(*points):
    dist = manhattan_dist(*points)
    wdist = [min(dist[0],6-dist[0]), min(dist[1],8-dist[1])]
    return sum(wdist)

import re
def tv_remote(words):
    words = re.sub('([A-Z])',r'*\1*',words).lower()
    words = re.sub('\*([\d.@_/ ]*)(\*|$)',r'\1',words)
    words = re.sub('\*$','',words)
    words = re.sub('\*([0-9.@_/ ]+)([^\*])',r'\1*\2',words)
    words = 'a' + words
    moves = sum([wrap_manhattan_dist(D[words[i]], D[words[i+1]])+1 for i in range(len(words)-1)])
    return moves


Solve in Python:
# Background

A spider web is defined by

* "rings" numbered out from the centre as `0`, `1`, `2`, `3`, `4`

* "radials" labelled clock-wise from the top as `A`, `B`, `C`, `D`, `E`, `F`, `G`, `H`

Here is a picture to help explain:

# Web Coordinates

As you can see, each point where the rings and the radials intersect can be described by a "web coordinate".

So in this example the spider is at `H3` and the fly is at `E2`

# Kata Task

Our friendly jumping spider is resting and minding his own spidery business at web-coordinate `spider`.

An inattentive fly bumbles into the web at web-coordinate `fly` and gets itself stuck.

Your task is to calculate and return **the
 distance** the spider must jump to get to the fly.

# Example

The solution to the scenario described by the picture is ``4.63522``

# Notes

* The centre of the web will always be referred to as `A0`
* The rings intersect the radials at **evenly** spaced distances of **1 unit**

____

Good Luck!DM

from math import cos, radians, sin

def spider_to_fly(spider, fly):
    (ts, rs), (tf, rf) = ((radians((ord(c) - 65) * 45), int(n)) for c, n in (spider, fly))
    return ((rs*cos(ts) - rf*cos(tf))**2 + (rs*sin(ts) - rf*sin(tf))**2)**0.5


Solve in Python:
# Background

I drink too much coffee. Eventually it will probably kill me.

*Or will it..?*

Anyway, there's no way to know.

*Or is there...?*

# The Discovery of the Formula

I proudly announce my discovery of a formula for measuring the life-span of coffee drinkers!

For

* ```h``` is a health number assigned to each person (8 digit date of birth YYYYMMDD)

* ```CAFE``` is a cup of *regular* coffee

* ```DECAF``` is a cup of *decaffeinated* coffee

To determine the life-time coffee limits:

* Drink cups of coffee (i.e. add to ```h```) until any part of the health number includes `DEAD`

* If the test subject can survive drinking five thousand cups wihout being ```DEAD``` then coffee has no ill effect on them

# Kata Task

Given the test subject's date of birth, return an array describing their life-time coffee limits

```[ regular limit , decaffeinated limit ]```

## Notes

* The limits are ```0``` if the subject is unaffected as described above

* At least 1 cup must be consumed (Just thinking about coffee cannot kill you!)

# Examples

* John was born 19/Jan/1950 so ```h=19500119```. His coffee limits are ```[2645, 1162]``` which is only about 1 cup per week. You better cut back John...How are you feeling? You don't look so well.

* Susan (11/Dec/1965) is unaffected by decaffeinated coffee, but regular coffee is very bad for her ```[111, 0]```. Just stick to the decaf Susan.

* Elizabeth (28/Nov/1964) is allergic to decaffeinated coffee. Dead after only 11 cups ```[0, 11]```. Read the label carefully Lizzy! Is it worth the risk?

* Peter (4/Sep/1965) can drink as much coffee as he likes ```[0, 0]```. You're a legend Peter!!

Hint: https://en.wikipedia.org/wiki/Hexadecimal

*Note: A life-span prediction formula this accurate has got to be worth a lot of money to somebody! I am willing to sell my copyright to the highest bidder. Contact me via the discourse section of this Kata.*

import re
def coffee_limits(year, month, day):
    # Your code here!
    h_cafe = str(year)

    if len(str(month)) == 1:
        h_cafe += "0" + str(month)
    else:
        h_cafe += str(month)

    if len(str(day)) == 1:
        h_cafe += "0" + str(day)
    else:
        h_cafe += str(day)

    h_cafe = int(h_cafe)
    h_decaf = h_cafe
    n = 0
    cafe = 0
    decaf = 0
    print(h_cafe)
    while (n < 5000):
        h_cafe += 51966
        h_decaf += 912559
        n += 1
        if "dead" in hex(h_cafe):
            if cafe == 0 :
                cafe = n
        elif "dead" in hex(h_decaf):
            if decaf == 0:
                decaf = n
    return [cafe,decaf]


Solve in Python:
# Background

My TV remote control has arrow buttons and an `OK` button.

I can use these to move a "cursor" on a logical screen keyboard to type "words"...

The screen "keyboard" layout looks like this

  #tvkb {
    width : 300px;
    border: 5px solid gray; border-collapse: collapse;
  }
  #tvkb td {
    color : orange;
    background-color : black;
    text-align : right;
    border: 3px solid gray; border-collapse: collapse;
  }

abcde123
fghij456
klmno789
pqrst.@0
uvwxyz_/

# Kata task

How many button presses on my remote are required to type a given `word`?

## Notes

* The cursor always starts on the letter `a` (top left)
* Remember to also press `OK` to "accept" each character.
* Take a direct route from one character to the next
* The cursor does not wrap (e.g. you cannot leave one edge and reappear on the opposite edge)
* A "word" (for the purpose of this Kata) is any sequence of characters available on my virtual "keyboard"

# Example

word = `codewars`

* c => `a`-`b`-`c`-OK = 3
* o => `c`-`d`-`e`-`j`-`o`-OK = 5
* d => `o`-`j`-`e`-`d`-OK = 4
* e => `d`-`e`-OK = 2
* w => `e`-`j`-`o`-`t`-`y`-`x`-`w`-OK = 7
* a => `w`-`r`-`m`-`h`-`c`-`b`-`a`-OK = 7
* r => `a`-`f`-`k`-`p`-`q`-`r`-OK = 6
* s => `r`-`s`-OK = 2

Answer = 3 + 5 + 4 + 2 + 7 + 7 + 6 + 2 = 36

*Good Luck!
DM.*

Series
* TV Remote
* TV Remote (shift and space)
* TV Remote (wrap)
* TV Remote (symbols)

LAYOUT = """\
a   b   c   d   e   1   2   3
f   g   h   i   j   4   5   6
k   l   m   n   o   7   8   9
p   q   r   s   t   .   @   0
u   v   w   x   y   z   _   /
""".split()

def get_pos(char):
    return divmod(LAYOUT.index(char), 8)

def distance(char1, char2):
    c1x, c1y = get_pos(char1)
    c2x, c2y = get_pos(char2)
    return abs(c1x - c2x) + abs(c1y - c2y)

def tv_remote(word):
    return sum(distance(prev, curr) for prev, curr in zip("a" + word, word)) + len(word)


Solve in Python:
# Background

My TV remote control has arrow buttons and an `OK` button.

I can use these to move a "cursor" on a logical screen keyboard to type words...

# Keyboard

The screen "keyboard" layout looks like this

  #tvkb {
    width : 400px;
    border: 5px solid gray; border-collapse: collapse;
  }
  #tvkb td {
    color : orange;
    background-color : black;
    text-align : center;
    border: 3px solid gray; border-collapse: collapse;
  }

abcde123
fghij456
klmno789
pqrst.@0
uvwxyz_/
aASP

* `aA` is the SHIFT key. Pressing this key toggles alpha characters between UPPERCASE and lowercase
* `SP` is the space character
* The other blank keys in the bottom row have no function

# Kata task

How many button presses on my remote are required to type the given `words`?

## Notes

* The cursor always starts on the letter `a` (top left)
* The alpha characters are initially lowercase (as shown above)
* Remember to also press `OK` to "accept" each letter
* Take a direct route from one letter to the next
* The cursor does not wrap (e.g. you cannot leave one edge and reappear on the opposite edge)
* Although the blank keys have no function, you may navigate through them if you want to
* Spaces may occur anywhere in the `words` string.
* Do not press the SHIFT key until you need to. For example, with the word `e.Z`, the SHIFT change happens **after** the `.` is pressed (not before)

# Example

words = `Code Wars`

* C => `a`-`f`-`k`-`p`-`u`-`aA`-OK-`U`-`P`-`K`-`F`-`A`-`B`-`C`-OK = 14
* o => `C`-`H`-`M`-`R`-`W`-`V`-`U`-`aA`-OK-`SP`-`v`-`q`-`l`-`m`-`n`-`o`-OK = 16
* d => `o`-`j`-`e`-`d`-OK = 4
* e => `d`-`e`-OK = 2
* space => `e`-`d`-`c`-`b`-`g`-`l`-`q`-`v`-`SP`-OK = 9
* W => `SP`-`aA`-OK-`SP`-`V`-`W`-OK = 6
* a => `W`-`V`-`U`-`aA`-OK-`u`-`p`-`k`-`f`-`a`-OK = 10
* r => `a`-`f`-`k`-`p`-`q`-`r`-OK = 6
* s => `r`-`s`-OK = 2

Answer = 14 + 16 + 4 + 2 + 9 + 6 + 10 + 6 + 2 = 69

*Good Luck!
DM.*

Series
* TV Remote
* TV Remote (shift and space)
* TV Remote (wrap)
* TV Remote (symbols)

import re

def tv_remote(words):
    letters = {c: (x, y)
        for y, row in enumerate((
        "abcde123",
        "fghij456",
        "klmno789",
        "pqrst.@0",
        "uvwxyz_/",
        "⇧ "))
        for x, c in enumerate(row)}
    words = re.sub(r'((?:^|[a-z])[^A-Z]*)([A-Z])', r'\1⇧\2', words)
    words = re.sub(r'([A-Z][^a-z]*)([a-z])', r'\1⇧\2', words)
    words = words.lower()
    return sum(
        abs(letters[c1][0] - letters[c2][0]) +
        abs(letters[c1][1] - letters[c2][1]) + 1
        for c1, c2 in zip("a" + words, words))


Solve in Python:
# Background

My pet bridge-maker ants are marching across a terrain from left to right.

If they encounter a gap, the first one stops and then next one climbs over him, then the next, and the next, until a bridge is formed across the gap.

What clever little things they are!

Now all the other ants can walk over the ant-bridge.

When the last ant is across, the ant-bridge dismantles itself similar to how it was constructed.

This process repeats as many times as necessary (there may be more than one gap to cross) until all the ants reach the right hand side.

# Kata Task

My little ants are marching across the terrain from left-to-right in the order ```A``` then ```B``` then ```C```...

What order do they exit on the right hand side?

# Notes

* ```-``` = solid ground
* ```.``` = a gap
* The number of ants may differ but there are always enough ants to bridge the gaps
* The terrain never starts or ends with a gap
* Ants cannot pass other ants except by going over ant-bridges
* If there is ever ambiguity which ant should move, then the ant at the **back** moves first

# Example

## Input
* ants = ````GFEDCBA````
* terrain = ```------------...-----------```

## Output
* result = ```EDCBAGF```

## Details

Ants moving left to right.
GFEDCBA
------------...-----------

The first one arrives at a gap.
GFEDCB     A
------------...-----------

They start to bridge over the gap...
GFED       ABC
------------...-----------

...until the ant-bridge is completed!
GF         ABCDE
------------...-----------

And then the remaining ants can walk across the bridge.
               F
G          ABCDE
------------...-----------

And when no more ants need to cross...
           ABCDE        GF
------------...-----------

... the bridge dismantles itself one ant at a time....
             CDE      BAGF
------------...-----------

...until all ants get to the other side
                   EDCBAGF
------------...-----------

def ant_bridge(ants, terrain):
    n = terrain.replace('-.', '..').replace('.-', '..').count('.') % len(ants)
    return ants[-n:] + ants[:-n]


Solve in Python:
# Background

The famous Collatz Sequence is generated with the following rules:

* Start with a positive integer `a[0] = n`.
* If `a[i]` is even, `a[i+1] = a[i] / 2`.
* Otherwise, `a[i+1] = a[i] * 3 + 1`.

However, for the purpose of this Kata, I give a **slightly modified definition**:

* If `a[i]` is even, `a[i+1] = a[i] / 2`. This step is a step-down, or `D`.
* Otherwise, `a[i+1] = (a[i] * 3 + 1) / 2`. This step is a step-up, or `U`.

Also, for any starting number, the sequence is generated indefinitely, not ending at 1.

# Problem Description

For any given starting number, we can record the types of steps(`D` or `U`) from it.
For example, if we start with the number 11, the Collatz steps look like this:
```
a[0] = 11
a[1] = (11 * 3 + 1) / 2 = 17 -> U
a[2] = (17 * 3 + 1) / 2 = 26 -> U
a[3] = 26 / 2 = 13           -> D
a[4] = (13 * 3 + 1) / 2 = 20 -> U
a[5] = 20 / 2 = 10           -> D
a[6] = 10 / 2 = 5            -> D
a[7] = (5 * 3 + 1) / 2 = 8   -> U
a[8] = 8 / 2 = 4             -> D
a[9] = 4 / 2 = 2             -> D
a[10] = 2 / 2 = 1            -> D
a[11] = (1 * 3 + 1) / 2 = 2  -> U
a[12] = 2 / 2 = 1            -> D
...
```

```
11 -> 17 -> 26 -> 13 -> 20 -> 10 -> 5 -> 8 -> 4 -> 2 -> 1 -> 2 -> 1 -> ...
   U     U     D     U     D     D    U    D    D    D    U    D
```

Based on the steps shown above, the first four Collatz steps of 11 is `UUDU`.
Also, 107 is the smallest number over 100 whose Collatz steps start with `UUDU`, and
1003 is the smallest number over 1000 with the property.

A special example is the number 1, which can generate any number of `UD`.

Find the smallest integer exceeding or equal to `n` whose Collatz steps start with the given string `steps`.

# Constraints

`1 <= n <= 10 ** 9`

`n` is always a valid integer.

`1 <= length(steps) <= 25`

The string `steps` will entirely consist of `U`s and `D`s.

# Examples

```python
collatz_steps(1, 'UUDU') == 11
collatz_steps(100, 'UUDU') == 107
collatz_steps(1000, 'UUDU') == 1003

collatz_steps(1, 'UD') == 1
collatz_steps(1, 'UDUD') ==...

def collatz_steps(n, s):
    while True:
        x = n
        ans = ''
        flag = True
        for j in range(len(s)):
            if x%2 == 0:
                x = x//2
                ans += 'D'
            else:
                x = (x*3+1)//2
                ans += 'U'
            if ans[j] != s[j]:
                flag = False
                break
        if flag == True:
            return n
        else:
            n += 2**(len(ans)-1)


Solve in Python:
# Background:

You're working in a number zoo, and it seems that one of the numbers has gone missing!

Zoo workers have no idea what number is missing, and are too incompetent to figure it out, so they're hiring you to do it for them.

In case the zoo loses another number, they want your program to work regardless of how many numbers there are in total.

___

## Task:

Write a function that takes a shuffled list of unique numbers from `1` to `n` with one element missing (which can be any number including `n`). Return this missing number.

**Note**: huge lists will be tested.

## Examples:

```
[1, 3, 4]  =>  2
[1, 2, 3]  =>  4
[4, 2, 3]  =>  1
```

def find_missing_number(numbers):
    if numbers == []:return 1
    diff = list(set(range(1, len(numbers)+1))- set(numbers))
    if diff == []:return max(numbers)+1
    return diff[0]


Solve in Python:
# Base reduction

## Input

A positive integer:
```
0 < n < 1000000000
```

## Output

The end result of the base reduction.

If it cannot be fully reduced (reduced down to a single-digit number), return -1.

Assume that if 150 conversions from base 11 take place in a row, the number cannot be fully reduced.

## Description

Base reduction is a process where a number is inputted, repeatedly converted into another base, and then outputted if it cannot be reduced anymore. If it cannot be fully reduced, return -1.

During the base conversions, the number is converted from the lowest base it can be converted from into base 10. For example, 123 would be converted from base 4 to base 10, since base 4 is the lowest base that 123 can be in (123 base 3 is impossible; in base 3, there is no digit 3).

If the lowest possible base the number can be converted into is 10, convert the number from base 11 to base 10. For example, 53109 would be converted from base 11 to base 10, since base 10 is the lowest base it can be in.

In the end, you should get a number that cannot be reduced by this process (a single digit number).

## Example

Starting with 5312:
```
5312 base 6 = 1196 base 10
1196 base 11 = 1557 base 10
1557 base 8 = 879 base 10
879 base 11 = 1054 base 10
1054 base 6 = 250 base 10
250 base 6 = 102 base 10
102 base 3 = 11 base 10
11 base 2 = 3 base 10
```
The output would be 3.

def basereduct(x):
    for _ in range(150):
        s = str(x)
        x = int(s, max(int(c) for c in s) + 1 if '9' not in s else 11)
        if x < 10: return x
    return -1


Solve in Python:
# Base64 Numeric Translator

Our standard numbering system is (Base 10). That includes 0 through 9. Binary is (Base 2), only 1’s and 0’s.  And Hexadecimal is (Base 16) (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F). A hexadecimal “F” has a (Base 10) value of 15. (Base 64) has 64 individual characters which translate in value in (Base 10) from between 0 to 63.

####Write a method that will convert a string from (Base 64) to it's (Base 10) integer value.

The (Base 64) characters from least to greatest will be
```
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
```
Where 'A' is equal to 0 and '/' is equal to 63.

Just as in standard (Base 10) when you get to the highest individual integer 9 the next number adds an additional place and starts at the beginning 10; so also (Base 64) when you get to the 63rd digit '/' and the next number adds an additional place and starts at the beginning "BA".

Example:
```
base64_to_base10("/") # => 63
base64_to_base10("BA") # => 64
base64_to_base10("BB") # => 65
base64_to_base10("BC") # => 66
```

Write a method `base64_to_base10` that will take a string (Base 64) number and output it's (Base 10) value as an integer.

def base64_to_base10(s):
    n = 0
    for c in s:
        n = n * 64 + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.index(c)
    return n


Solve in Python:
# Bubblesort Algorithm

## Overview

The Bubblesort Algorithm is one of many algorithms used to sort a list of similar items (e.g. all numbers or all letters) into either ascending order or descending order.  Given a list (e.g.):

```python
[9, 7, 5, 3, 1, 2, 4, 6, 8]
```

To sort this list in ascending order using Bubblesort, you first have to compare the first two terms of the list.  If the first term is larger than the second term, you perform a swap.  The list then becomes:

```python
[7, 9, 5, 3, 1, 2, 4, 6, 8] # The "9" and "7" have been swapped because 9 is larger than 7 and thus 9 should be after 7
```

You then proceed by comparing the 2nd and 3rd terms, performing a swap *when necessary*, and then the 3rd and 4th term, then the 4th and 5th term, etc. etc.  When you reach the end of the list, it is said that you have completed **1 complete pass**.

## Task

Given an array of integers, your function `bubblesortOnce`/`bubblesort_once`/`BubblesortOnce` (or equivalent, depending on your language's naming conventions) should return a *new* array equivalent to performing exactly **1 complete pass** on the original array.  Your function should be pure, i.e. it should **not** mutate the input array.

def bubblesort_once(arr):

    new_arr = arr.copy()
    for i in range(len(new_arr)-1):
        if new_arr[i]>new_arr[i+1]:
            new_arr[i], new_arr[i+1] = new_arr[i+1], new_arr[i]
    return new_arr


Solve in Python:
# Challenge :

Write a function that takes a single argument `n` that is a string representation of a simple mathematical expression and evaluates it as a floating point value.

# Commands :
- positive or negative decimal numbers
- `+, -, *, /, ( / ).`

---

Expressions use [infix notation](https://en.wikipedia.org/wiki/Infix_notation).

# Evaluation :

Operators should be evaluated in the order they appear and not as in `BODMAS`, though brackets __should__ be correctly observed.

The function should return the correct result for any possible expression of this form.

# Note :

- All given input will be valid.
- It will consist entirely of numbers or one of the operators.
- Parentheses will alway be matched.
- Use of `eval` or its equivalent is forbidden
- use of `exec` is forbidden (Python)
- Use of `Function` or any of their (Function, eval) equivalent is also forbidden.
- Using `require` is also forbidden. (`import` for python)
- Using more than 7 (8 for python) lines is also forbidden.
- Using more than 260 (JS) / 240 (python) characters is also forbidden.
- Having more than 100 chars per line is forbidden.
- Having more than 6 semi-colons is forbidden

and that is about it.

---

# Examples :

    e("2*3*4*5+99")               ---> 219
    e("2*3*4*5+99*321-12312312")  ---> -12242013
    e("1-2*2/2*2-1*7+3")          ---> -18

---


Solve in Python:
# Connect Four

Take a look at wiki description of Connect Four game:

[Wiki Connect Four](https://en.wikipedia.org/wiki/Connect_Four)

The grid is 6 row by 7 columns, those being named from A to G.

You will receive a list of strings showing the order of the pieces which dropped in columns:

```python
  pieces_position_list = ["A_Red",
                          "B_Yellow",
                          "A_Red",
                          "B_Yellow",
                          "A_Red",
                          "B_Yellow",
                          "G_Red",
                          "B_Yellow"]
```

The list may contain up to 42 moves and shows the order the players are playing.

The first player who connects four items of the same color is the winner.

You should return "Yellow", "Red" or "Draw" accordingly.

import re
def who_is_winner(pieces_position_list):
    # Your code here!
    tempList=["".join(["*" for j in range(7)])+"\t" for i in range(6)]
    for i in pieces_position_list:
        temp=i.split("_")
        columns=ord(temp[0])-ord("A")
        sign="1" if temp[1]=="Red" else "2"
        for j in range(len(tempList)):
            if tempList[j][columns]=="*":
                tempList[j]=tempList[j][:columns]+sign+tempList[j][columns+1:]
                break
        else:
            return "Draw"
        win=GetWin("".join(tempList))
        if win!="Draw":
            print(win)
            return win
    else:
        return "Draw"
    pass

def GetWin(string):
    if re.search(r"1{4,}|1(?:.{7}1){3,}|1(?:.{8}1){3,}|1(?:.{6}1){3,}",string):
        return "Red"
    if re.search(r"2{4,}|2(?:.{7}2){3,}|2(?:.{8}2){3,}|2(?:.{6}2){3,}",string):
        return "Yellow"
    return "Draw"


Solve in Python:
# Context

According to Wikipedia : "The seventh son of a seventh son is a concept from folklore regarding special powers given to, or held by, such a son. **The seventh son must come from an unbroken line with no female siblings born between, and be, in turn, born to such a seventh son.**"

# Your task

You will be given a string of JSON, consisting of a family tree containing people's names, genders and children. Your task will be to find the seventh sons of seventh sons in the family tree, and return a __set__ of their names. If there are none, return an __empty set__.

## Tips

* Have a good look at the sample test cases.

* For a seventh son to be a seventh son, there must not be any daughters in the line leading to him. There may be daughters after him, though.

* **You may want to use the json module for this one.**

def find_seventh_sons_of_seventh_sons(jstring):
    return set(has_7_of_7_son(json.loads(jstring)))

def has_7_of_7_son(person, parent_is_7=False):
    counter = 0
    result = []
    broken = False
    if person['children']:
        for child in person['children']:
            if child['gender'] == 'male': # and
                counter += 1
            else:
                broken = True
            if counter == 7 and not broken:
                if parent_is_7:
                    result.append(child['name'])
                result.extend(has_7_of_7_son(child, True))
            result.extend(has_7_of_7_son(child, False))
    return result


Solve in Python:
# Convergents of e
The square root of 2 can be written as an infinite continued fraction.
![img](http://img0.ph.126.net/x1Hyc4iHQg0Jz2EInmT3ag==/6597639313681841979.png)
The infinite continued fraction can be written, √2 = [1;(2)], (2) indicates that 2 repeats ad infinitum. In a similar way, √23 = [4;(1,3,1,8)].

It turns out that the sequence of partial values of continued fractions for square roots provide the best rational approximations. Let us consider the convergents for √2.
![img](http://img1.ph.126.net/xme9gNBQdA7bvQkwIftznQ==/6597819633588793645.png)
Hence the sequence of the first ten convergents for √2 are:

1, 3/2, 7/5, 17/12, 41/29, 99/70, 239/169, 577/408, 1393/985, 3363/2378, …

What is most surprising is that the important mathematical constant,
e = [2; 1,2,1, 1,4,1, 1,6,1 , … , 1,2k,1, …].

The first ten terms in the sequence of convergents for e are:

2, 3, 8/3, 11/4, 19/7, 87/32, 106/39, 193/71, 1264/465, 1457/536, …

The sum of digits in the numerator of the 10th convergent is 1+4+5+7=17.

Find the sum of digits in the numerator of the mth convergent of the continued fraction for e.

- Powered by [Project Euler](https://projecteuler.net/problem=65)

def convergents_of_e(n):
    def b(n):
        return n // 3 * 2 if n % 3 == 0 else 1
    x, y = b(n), 1
    for k in range(n - 1, 0, -1):
        x, y = b(k) * x + y, x
    return sum(int(d) for d in str(x + y))


Solve in Python:
# Convert Improper Fraction to Mixed Number

You will need to convert an [improper fraction](https://www.mathplacementreview.com/arithmetic/fractions.php#improper-fractions) to a [mixed number](https://www.mathplacementreview.com/arithmetic/fractions.php#mixed-number). For example:

```python
get_mixed_num('18/11') # Should return '1 7/11'
get_mixed_num('13/5') # Should return '2 3/5'
get_mixed_num('75/10') # Should return '7 5/10'
```

NOTE: All fractions will be greater than 0.

def get_mixed_num(fraction):
    n, d = (int(num) for num in fraction.split("/"))
    i, n = divmod(n, d)
    return f"{i} {n}/{d}"


Solve in Python:
# Convert a linked list to a string

## Related Kata

Although this Kata is not part of an official Series, you may also want to try out [Parse a linked list from a string](https://www.codewars.com/kata/582c5382f000e535100001a7) if you enjoyed this Kata.

## Preloaded

Preloaded for you is a class, struct or derived data type `Node` (depending on the language) used to construct linked lists in this Kata:

```python
class Node():
    def __init__(self, data, next = None):
        self.data = data
        self.next = next
```

~~~if:objc
*NOTE: In Objective-C, the* `Node` *struct is placed on top of your main solution because there is a "double-import" bug in the Preloaded section at the time of writing (which cannot be fixed on my end).  Attempts to modify it (e.g. to cheat the tests in some way) will likely result in a test crash so it is not recommended for you to modify that section ;)*
~~~

~~~if:c
*NOTE: In C, the* `Node` *struct is placed on top of your main solution (and the [Sample] Test Cases) because the compiler complains about not recognizing the* `Node` *datatype even after adding it to the Preloaded section.  Attempts to modify it (e.g. to cheat the tests in some way) will likely result in a test crash so it is not recommended for you to modify that section ;)*
~~~

If you are attempting this Kata in NASM then note that the code example shown directly above may not be relevant; please refer to the Sample Tests (written in C) for the exact definition of the `Node` structure.

## Prerequisites

This Kata assumes that you are already familiar with the idea of a linked list.  If you do not know what that is, you may want to read up on [this article on Wikipedia](https://en.wikipedia.org/wiki/Linked_list).  Specifically, the linked lists this Kata is referring to are **singly linked lists**, where the value of a specific node is stored in its `data`/`$data`/`Data` property, the reference to the next node is stored in its `next`/`$next`/`Next`/`next_node` property and the terminator for a list is...

def stringify(node):
    if node == None:
        return 'None'
    ret = ''
    while node.data != None:
        ret += str(node.data) + ' -> '
        if not node.__next__:
            ret += 'None'
            break
        node = node.__next__
    return ret


Solve in Python:
# Convert number to reversed array of digits

Given a random non-negative number, you have to return the digits of this number within an array in reverse order.

## Example:

```
348597 => [7,9,5,8,4,3]
```

def digitize(n):
    results = []
    for x in range(len(str(n))):
        results.append(int(str(n)[len(str(n)) - x - 1]))
    return results


Solve in Python:
# Covfefe

Your are given a string. You must replace the word(s) `coverage` by `covfefe`, however, if you don't find the word `coverage` in the string, you must add `covfefe` at the end of the string with a leading space.

For the languages where the string is not immutable (such as ruby), don't modify the given string, otherwise this will break the test cases.

def covfefe(s):
    if 'coverage' in s:
        return s.replace('coverage', 'covfefe')
    else:
        return s + ' ' + 'covfefe'


Solve in Python:
# Definition

**_Balanced number_** is the number that * **_The sum of_** all digits to the **_left of the middle_** digit(s) and the sum of all digits to the **_right of the middle_** digit(s) are **_equal_***.

____

# Task

**_Given_** a number, **_Find if it is Balanced or not_** .
____

# Warm-up (Highly recommended)

# [Playing With Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
___

# Notes

* *If* the **_number has an odd number of digits_**  then **_there is only one middle digit_**,  e.g.  `92645`  has middle digit `6`;  **_otherwise_**, there are **_two middle digits_** , e.g.  `1301`  has middle digits  `3`  and  `0`

* **_The middle digit(s)_**  should  **_not_** be considered when *determining whether a number is balanced or not*, **_e.g_**  `413023`  is a **_balanced number because the left sum and right sum are both_**   `5`.

* **_Number_** *passed is always*  **_Positive_** .

* **_Return_** *the result as* **_String_**

___

# Input >> Output Examples

```
(balanced-num 7) ==> return "Balanced"
```

## **_Explanation_**:

* **_Since_** , **_The sum of_** *all digits to the* **_left of the middle_** digit (0)

* and **_the sum of_** *all digits to the* **_right of the middle_** digit (0) are **_equal_**  , **_then_** *It's* **_Balanced_**
___

```
(balanced-num 295591) ==> return "Not Balanced"
```

## **_Explanation_**:

* **_Since_** , **_The sum of_** *all digits to the* **_left of the middle_** digits (11)

* and **_the sum of_** *all digits to the* **_right of the middle_** digits (10) are **_Not equal_**  , **_then_** *It's* **_Not Balanced_**

* **_Note_** : **_The middle digit(s)_**  *are* **_55_** .

___
```
(balanced-num 959) ==> return "Balanced"
```

## **_Explanation_**:

* **_Since_** , **_The sum of_** *all digits to the* **_left of the middle_** digits (9)

* and **_the sum of_** *all digits to the* **_right of the middle_** digits (9) are **_equal_**  , **_then_** *It's* **_Balanced_**

* **_Note_** : **_The middle digit_**  *is* **_5_**...

def balanced_num(number):
  n = list(map(int,str(number)))
  l = (len(n)-1,len(n)-2)[len(n) % 2 == 0]//2
  return "Balanced" if number <=99 else ("Not Balanced","Balanced")[sum(n[:l]) == sum(n[-l:])]


Solve in Python:
# Definition

**_Disarium number_** is the number that *The sum of its digits powered with their respective positions is equal to the number itself*.

____

# Task

**_Given_** a number, **_Find if it is Disarium or not_** .
____

# Warm-up (Highly recommended)

# [Playing With Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
___

# Notes

* **_Number_** *passed is always*  **_Positive_** .
* **_Return_** *the result as* **_String_**
___

# Input >> Output Examples

```
disariumNumber(89) ==> return "Disarium !!"
```
## **_Explanation_**:

* Since , **_8^(1) + 9^(2) = 89_** , thus *output* is `"Disarium !!"`
___

```
disariumNumber(564) ==> return "Not !!"
```
## **_Explanation_**:

Since , **_5^(1) + 6^(2) + 4^(3) = 105 != 564_** ,  thus *output* is `"Not !!"`

___
___
___

# [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers)

# [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays)

# [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored)
___

## ALL translations are welcomed

## Enjoy Learning !!
# Zizou

def disarium_number(n):
    return ('Not !!','Disarium !!')[sum(int(i)**a for a,i in enumerate(str(n),1)) == n]


Solve in Python:
# Definition

**_Extra perfect number_** *is the number that* **_first_** and **_last_** *bits* are **_set bits_**.

____

# Task

**_Given_**  *a positive integer*   `N` ,  **_Return_** the **_extra perfect numbers_** *in range from*  `1`  to  `N` .
____

# Warm-up (Highly recommended)

# [Playing With Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
___

# Notes

* **_Number_** *passed is always*  **_Positive_** .

* **_Returned array/list_** should *contain the extra perfect numbers in ascending order*  **from lowest to highest**
___

# Input >> Output Examples

```
extraPerfect(3)  ==>  return {1,3}
```
## **_Explanation_**:

# (1)10 =(1)2

**First** and **last** bits as **_set bits_**.

# (3)10 = (11)2

**First** and **last** bits as **_set bits_**.
___

```
extraPerfect(7)  ==>  return {1,3,5,7}
```

## **_Explanation_**:

# (5)10 = (101)2

**First** and **last** bits as **_set bits_**.

# (7)10 = (111)2

**First** and **last** bits as **_set bits_**.
___
___
___

# [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers)

# [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays)

# [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored)
___

## ALL translations are welcomed

## Enjoy Learning !!
# Zizou

def extra_perfect(n):
    return [i for i in range(1,n+1) if bin(i)[2]=='1' and bin(i)[-1]=='1']