Solve in Python:
In a forest, each rabbit has some color. Some subset of rabbits (possibly all of them) tell you how many other rabbits have the same color as them. Those answers are placed in an array.

Return the minimum number of rabbits that could be in the forest.

Examples:
Input: answers = [1, 1, 2]
Output: 5
Explanation:
The two rabbits that answered "1" could both be the same color, say red.
The rabbit than answered "2" can't be red or the answers would be inconsistent.
Say the rabbit that answered "2" was blue.
Then there should be 2 other blue rabbits in the forest that didn't answer into the array.
The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.

Input: answers = [10, 10, 10]
Output: 11

Input: answers = []
Output: 0

Note:

       answers will have length at most 1000.
       Each answers[i] will be an integer in the range [0, 999].

class Solution:
     def basicCalculatorIV(self, expression, evalvars, evalints):
         """
         :type expression: str
         :type evalvars: List[str]
         :type evalints: List[int]
         :rtype: List[str]
         """
         class C(collections.Counter):
             def __add__(self, other):
                 self.update(other)
                 return self
             def __sub__(self, other):
                 self.subtract(other)
                 return self
             def __mul__(self, other):
                 product = C()
                 for x in self:
                     for y in other:
                         xy = tuple(sorted(x + y))
                         product[xy] += self[x] * other[y]
                 return product
         vals = dict(zip(evalvars, evalints))
         def f(s):
             s = str(vals.get(s, s))
             return C({(s,): 1}) if s.isalpha() else C({(): int(s)})
         c = eval(re.sub('(\w+)', r'f("\1")', expression))
         return ['*'.join((str(c[x]),) + x)
                 for x in sorted(c, key=lambda x: (-len(x), x))
                 if c[x]]


Solve in Python:
In a given 2D binary array A, there are two islands.  (An island is a 4-directionally connected group of 1s not connected to any other 1s.)
Now, we may change 0s to 1s so as to connect the two islands together to form 1 island.
Return the smallest number of 0s that must be flipped.  (It is guaranteed that the answer is at least 1.)

Example 1:
Input: A = [[0,1],[1,0]]
Output: 1
Example 2:
Input: A = [[0,1,0],[0,0,0],[0,0,1]]
Output: 2
Example 3:
Input: A = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]
Output: 1

Constraints:

2 <= A.length == A[0].length <= 100
A[i][j] == 0 or A[i][j] == 1

class Solution:
    def shortestBridge(self, A: List[List[int]]) -> int:

        count=0
        borders = collections.defaultdict(list)
        seen = set()
        x,y = [1,-1,0,0], [0,0,1,-1]
        m,n = len(A), len(A[0])
        for i in range(m):
            for j in range(n):
                if A[i][j] == 1 and (i,j) not in seen:
                    frontier = [(i,j)]
                    island = {(i,j)}
                    while frontier:
                        cur = frontier.pop()
                        bord = False
                        for k in range(len(x)):
                            r,c = cur[0]+x[k], cur[1]+y[k]
                            if 0<=r<m and 0<=c<n:
                                if A[r][c]==1 and (r,c) not in island:
                                    frontier.append((r,c))
                                    island.add((r,c))
                                elif A[r][c]==0: borders[count+1].append(cur)

                    count+=1
                    seen.update(island)
                if count==2: break
            if count==2: break

        ans = float('inf')
        borders

        for i,j in borders[1]:
            for x,y in borders[2]:
                ans = min(ans, abs(i-x)+abs(j-y)-1)

        return ans


Solve in Python:
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.

Note:

The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000].

from fractions import Fraction
class Solution:
    def splitArraySameAverage(self, A: List[int]) -> bool:
        if len(A) == 1: return False
        avg = Fraction(sum(A), len(A))
        A = [num - avg for num in A]
        left = set()
        for i in range(len(A) // 2):
            curr_set = {s + A[i] for s in left}
            left = left | curr_set | {A[i]}
        if 0 in left: return True
        rsum = sum(A[i] for i in range(len(A) // 2, len(A)))
        right = set()
        for i in range(len(A) // 2, len(A)):
            if A[i] == 0: return True
            curr_set = {A[i]}
            for s in right:
                if s + A[i] == 0 or (- s - A[i] in left and s + A[i] != rsum):
                    return True
                curr_set.add(s + A[i])
            right = right | curr_set
        return False


Solve in Python:
In a gold mine grid of size m * n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty.
Return the maximum amount of gold you can collect under the conditions:

Every time you are located in a cell you will collect all the gold in that cell.
From your position you can walk one step to the left, right, up or down.
You can't visit the same cell more than once.
Never visit a cell with 0 gold.
You can start and stop collecting gold from any position in the grid that has some gold.

Example 1:
Input: grid = [[0,6,0],[5,8,7],[0,9,0]]
Output: 24
Explanation:
[[0,6,0],
 [5,8,7],
 [0,9,0]]
Path to get the maximum gold, 9 -> 8 -> 7.

Example 2:
Input: grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]]
Output: 28
Explanation:
[[1,0,7],
 [2,0,6],
 [3,4,5],
 [0,3,0],
 [9,0,20]]
Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7.

Constraints:

1 <= grid.length, grid[i].length <= 15
0 <= grid[i][j] <= 100
There are at most 25 cells containing gold.

class Solution:
    def getMaximumGold(self, grid: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])
        def dfs(r, c, total, vis):
            nonlocal maxx
            if r < 0 or r >= m or c < 0 or c >= n or grid[r][c] == 0 or (r,c) in vis:
                return
            total += grid[r][c]
            maxx = max(total, maxx)
            dfs(r+1, c, total, vis + [(r,c)])
            dfs(r-1, c, total, vis + [(r,c)])
            dfs(r, c+1, total, vis + [(r,c)])
            dfs(r, c-1, total, vis + [(r,c)])

        grt = 0
        for i in range(m):
            for j in range(n):
                if grid[i][j] != 0:
                    maxx = 0
                    dfs(i, j, 0, [])
                    grt = max(grt, maxx)
        return grt


Solve in Python:
In a list of songs, the i-th song has a duration of time[i] seconds.
Return the number of pairs of songs for which their total duration in seconds is divisible by 60.  Formally, we want the number of indices i, j such that i < j with (time[i] + time[j]) % 60 == 0.

Example 1:
Input: [30,20,150,100,40]
Output: 3
Explanation: Three pairs have a total duration divisible by 60:
(time[0] = 30, time[2] = 150): total duration 180
(time[1] = 20, time[3] = 100): total duration 120
(time[1] = 20, time[4] = 40): total duration 60

Example 2:
Input: [60,60,60]
Output: 3
Explanation: All three pairs have a total duration of 120, which is divisible by 60.

Note:

1 <= time.length <= 60000
1 <= time[i] <= 500

from collections import Counter
class Solution:
    def numPairsDivisibleBy60(self, time: List[int]) -> int:
        count = Counter(time)
        pair = 0
        for p in count :
            tp = count[p]
            t = 60 - p % 60
            while t <= 500 :
                pair += tp*count[t] if t != p else tp * (tp-1)
                t += 60

        return pair // 2


Solve in Python:
In a network of nodes, each node i is directly connected to another node j if and only if graph[i][j] = 1.
Some nodes initial are initially infected by malware.  Whenever two nodes are directly connected and at least one of those two nodes is infected by malware, both nodes will be infected by malware.  This spread of malware will continue until no more nodes can be infected in this manner.
Suppose M(initial) is the final number of nodes infected with malware in the entire network, after the spread of malware stops.
We will remove one node from the initial list.  Return the node that if removed, would minimize M(initial).  If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index.
Note that if a node was removed from the initial list of infected nodes, it may still be infected later as a result of the malware spread.

Example 1:
Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
Output: 0

Example 2:
Input: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]
Output: 0

Example 3:
Input: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]
Output: 1

Note:

1 < graph.length = graph[0].length <= 300
0 <= graph[i][j] == graph[j][i] <= 1
graph[i][i] == 1
1 <= initial.length <= graph.length
0 <= initial[i] < graph.length

class Solution(object):
    def minMalwareSpread(self, graph, initial):
        def dfs(node, visited):
            for neighbor in range(len(graph[node])):
                if graph[node][neighbor] == 1 and neighbor not in visited:
                    visited.add(neighbor)
                    dfs(neighbor, visited)

        res, max_size = min(initial), 0
        i_set = set(initial)
        total_visited = set()
        for node in range(len(graph)):
            if node not in total_visited:
                visited = {node}
                dfs(node, visited)
                infected = visited & i_set
                if len(infected) == 1:
                    if len(visited) > max_size or (len(visited) == max_size and list(infected)[0] < res):
                        res = list(infected)[0]
                        max_size = len(visited)
                total_visited |= visited
        return res


Solve in Python:
In a project, you have a list of required skills req_skills, and a list of people.  The i-th person people[i] contains a list of skills that person has.
Consider a sufficient team: a set of people such that for every required skill in req_skills, there is at least one person in the team who has that skill.  We can represent these teams by the index of each person: for example, team = [0, 1, 3] represents the people with skills people[0], people[1], and people[3].
Return any sufficient team of the smallest possible size, represented by the index of each person.
You may return the answer in any order.  It is guaranteed an answer exists.

Example 1:
Input: req_skills = ["java","nodejs","reactjs"], people = [["java"],["nodejs"],["nodejs","reactjs"]]
Output: [0,2]
Example 2:
Input: req_skills = ["algorithms","math","java","reactjs","csharp","aws"], people = [["algorithms","math","java"],["algorithms","math","reactjs"],["java","csharp","aws"],["reactjs","csharp"],["csharp","math"],["aws","java"]]
Output: [1,2]

Constraints:

1 <= req_skills.length <= 16
1 <= people.length <= 60
1 <= people[i].length, req_skills[i].length, people[i][j].length <= 16
Elements of req_skills and people[i] are (respectively) distinct.
req_skills[i][j], people[i][j][k] are lowercase English letters.
Every skill in people[i] is a skill in req_skills.
It is guaranteed a sufficient team exists.

from functools import lru_cache

class Solution:
    def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:
        ids = {}
        sid = 0
        skills = 0
        for skill in req_skills:
            ids[skill] = sid
            skills = skills | (1 << sid)
            # print(sid, 1 << sid)
            sid += 1

        # print(ids)
        # print(skills)

        n = len(people)

        @lru_cache(None)
        def dp(i, left):
            if left == 0:
                return []
            if i == n:
                return None

            a = dp(i + 1, left)

            for s in people[i]:
                if s in ids:
                    j = ids[s]
                    left = (left & ~(1 << j))

            b = dp(i + 1, left)

            if a is not None and b is not None:
                if len(a) < len(b) + 1:
                    return a
                else:
                    return [i] + b

            if a is None and b is None:
                return None

            return ([i] + b) if a is None else a

        return dp(0, skills)


Solve in Python:
In a regular table tennis match, the player who serves changes every time after 2 points are scored, regardless of which players scored them.
Chef and Cook are playing a different match — they decided that the player who serves would change every time after $K$ points are scored instead (again regardless of which players scored them). When the game starts, it's Chef's turn to serve.
You are given the current number of points scored by Chef and Cook ($P_1$ and $P_2$ respectively). Find out whether Chef or Cook has to serve next.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains three space-separated integers $P_1$, $P_2$ and $K$.

-----Output-----
For each test case, print a single line containing the string "CHEF" if it is Chef's turn or "COOK" if it is Cook's turn.

-----Constraints-----
- $1 \le T \le 10^5$
- $1 \le K \le 10^{9}$
- $0 \le P_1, P_2 \le 10^{9}$

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

-----Example Input-----
3
1 3 2
0 3 2
34 55 2

-----Example Output-----
CHEF
COOK
CHEF

-----Explanation-----
Example case 1: Chef serves for the first two points, Cook serves for the next two, so Chef has to serve again now.

for _ in range(int(input())):
 a,b,k=map(int,input().split())
 c=a+b
 d=c//k
 if d%2==0:
  print('CHEF')
 elif d%2!=0:
  print('COOK')


Solve in Python:
In a row of trees, the i-th tree produces fruit with type tree[i].
You start at any tree of your choice, then repeatedly perform the following steps:

Add one piece of fruit from this tree to your baskets.  If you cannot, stop.
Move to the next tree to the right of the current tree.  If there is no tree to the right, stop.

Note that you do not have any choice after the initial choice of starting tree: you must perform step 1, then step 2, then back to step 1, then step 2, and so on until you stop.
You have two baskets, and each basket can carry any quantity of fruit, but you want each basket to only carry one type of fruit each.
What is the total amount of fruit you can collect with this procedure?

Example 1:
Input: [1,2,1]
Output: 3
Explanation: We can collect [1,2,1].

Example 2:
Input: [0,1,2,2]
Output: 3
Explanation: We can collect [1,2,2].
If we started at the first tree, we would only collect [0, 1].

Example 3:
Input: [1,2,3,2,2]
Output: 4
Explanation: We can collect [2,3,2,2].
If we started at the first tree, we would only collect [1, 2].

Example 4:
Input: [3,3,3,1,2,1,1,2,3,3,4]
Output: 5
Explanation: We can collect [1,2,1,1,2].
If we started at the first tree or the eighth tree, we would only collect 4 fruits.

Note:

1 <= tree.length <= 40000
0 <= tree[i] < tree.length

class Solution:
    def totalFruit(self, tree: List[int]) -> int:
        count = collections.Counter()
        i = ans = 0

        for j in range(len(tree)):
            fruit = tree[j]
            count[fruit] += 1

            while len(count.keys()) > 2:
                count[tree[i]] -= 1
                if count[tree[i]] == 0:
                    del count[tree[i]]
                i += 1

            ans = max(ans, j-i+1)

        return ans


Solve in Python:
In a small town the population is `p0 = 1000` at the beginning of a year. The population
regularly increases by `2 percent` per year and moreover `50` new inhabitants per year
come to live in the town.
How many years does the town need to see its population
greater or equal to `p = 1200` inhabitants?

```
At the end of the first year there will be:
1000 + 1000 * 0.02 + 50 => 1070 inhabitants

At the end of the 2nd year there will be:
1070 + 1070 * 0.02 + 50 => 1141 inhabitants (number of inhabitants is an integer)

At the end of the 3rd year there will be:
1141 + 1141 * 0.02 + 50 => 1213

It will need 3 entire years.
```
More generally given parameters:

`p0, percent, aug (inhabitants coming or leaving each year), p (population to surpass)`

the function `nb_year` should return `n` number of entire years needed to
get a population greater or equal to `p`.

aug is an integer, percent a positive or null number, p0 and p are positive integers (> 0)
```
Examples:
nb_year(1500, 5, 100, 5000) -> 15
nb_year(1500000, 2.5, 10000, 2000000) -> 10
```

Note: Don't forget to convert the percent parameter as a percentage in the body of your function: if the parameter percent is 2 you have to convert it to 0.02.

def nb_year(p0, percent, aug, p):
    n = p0 + p0* (percent/100) + aug
    nb= 1
    while n < p:
        n = n + n*(percent/100) + aug
        nb += 1
    return(nb)


Solve in Python:
In a special ranking system, each voter gives a rank from highest to lowest to all teams participated in the competition.
The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter.
Given an array of strings votes which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above.
Return a string of all teams sorted by the ranking system.

Example 1:
Input: votes = ["ABC","ACB","ABC","ACB","ACB"]
Output: "ACB"
Explanation: Team A was ranked first place by 5 voters. No other team was voted as first place so team A is the first team.
Team B was ranked second by 2 voters and was ranked third by 3 voters.
Team C was ranked second by 3 voters and was ranked third by 2 voters.
As most of the voters ranked C second, team C is the second team and team B is the third.

Example 2:
Input: votes = ["WXYZ","XYZW"]
Output: "XWYZ"
Explanation: X is the winner due to tie-breaking rule. X has same votes as W for the first position but X has one vote as second position while W doesn't have any votes as second position.

Example 3:
Input: votes = ["ZMNAGUEDSJYLBOPHRQICWFXTVK"]
Output: "ZMNAGUEDSJYLBOPHRQICWFXTVK"
Explanation: Only one voter so his votes are used for the ranking.

Example 4:
Input: votes = ["BCA","CAB","CBA","ABC","ACB","BAC"]
Output: "ABC"
Explanation:
Team A was ranked first by 2 voters, second by 2 voters and third by 2 voters.
Team B was ranked first by 2 voters, second by 2 voters and third by 2 voters.
Team C was ranked first by 2 voters, second by 2 voters and third by 2 voters.
There is a tie and we rank teams ascending by their IDs.

Example 5:
Input: votes = ["M","M","M","M"]
Output: "M"
Explanation: Only team M in the competition...

class Solution:
    def rankTeams(self, votes: List[str]) -> str:
        N = len(votes[0])
        mapping = collections.defaultdict(lambda :[0 for _ in range(N)])
        for v in votes:
            for i, char in enumerate(v):
                mapping[char][i] += 1
        return ''.join([candidate for candidate, _ in sorted(mapping.items(), key = lambda x:(x[1], -ord(x[0])), reverse = True)])


Solve in Python:
In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", a move consists of either replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR". Given the starting string start and the ending string end, return True if and only if there exists a sequence of moves to transform one string to the other.

Example:

Input: start = "RXXLRXRXL", end = "XRLXXRRLX"
Output: True
Explanation:
We can transform start to end following these steps:
RXXLRXRXL ->
XRXLRXRXL ->
XRLXRXRXL ->
XRLXXRRXL ->
XRLXXRRLX

Note:

       1 <= len(start) = len(end) <= 10000.
       Both start and end will only consist of characters in {'L', 'R', 'X'}.

class Solution:
     def isToeplitzMatrix(self, matrix):
         """
         :type matrix: List[List[int]]
         :rtype: bool
         """

         x, y = len(matrix[0]), len(matrix)

         for i in range(x - 1):
             for j in range(y - 1):
                 if matrix[j][i] != matrix[j+1][i+1]:
                     return False
         return True


Solve in Python:
In a warehouse, there is a row of barcodes, where the i-th barcode is barcodes[i].
Rearrange the barcodes so that no two adjacent barcodes are equal.  You may return any answer, and it is guaranteed an answer exists.

Example 1:
Input: [1,1,1,2,2,2]
Output: [2,1,2,1,2,1]

Example 2:
Input: [1,1,1,1,2,2,3,3]
Output: [1,3,1,3,2,1,2,1]

Note:

1 <= barcodes.length <= 10000
1 <= barcodes[i] <= 10000

from collections import Counter
class Solution:
    def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:
        if barcodes is None or len(barcodes) == 0:
            return []
        if len(barcodes) == 1:
            return barcodes

        counter = Counter(barcodes)
        num_occurrences = sorted(counter, key = lambda x: counter.get(x), reverse=True)
        elements = dict()

        for elem in num_occurrences:
            elements[elem] = counter[elem]

        output = [None] * len(barcodes)
        item_index = 0
        index = 0
        value = num_occurrences[0]
        value_index= 0
        for i in range(len(barcodes)):
            while output[index] is not None or output[index - 1] == value:
                index += 1
                index %= len(barcodes)
            output[index] = value
            item_index += 1
            index += 1
            index %= len(barcodes)
            if elements[value] == 1:
                value_index += 1
                if value_index >= len(num_occurrences):
                    return output
                value = num_occurrences[value_index]
            else:
                elements[value] -= 1

        return output


Solve in Python:
In africa jungle , there were zebra's who liked to spit.
There owner watched them for whole day and noted in his sheet where each zebra spitted.
Now he's in a confusion and wants to know if in the jungle there are two zebra's which spitted at each other.
Help him solve this task.
If the zebra is present in position a spits b metres right , he can hit only zebra in position a+b , if such a zebra exists.

-----Input:-----
- The first line contains integer t(1<=t<100)- amount of zebras in jungle.
- Each of following t lines contains two integers a(i) and b(i)(-10^4<=x(i)<=10^4,1<|d(i)|<=2.10^4) - records in owner sheet.
- a(i) is the position of i-th zebra and b(i) is distance at which the i-th camel spitted.
Positive values of d(i) correspond to spits right, negative values correspond to spit left.No two zebras may stand in the same position.

-----Output:-----
If there are two zebras , which spitted at each other , output YES, otherwise , output NO.

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

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

# cook your dish here
t=int(input())
a=list()
for _ in range(t):
    a.append(list(map(int,input().split())))
count=0
for i in range(t):
    for j in range(i+1,t):
        if a[i][1]+a[j][1]==0:
            count+=1
            print('YES')
            break
    if count!=0:
        break
if count==0:
    print("NO")


Solve in Python:
In an alien language, surprisingly they also use english lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters.
Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographicaly in this alien language.

Example 1:
Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
Output: true
Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted.

Example 2:
Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"
Output: false
Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.

Example 3:
Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"
Output: false
Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info).

Constraints:

1 <= words.length <= 100
1 <= words[i].length <= 20
order.length == 26
All characters in words[i] and order are English lowercase letters.

class Solution:
    def isAlienSorted(self, words: List[str], order: str) -> bool:
        d = {c: i for i, c in enumerate(order)}
        def compare(w1, w2):
            for i in range(min(len(w1), len(w2))):
                if d[w1[i]] < d[w2[i]]:
                    return True
                if d[w1[i]] > d[w2[i]]:
                    return False
            return len(w1) <= len(w2)

        for i in range(len(words) - 1):
            if not compare(words[i], words[i+1]):
                return False

        return True


Solve in Python:
In an array A containing only 0s and 1s, a K-bit flip consists of choosing a (contiguous) subarray of length K and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0.
Return the minimum number of K-bit flips required so that there is no 0 in the array.  If it is not possible, return -1.

Example 1:
Input: A = [0,1,0], K = 1
Output: 2
Explanation: Flip A[0], then flip A[2].

Example 2:
Input: A = [1,1,0], K = 2
Output: -1
Explanation: No matter how we flip subarrays of size 2, we can't make the array become [1,1,1].

Example 3:
Input: A = [0,0,0,1,0,1,1,0], K = 3
Output: 3
Explanation:
Flip A[0],A[1],A[2]: A becomes [1,1,1,1,0,1,1,0]
Flip A[4],A[5],A[6]: A becomes [1,1,1,1,1,0,0,0]
Flip A[5],A[6],A[7]: A becomes [1,1,1,1,1,1,1,1]

Note:

1 <= A.length <= 30000
1 <= K <= A.length

class Solution:
    def minKBitFlips(self, A: List[int], k: int) -> int:
        n = len(A)
        count = [0] * n
        ps = 0
        res = 0

        for i in range(n-k+1):
            flip = ps + A[i]
            if flip % 2 == 0:
                count[i] = 1
                res += 1
                ps += 1

            if i - k + 1 >= 0:
                ps -= count[i-k+1]

        for i in range(n-k+1, n):
            if (ps + A[i]) % 2 == 0:
                return -1
            ps -= count[i-k+1]

        return res


Solve in Python:
In an array A of 0s and 1s, how many non-empty subarrays have sum S?

Example 1:
Input: A = [1,0,1,0,1], S = 2
Output: 4
Explanation:
The 4 subarrays are bolded below:
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]

Note:

A.length <= 30000
0 <= S <= A.length
A[i] is either 0 or 1.

class Solution:
    def numSubarraysWithSum(self, A: List[int], S: int) -> int:
        n = len(A)
        prefix = [0 for _ in range(n+1)]
        for i in range(n):
            prefix[i+1] = prefix[i] + A[i]

        def at_most_k(k: int) -> int:
            begin, end = 0, 1
            cnt = 0
            while end < n+1:
                while begin < end and prefix[end] - prefix[begin] > k:
                    begin += 1
                cnt += end - begin
                end += 1
            return cnt

        return at_most_k(S) - at_most_k(S-1)


Solve in Python:
In an array, a $block$ is a maximal sequence of identical elements. Since blocks are maximal, adjacent blocks have distinct elements, so the array breaks up into a series of blocks.  For example, given the array $[3, 3, 2, 2, 2, 1, 5, 8, 4, 4]$, there are 6 blocks: $[3, 3], [2, 2, 2], [1], [5], [8], [4, 4]$ .
In this task, you are given two arrays, $A$ (of length $n$), and $B$ (of length $m$), and a number $K$. You have to interleave $A$ and $B$ to form an array $C$ such that $C$ has $K$ blocks. Each way of interleaving $A$ and $B$ can be represented as a $0-1$ array $X$ of length $n+m$ in which $X[j]$ is $0$ if $C[j]$ came from $A$ and $X[j]$ is $1$ if $C[j]$ came from $B$.
A formal description of the interleaving process is given at the end.
For example, if $A = [1, 3]$ and $B = [3, 4]$, there are $6$ ways of interleaving $A$ and $B$.  With each interleaving $X$ of $A$ and $B$, we also count the number of blocks in the resulting interleaved array $C$.  The descriptions of the interleavings, $X$, and the outcomes, $C$, are given below.
- $X = [0, 0, 1, 1]$, which corresponds to $C = [1, 3, 3, 4]$, $3$ blocks.
- $X = [0, 1, 0, 1]$, which corresponds to $C = [1, 3, 3, 4]$, $3$ blocks.
- $X = [0, 1, 1, 0]$, which corresponds to $C = [1, 3, 4, 3]$ , $4$ blocks.
- $X = [1, 0, 0, 1]$, which corresponds to $C = [3, 1, 3, 4]$, $4$ blocks.
- $X = [1, 0, 1, 0]$, which corresponds to $C = [3, 1, 4, 3]$, $4$ blocks.
- $X = [1, 1, 0, 0]$, which corresponds to $C = [3, 4, 1, 3]$, $4$ blocks.
Observe that different interleavings $X$ may produce the same array $C$, such as the first two interleavings in the example above.
Your task is the following.  Given arrays $A$ and $B$ and a number $K$, find the number of different interleavings $X$ of $A$ and $B$ that produce an output array $C$ with exactly $K$ blocks.  Note that we are counting the number of interleavings, not the number of different output arrays after interleaving.  For instance, if the same output array C is produced via 2 different interleavings, it gets...

# cook your dish here
mod = 10 ** 8 + 7

def dic_add(dic, k1, v):
 if k1 <= k:
  if k1 in dic:
   dic[k1] = (dic[k1]+v) % mod
  else:
   dic[k1] = v

for _ in range(int(input())):
 n, m, k = list(map(int, input().split()))
 a_l = list(map(int, input().split()))
 b_l = list(map(int, input().split()))

 # 0: m end, 1: n end
 f_dp = [[[{} for _ in range(n+1)] for _ in range(m+1)] for _ in range(2)]

 f_dp[0][1][0] = {1: 1}
 f_dp[1][0][1] = {1: 1}
 dif = 1
 for j in range(1, m):
  if b_l[j] != b_l[j - 1]:
   dif += 1
  f_dp[0][j+1][0] = {dif: 1}

 dif = 1
 for i in range(1, n):
  if a_l[i] != a_l[i - 1]:
   dif += 1
  f_dp[1][0][i+1] = {dif: 1}

 for i in range(1, n + 1):
  for j in range(1, m + 1):
   # m end
   if j -2 >= 0 and b_l[j-1] != b_l[j - 2]:
    addi = 1
   else:
    addi = 0
   for kk, vv in list(f_dp[0][j - 1][i].items()):
    dic_add(f_dp[0][j][i], kk + addi, vv)

   if b_l[j-1] != a_l[i-1]:
    addi = 1
   else:
    addi = 0
   for kk, vv in list(f_dp[1][j-1][i].items()):
    dic_add(f_dp[0][j][i], kk + addi, vv)

   # n end
   if i -2 >= 0 and a_l[i-1] != a_l[i - 2]:
    addi = 1
   else:
    addi = 0
   for kk, vv in list(f_dp[1][j][i-1].items()):
    dic_add(f_dp[1][j][i], kk + addi, vv)

   if b_l[j-1] != a_l[i-1]:
    addi = 1
   else:
    addi = 0
   for kk, vv in list(f_dp[0][j][i-1].items()):
    dic_add(f_dp[1][j][i], kk + addi, vv)

 ans = 0
 if k in f_dp[0][m][n]:
  ans += f_dp[0][m][n][k]
 if k in f_dp[1][m][n]:
  ans += f_dp[1][m][n][k]
 print(ans%mod)


Solve in Python:
In an infinite array with two rows, the numbers in the top row are denoted

`. . . , A[−2], A[−1], A[0], A[1], A[2], . . .`

and the numbers in the bottom row are denoted

`. . . , B[−2], B[−1], B[0], B[1], B[2], . . .`

For each integer `k`, the entry `A[k]` is directly above
the entry `B[k]` in the array, as shown:

...|A[-2]|A[-1]|A[0]|A[1]|A[2]|...
...|B[-2]|B[-1]|B[0]|B[1]|B[2]|...

For each integer `k`, `A[k]` is the average of the entry to its left, the entry to its right,
and the entry below it; similarly, each entry `B[k]` is the average of the entry to its
left, the entry to its right, and the entry above it.

Given `A[0], A[1], A[2] and A[3]`, determine the value of `A[n]`. (Where range of n is -1000 Inputs and Outputs in BigInt!**

Adapted from 2018 Euclid Mathematics Contest.
https://www.cemc.uwaterloo.ca/contests/past_contests/2018/2018EuclidContest.pdf


Solve in Python:
In an infinite binary tree where every node has two children, the nodes are labelled in row order.
In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left.

Given the label of a node in this tree, return the labels in the path from the root of the tree to the node with that label.

Example 1:
Input: label = 14
Output: [1,3,4,14]

Example 2:
Input: label = 26
Output: [1,2,6,10,26]

Constraints:

1 <= label <= 10^6

class Solution:
    def pathInZigZagTree(self, label: int) -> List[int]:
        x=bin(label)[2:]
        n = len(x)
        #invert path
        y=\"1\"
        for i in range(1, n): y += \"0\" if x[i] == \"1\" else \"1\"
        #Follow path in odd even fashion
        out = []
        for i in range(n):
            if n%2 == 0:
                if i % 2 == 1: out.append(int(x[:i+1], 2))
                else: out.append(int(y[:i+1], 2))
            else:
                if i % 2 == 0: out.append(int(x[:i+1], 2))
                else: out.append(int(y[:i+1], 2))
        return out


Solve in Python:
In another Kata I came across a weird `sort` function to implement. We had to sort characters as usual ( 'A' before 'Z' and 'Z' before 'a' ) except that the `numbers` had to be sorted **after** the `letters` ( '0' after 'z') !!!

(After a couple of hours trying to solve this unusual-sorting-kata I discovered final tests used **usual** sort (digits  **before** letters :-)

So, the `unusualSort/unusual_sort` function you'll have to code will sort `letters` as usual, but will put `digits` (or one-digit-long `numbers` ) **after** `letters`.

## Examples
```python
unusual_sort(["a","z","b"])  # -> ["a","b","z"]  as usual
unusual_sort(["a","Z","B"])  # -> ["B","Z","a"]  as usual

//... but ...
unusual_sort(["1","z","a"])  # -> ["a","z","1"]
unusual_sort(["1","Z","a"])  # -> ["Z","a","1"]
unusual_sort([3,2,1"a","z","b"])  # -> ["a","b","z",1,2,3]
unusual_sort([3,"2",1,"a","c","b"])  # -> ["a","b","c",1,"2",3]
```
**Note**: `digits` will be sorted **after** "`same-digit-numbers`", eg: `1` is before `"1"`, `"2"` after `2`.
```python
unusual_sort([3,"2",1,"1","3",2])  # -> [1,"1",2,"2",3,"3"]
```

You may assume that **argument** will always be an `array/list` of **characters** or **one-digit-long numbers**.

def unusual_sort(array):
    _isdigit = lambda d : type(d) == int or (type(d) == str and d.isdigit())
    digits = [d for d in array if _isdigit(d)]
    nondigits = [n for n in array if not _isdigit(n)]

    digits.sort(key=lambda d:int(d) if type(d) == str else d - 0.1)
    nondigits.sort()

    return nondigits + digits


Solve in Python:
In an n*n grid, there is a snake that spans 2 cells and starts moving from the top left corner at (0, 0) and (0, 1). The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at (n-1, n-2) and (n-1, n-1).
In one move the snake can:

Move one cell to the right if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.
Move down one cell if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.
Rotate clockwise if it's in a horizontal position and the two cells under it are both empty. In that case the snake moves from (r, c) and (r, c+1) to (r, c) and (r+1, c).

Rotate counterclockwise if it's in a vertical position and the two cells to its right are both empty. In that case the snake moves from (r, c) and (r+1, c) to (r, c) and (r, c+1).

Return the minimum number of moves to reach the target.
If there is no way to reach the target, return -1.

Example 1:

Input: grid = [[0,0,0,0,0,1],
               [1,1,0,0,1,0],
               [0,0,0,0,1,1],
               [0,0,1,0,1,0],
               [0,1,1,0,0,0],
               [0,1,1,0,0,0]]
Output: 11
Explanation:
One possible solution is [right, right, rotate clockwise, right, down, down, down, down, rotate counterclockwise, right, down].

Example 2:
Input: grid = [[0,0,1,1,1,1],
               [0,0,0,0,1,1],
               [1,1,0,0,0,1],
               [1,1,1,0,0,1],
               [1,1,1,0,0,1],
               [1,1,1,0,0,0]]
Output: 9

Constraints:

2 <= n <= 100
0 <= grid[i][j] <= 1
It is guaranteed that the snake starts at empty cells.

class Solution:

    def minimumMoves(self, grid: List[List[int]]) -> int:
        visited = set()
        queue = deque()
        n = len(grid)
        queue.append((0, 0, 0, 1))
        visited.add(queue[0])
        res = 0
        target = (n-1, n-2, n-1, n-1)
        while queue:
            size = len(queue)
            for _ in range(size):
                curr = queue.popleft()
                if curr == target:
                    return res
                horizontal = curr[0] == curr[2]

                moves = []

                if curr[3] < n - 1 and grid[curr[0]][curr[1] + 1] == 0 and grid[curr[2]][curr[3] + 1] == 0:
                    moves.append((curr[0], curr[1] + 1, curr[2], curr[3] + 1))
                if curr[2] < n - 1 and grid[curr[0] + 1][curr[1]] == 0 and grid[curr[2] + 1][curr[3]] == 0:
                    moves.append((curr[0] + 1, curr[1], curr[2] + 1, curr[3]))
                if horizontal and curr[2] < n - 1 and grid[curr[0] + 1][curr[1]] == 0 and grid[curr[2] + 1][curr[3]] == 0:
                    moves.append((curr[0], curr[1], curr[0] + 1, curr[1]))
                if not horizontal and curr[3] < n - 1 and grid[curr[0]][curr[1] + 1] == 0 and grid[curr[2]][curr[3] + 1] == 0:
                    moves.append((curr[0], curr[1], curr[0], curr[1] + 1))

                for move in moves:
                    if move not in visited:
                        visited.add(move)
                        queue.append(move)
            res += 1
        return -1


Solve in Python:
In case you might be unlucky enough not to know the best dark fantasy franchise ever, Berserk tells the story of a man that, hating gratuitous violence, decided to become a mercenary (thus one who sells violence, no gratuity anymore!) and starts an epic struggle against apparently unsormountable odds, unsure if he really wants to pursue a path of vengeance or to try to focus on his remaining and new loved ones.

*The main character, Gatsu,ready to start yet another Tuesday*

Ok, the first part was a joke, but you can read more about the tale of the main character, a "Byronic hero" for wikipedia, in other pages like [here](https://en.wikipedia.org/wiki/Berserk_(manga%29).

After an insanely long waiting, finally fans got the [follow up](https://en.wikipedia.org/wiki/Berserk_(2016_TV_series%29) of [the acclaimed 90s show](https://en.wikipedia.org/wiki/Berserk_(1997_TV_series%29).

Regrettably, while the first adaption was considerably shortened, the latter was quite butchered, missing entire parts, like the "lost children" arc, but that would have actual children butchered and thus you might get why it was decided to skip it. And fan could somehow cope with it, if it was not for the very meager use of CG (Computer Graphic).

Luckily, I am a simple man and every time Gatsu swings his humongous sword, that is enough to make me forget about everything else.

Your goal is to build a Berserk Rater function that takes an array/list of events of each episode (as strings) and calculate a rating based on that: you start with a score of 0 (hey, it's a work from Miura-sensei, I have great expectations to satisfy!) and you have to:

* subtract 2 each time "CG" is mentioned (case insensitive);
* add 5 every time "Clang" is mentioned (case insensitive);
* if a sentence has both "Clang" and "CG", "Clang" wins (add 5);
* remove 1 every time neither is mentioned (I get bored easily, you know, particularly if you remove important parts and keep side character whining for half an episode).

You should then return a string,...

berserk_rater = lambda x: (lambda x: "worstest episode ever" if x < 0 else "bestest episode ever" if x > 10 else str(x))(sum(map(lambda x: (lambda x: 5 if "clang" in x else -2 if "cg" in x else -1)(x.lower()), x)))


Solve in Python:
In computer science and discrete mathematics, an [inversion](https://en.wikipedia.org/wiki/Inversion_%28discrete_mathematics%29) is a pair of places in a sequence where the elements in these places are out of their natural order. So, if we use ascending order for a group of numbers, then an inversion is when larger numbers appear before lower number in a sequence.

Check out this example sequence: ```(1, 2, 5, 3, 4, 7, 6)``` and we can see here three inversions
```5``` and ```3```; ```5``` and ```4```; ```7``` and ```6```.

You are given a sequence of numbers and you should count the number of inversions in this sequence.

```Input```: A sequence as a tuple of integers.

```Output```: The inversion number as an integer.

Example:
```python
  count_inversion((1, 2, 5, 3, 4, 7, 6)) == 3
  count_inversion((0, 1, 2, 3)) == 0
```

def count_inversion(sequence):
    """
        Count inversions in a sequence of numbers
    """
    count = 0
    for i, x in enumerate(sequence):
        for y in sequence[i+1:]:
            if x > y: count += 1
    return count


Solve in Python:
In computer science, cycle detection is the algorithmic problem of finding a cycle in a sequence of iterated function values.

For any function ƒ, and any initial value x0 in S, the sequence of iterated function values

    x0,x1=f(x0), x2=f(x1), ...,xi=f(x{i-1}),...

may eventually use the same value twice under some assumptions: S finite, f periodic ... etc. So there will be some `i ≠ j` such that `xi = xj`. Once this happens, the sequence must continue by repeating the cycle of values from `xi to xj−1`. Cycle detection is the problem of finding `i` and `j`, given `ƒ` and `x0`. Let `μ` be the smallest index such that the value associated will reappears and `λ` the smallest value such that `xμ = xλ+μ, λ` is the loop length.

Example:

Consider the sequence:
```
2, 0, 6, 3, 1, 6, 3, 1, 6, 3, 1, ....
```

The cycle in this value sequence is 6, 3, 1.
μ is 2 (first 6)
λ is 3 (length of the sequence or difference between position of consecutive 6).

The goal of this kata is to build a function that will return `[μ,λ]` when given a short sequence. Simple loops will be sufficient. The sequence will be given in the form of an array. All array will be valid sequence associated with deterministic function. It means that the sequence will repeat itself when a value is reached a second time. (So you treat two cases: non repeating [1,2,3,4] and repeating [1,2,1,2], no hybrid cases like [1,2,1,4]). If there is no repetition you should return [].

This kata is followed by two other cycle detection algorithms:
Loyd's: http://www.codewars.com/kata/cycle-detection-floyds-tortoise-and-the-hare
Bret's: http://www.codewars.com/kata/cycle-detection-brents-tortoise-and-hare

def cycle(sequence):
    found = {}
    for i, item in enumerate(sequence):
        if item in found:
            return [found[item], i - found[item]]
        found[item] = i
    else:
        return []


Solve in Python:
In computing, there are two primary byte order formats: big-endian and little-endian. Big-endian is used primarily for networking (e.g., IP addresses are transmitted in big-endian) whereas little-endian is used mainly by computers with microprocessors.

Here is an example (using 32-bit integers in hex format):

Little-Endian: 00 6D F4 C9 = 7,206,089

Big-Endian:    C9 F4 6D 00 = 3,388,239,104

Your job is to write a function that switches the byte order of a given integer. The function should take an integer n for the first argument, and the bit-size of the integer for the second argument. The bit size must be a power of 2 greater than or equal to 8. Your function should return a None value if the integer is negative, if the specified bit size is not a power of 2 that is 8 or larger, or if the integer is larger than the specified bit size can handle. In this kata, assume that all integers are unsigned (non-negative) and that all input arguments are integers (no floats, strings, None/nil values, etc.). Remember that you will need to account for padding of null (00) bytes.

Hint: bitwise operators are very helpful! :)

# Switch the endianness of integer n
# Assume 64-bit unsigned integers
import re
import math
def switch_endian(n, bits):
    number_in_hex = hex(n)
    length = len(number_in_hex)-2
    result = int(bits/4)
    x = math.log(bits, 2).is_integer()
    if x == False:
        return None
    if length > result:
        return None
    if length <= result:
        diff = result-length
        number_in_hex = number_in_hex.replace('0x','0'*diff)
        res_list = re.findall('[\da-z]{2}[^\da-z]*', number_in_hex)
        res_list = res_list[::-1]
        number_in_hex = ''.join(res_list)
        return(int('0x'+number_in_hex, 0))


Solve in Python:
In elementary arithmetic a "carry" is a digit that is transferred from one column of digits to another column of more significant digits during a calculation algorithm.

This Kata is about determining the number of carries performed during the addition of multi-digit numbers.

You will receive an input string containing a set of pairs of numbers formatted as follows:

```
123 456
555 555
123 594
```

And your output should be a string formatted as follows:

```
No carry operation
1 carry operations
3 carry operations
```

###Some Assumptions

- Assume that numbers can be of any length.
- But both numbers in the pair will be of the same length.
- Although not all the numbers in the set need to be of the same length.
- If a number is shorter, it will be zero-padded.
- The input may contain any arbitrary number of pairs.

def carry(s):
    a,b = s.split()
    c,f = 0,0
    for i,j in zip(map(int,a[::-1]),map(int,b[::-1])):
        if i+j+f > 9:
            f = 1
            c += 1
        else:
            f = 0
    return c

def solve(s):
    r = list(map(carry,s.splitlines()))
    return '\n'.join('No carry operation' if x==0 else f'{x} carry operations' for x in r)


Solve in Python:
In genetic the reverse complement of a sequence is formed by **reversing** the sequence and then taking the complement of each symbol.

The four nucleotides in DNA is Adenine (A), Cytosine (C), Guanine (G) and Thymine (Thymine).

- A is the complement of T
- C is the complement of G.

This is a bi-directional relation so:

- T is the complement of A
- G is the complement of C.

For this kata you need to complete the reverse complement function that take a DNA string and return the reverse complement string.

**Note**: You need to take care of lower and upper case. And if a sequence conatains some invalid characters you need to return "Invalid sequence".

This kata is based on the following [one](http://www.codewars.com/kata/complementary-dna/ruby) but with a little step in addition.

def reverse_complement(dna):
    # your code here
    reverse = {'A': 'T', 'T':'A', 'C':'G', 'G':'C'}
    r_c = ''
    for nucl in reversed(dna):
        if nucl not in reverse:
            return "Invalid sequence"
        else: r_c += reverse[nucl]
    return r_c


Solve in Python:
In genetics 2 differents DNAs sequences can code for the same protein.

This is due to the redundancy of the genetic code, in fact 2 different tri-nucleotide can code for the same amino-acid.
For example the tri-nucleotide 'TTT' and the tri-nucleotide 'TTC' both code for the amino-acid 'F'. For more information you can take a look [here](https://en.wikipedia.org/wiki/DNA_codon_table).

Your goal in this kata is to define if two differents DNAs sequences code for exactly the same protein. Your function take the 2 sequences you should compare.
For some kind of simplicity here the sequences will respect the following rules:

- It is a full protein sequence beginning with a Start codon and finishing by an Stop codon
- It will only contain valid tri-nucleotide.

The translation hash is available for you under a translation hash `$codons` [Ruby] or `codons` [Python and JavaScript].

To better understand this kata you can take a look at this [one](https://www.codewars.com/kata/5708ef48fe2d018413000776), it can help you to start.

def code_for_same_protein(seq1,seq2):
    if seq1 == seq2:
        return True
    lista = [['GCT','GCC','GCA','GCG'],['CGT','CGC','CGA','CGG','AGA','AGG'],['AAT','AAC'],['GAT','GAC'],['AAT','AAC','GAT','GAC'],['TGT','TGC'],['CAA','CAG'],['GAA','GAG'],['CAA','CAG','GAA','GAG'],['GGT','GGC','GGA','GGG'],['CAT','CAC'],['ATG'],['ATT','ATC','ATA'],['CTT','CTC','CTA','CTG','TTA','TTG'],['AAA','AAG'],['ATG'],['TTT','TTC'],['CCT','CCC','CCA','CCG'],['TCT','TCC','TCA','TCG','AGT','AGC'],['ACT','ACC','ACA','ACG'],['TGG'],['TAT','TAC'],['GTT','GTC','GTA','GTG'],['TAA','TGA','TAG']]
    for j in range(0,len(lista)):
        for i in range(0,len(seq1),3):
            if (seq1[i:i+3] in lista[j] and seq2[i:i+3] not in lista[j]):
                return False
    return True


Solve in Python:
In genetics a reading frame is a way to divide a sequence of nucleotides (DNA bases) into a set of consecutive non-overlapping triplets (also called codon). Each of this triplets is translated into an amino-acid during a translation process to create proteins.

In a single strand of DNA you find 3 Reading frames, for example the following sequence:
```
AGGTGACACCGCAAGCCTTATATTAGC
```
will be decompose in:
```
Frame 1: AGG·TGA·CAC·CGC·AAG·CCT·TAT·ATT·AGC
Frame 2: A·GGT·GAC·ACC·GCA·AGC·CTT·ATA·TTA·GC
Frame 3: AG·GTG·ACA·CCG·CAA·GCC·TTA·TAT·TAG·C
```
In a double strand DNA you find 3 more Reading frames base on the reverse complement-strand, given the previous DNA sequence, in the reverse complement ( A-->T, G-->C, T-->A, C-->G).
Due to the splicing of DNA strands and the fixed reading direction of a nucleotide strand, the reverse complement gets read from right to left

```
                        AGGTGACACCGCAAGCCTTATATTAGC
Reverse complement:     TCCACTGTGGCGTTCGGAATATAATCG
reversed reverse frame: GCTAATATAAGGCTTGCGGTGTCACCT
```

You have:
```
Reverse Frame 1: GCT AAT ATA AGG CTT GCG GTG TCA CCT
reverse Frame 2: G CTA ATA TAA GGC TTG CGG TGT CAC CT
reverse Frame 3: GC TAA TAT AAG GCT TGC GGT GTC ACC T
```

You can find more information about the Open Reading frame in wikipedia just [here] (https://en.wikipedia.org/wiki/Reading_frame)

Given the [standard table of genetic code](http://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi#SG1):

```
    AAs  = FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG
  Base1  = TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG
  Base2  = TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG
  Base3  = TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG
```

The tri-nucleotide TTT = F, TTC = F, TTA = L...

So our 6 frames will be translate as:

```
Frame 1: AGG·TGA·CAC·CGC·AAG·CCT·TAT·ATT·AGC
          R   *   H   R   K   P   Y   I   S

Frame 2: A·GGT·GAC·ACC·GCA·AGC·CTT·ATA·TTA·GC
             G  D   T   A  ...

import re

def translate_with_frame(dna, frames=[1, 2, 3, -1, -2, -3]):
    AAs = 'FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG'
    Base1 = 'TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG'
    Base2 = 'TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG'
    Base3 = 'TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG'
    trans = {'A': 'T', 'G': 'C', 'T': 'A', 'C': 'G'}
    intab = "AGTC"
    outtab = "TCAG"
    map = dict()
    for i, c in enumerate(AAs):
        code = Base1[i]+Base2[i]+Base3[i]
        map[code] = c
    res = []
    for i in frames:
        trantab = dna.maketrans(intab, outtab)
        DNA = dna if i > 0 else dna[::-1].translate(trantab)
        res.append(''.join(map[x]
                           for x in re.findall(r'.{3}', DNA[abs(i)-1:])))
    return res


Solve in Python:
In genetics a reading frame is a way to divide a sequence of nucleotides (DNA bases) into a set of consecutive non-overlapping triplets (also called codon). Each of this triplets is translated into an amino-acid during a translation process to create proteins.

Input
---
In a single strand of DNA you find 3 Reading frames, take for example the following input sequence:

    AGGTGACACCGCAAGCCTTATATTAGC

Output
---
For the output we are going to take the combinations and show them in the following manner:

````
Frame 1: AGG TGA CAC CGC AAG CCT TAT ATT AGC
Frame 2: A GGT GAC ACC GCA AGC CTT ATA TTA GC
Frame 3: AG GTG ACA CCG CAA GCC TTA TAT TAG C
````

For frame 1 split all of them in groups of three starting by the first base (letter).

For frame 2 split all of them in groups of three starting by the second base (letter) but having the first base (letter) at the beggining.

For frame 3 split all of them in groups of three starting by the third letter, but having the first and second bases (letters) at the beginning in the same order.

Series
---

1. [Decompose single strand DNA into 3 reading frames](http://www.codewars.com/kata/57507369b0b6d1b5a60001b3)

2. [Decompose double strand DNA into 6 reading frames](http://www.codewars.com/kata/57519060f2dac7ec95000c8e/)

3.  [Translate DNA to protein in 6 frames](http://www.codewars.com/kata/5708ef48fe2d018413000776)

def decompose_single_strand(single_strand):
    frame1= "Frame 1:"
    frame2= "Frame 2:"
    frame3= "Frame 3:"
    i=0
    while i in range(len(single_strand)):
        frame1+= " "+(single_strand[i:i+3])
        i+=3
    i=1
    frame2+= " " +(single_strand[0])
    while i in range(len(single_strand)):
        frame2+= " "+(single_strand[i:i+3])
        i+=3
    i=2
    frame3+= " "+(single_strand[0:2])
    while i in range(len(single_strand)):
        frame3+= " "+ (single_strand[i:i+3])
        i+=3
    frames = (frame1+'\n'+frame2+'\n'+frame3)
    return frames


Solve in Python:
In genetics, a sequence’s motif is a nucleotides (or amino-acid) sequence pattern. Sequence motifs have a biological significance. For more information you can take a look [here](https://en.wikipedia.org/wiki/Sequence_motif).

For this kata you need to complete the function `motif_locator`. This function receives 2 arguments - a sequence and a motif. Both arguments are strings.

You should return an array that contains all the start positions of the motif (in order). A sequence may contain 0 or more repetitions of the given motif. Note that the number of the first position is 1, not 0.

**Some examples:**

- For the `sequence` "ACGTGGGGACTAGGGG" and the `motif` "GGGG" the result should be [5, 13].
- For the `sequence` "ACCGTACCAAGGGACC" and the `motif` "AAT"  the result should be []
- For the `sequence` "GGG" and the motif "GG" the result should be [1, 2]

**Note**: You can take a look to my others bio-info kata [here](http://www.codewars.com/users/nbeck/authored)

def motif_locator(sequence, motif):
    res, i = [], 0
    while True:
        i = sequence.find(motif, i) + 1
        if not i: return res
        res.append(i)


Solve in Python:
In geometry, a cube is a three-dimensional solid object bounded by six square faces, facets or sides, with three meeting at each vertex.The cube is the only regular hexahedron and is one of the five Platonic solids. It has 12 edges, 6 faces and 8 vertices.The cube is also a square parallelepiped, an equilateral cuboid and a right rhombohedron. It is a regular square prism in three orientations, and a trigonal trapezohedron in four orientations.

You are given a task of finding a if the provided value is a perfect cube!

def you_are_a_cube(cube):
    return int(cube**0.33334)**3 == cube


Solve in Python:
In graph theory, a graph is a collection of nodes with connections between them.
Any node can be connected to any other node exactly once, and can be connected to no nodes, to some nodes, or to every other node.
Nodes cannot be connected to themselves
A path through a graph is a sequence of nodes, with every node connected to the node following and preceding it.
A closed path is a path which starts and ends at the same node.

An open path:
```
1 -> 2 -> 3
```
a closed path:
```
1 -> 2 -> 3 -> 1
```
A graph is connected if there is a path from every node to every other node.
A graph is a tree if it is connected and there are no closed paths.

Your job is to write a function 'isTree', which returns true if a graph is a tree, and false if it is not a tree.

Graphs will be given as an array with each item being an array of integers which are the nodes that node is connected to.

For example, this graph:
```
0--1
|  |
2--3--4
```
has array:
```
[[1,2], [0,3], [0,3], [1,2,4], [3]]
```
Note that it is also not a tree, because it contains closed path:
```
0->1->3->2->0
```
A node with no connections is an empty array
Note that if node 0 is connected to node 1, node 1 is also connected to node 0. This will always be true.
The order in which each connection is listed for each node also does not matter.

Good luck!

def isTree(Q) :
    if not len(Q) : return False
    H = [0] * len(Q)
    U = [[-1,0]]
    while len(U) :
        F,T = U.pop()
        if H[T] : return False
        H[T] = 1
        U += [[T,V] for V in Q[T] if V != F]
    return len(Q) == sum(H)


Solve in Python:
In his publication Liber Abaci Leonardo Bonacci, aka Fibonacci, posed a problem involving a population of idealized rabbits. These rabbits bred at a fixed rate, matured over the course of one month, had unlimited resources, and were immortal.

Beginning with one immature pair of these idealized rabbits that produce b pairs of offspring at the end of each month. Create a function that determines the number of pair of mature rabbits after n months.

To illustrate the problem, consider the following example:

```python
fib_rabbits(5, 3) returns 19
```

Month
Immature Pairs
Adult Pairs

0
1
0

1
0
1

2
3
1

3
3
4

4
12
7

5
21
19

Hint: any Fibonacci number can be computed using the following equation Fn = F(n-1) + F(n-2)

def fib_rabbits(n, b):
    f = [0, 1]
    for _ in range(n - 1): f.append(f[-1] + b * f[-2])
    return f[n]


Solve in Python:
In input string ```word```(1 word):
* replace the vowel with the nearest left consonant.
* replace the consonant with the nearest right vowel.

P.S. To complete this task imagine the alphabet is a circle (connect the first and last element of the array in the mind). For example, 'a' replace with 'z', 'y' with 'a', etc.(see below)

For example:
```
'codewars' => 'enedazuu'
'cat' => 'ezu'
'abcdtuvwxyz' => 'zeeeutaaaaa'
```

It is preloaded:

```
const alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
const consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'];
const vowels = ['a','e','i','o','u'];
```

P.S. You work with lowercase letters only.

def replace_letters(word):
  return word.translate(str.maketrans('abcdefghijklmnopqrstuvwxyz','zeeediiihooooonuuuuutaaaaa'))


Solve in Python:
In mathematics, a **pandigital number** is a number that in a given base has among its significant digits each digit used in the base at least once. For example, 1234567890 is a pandigital number in base 10.

For simplification, in this kata, we will consider pandigital numbers in *base 10* and with all digits used *exactly once*. The challenge is to calculate a sorted sequence of pandigital numbers, starting at a certain `offset` and with a specified `size`.

Example:
```python
  > get_sequence(0, 5)
  [1023456789, 1023456798, 1023456879, 1023456897, 1023456978]
```

Rules:
- We are looking for positive pandigital numbers in base 10.
- Each digit should occur `exactly once`.
- A pandigital number can't start with digit zero.
- The offset is an integer (negative, zero or positive number) (long in Java)
- The size is a positive integer number (int in Java)
- Return the `size` pandigital numbers which are not smaller than the `offset`. If there is not enough `size` pandigital numbers, just return all of them.
- Return an empty array if nothing is found.

def get_sequence(offset, size):
    result = []
    if offset < 1023456789:
        offset = 1023456789
    while len(result) < size and offset < 10000000000:
        if len(set(str(offset))) == 10:
            result.append(offset)
        offset += 1
    return result


Solve in Python:
In mathematics, a [Diophantine equation](https://en.wikipedia.org/wiki/Diophantine_equation) is a polynomial equation, usually with two or more unknowns, such that only the integer solutions are sought or studied.

In this kata we want to find all integers `x, y` (`x >= 0, y >= 0`) solutions of a diophantine equation of the form:
#### x^(2) - 4 \* y^(2) = n

(where the unknowns are `x` and `y`, and `n` is a given positive number)
in decreasing order of the positive xi.

If there is no solution return `[]` or `"[]" or ""`. (See "RUN SAMPLE TESTS" for examples of returns).

## Examples:

```
solEquaStr(90005) --> "[[45003, 22501], [9003, 4499], [981, 467], [309, 37]]"
solEquaStr(90002) --> "[]"
```

## Hint:

x^(2) - 4 \* y^(2) = (x - 2\*y) \* (x + 2\*y)

def sol_equa(n):
    res = []
    if n <= 0:
        return res
    for i in range(1,int(pow(n,1/2)+1)):
        if int(n % i) == 0 and int(n-i*i) % (4*i) ==0:
            res.append([int((i+n/i)/2),int((n/i-i)/4)])
    return res


Solve in Python:
In mathematics, a matrix (plural matrices) is a rectangular array of numbers. Matrices have many applications in programming, from performing transformations in 2D space to machine learning.

One of the most useful operations to perform on matrices is matrix multiplication, which takes a pair of matrices and produces another matrix – known as the dot product. Multiplying matrices is very different to multiplying real numbers, and follows its own set of rules.

Unlike multiplying real numbers, multiplying matrices is non-commutative: in other words, multiplying matrix ```a``` by matrix ```b``` will not give the same result as multiplying matrix ```b``` by matrix ```a```.

Additionally, not all pairs of matrix can be multiplied. For two matrices to be multipliable, the number of columns in matrix ```a``` must match the number of rows in matrix ```b```.

There are many introductions to matrix multiplication online, including at Khan Academy, and in the classic MIT lecture series by Herbert Gross.

To complete this kata, write a function that takes two matrices - ```a``` and ```b``` - and returns the dot product of those matrices. If the matrices cannot be multiplied, return ```-1``` for JS/Python, or `null` for Java.

Each matrix will be represented by a two-dimensional list (a list of lists). Each inner list will contain one or more numbers, representing a row in the matrix.

For example, the following matrix:

```|1 2|``````|3 4|```

Would be represented as:

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

It can be assumed that all lists will be valid matrices, composed of lists with equal numbers of elements, and which contain only numbers. The numbers may include integers and/or decimal points.

import numpy as np
def getMatrixProduct(a, b):
    try: return np.dot(a, b).tolist()
    except: return -1


Solve in Python:
In mathematics, the factorial of integer 'n' is written as 'n!'.
It is equal to the product of n and every integer preceding it.
For example: **5! = 1 x 2 x 3 x 4 x 5 = 120**

Your mission is simple: write a function that takes an integer 'n' and returns 'n!'.

You are guaranteed an integer argument. For any values outside the positive range, return `null`, `nil` or `None` .

**Note:** 0! is always equal to 1. Negative values should return null;

For more on Factorials : http://en.wikipedia.org/wiki/Factorial

import math

def factorial(n):
    if n < 0:
        return None
    return math.factorial(n)


Solve in Python:
In music, if you double (or halve) the pitch of any note you will get to the same note again.

"Concert A" is fixed at 440 Hz, and every other note is defined based on that. 880 Hz is also an A, as is 1760 Hz, as is 220 Hz.

There are 12 notes in Western music: A, A#, B, C, C#, D, D#, E, F, F#, G, G#. You are given a preloaded dictionary with these 12 notes and one of the pitches that creates that note (starting at Concert A).

Now, given a pitch (in Hz), return the corresponding note. (All inputs will be valid notes).

For reference, the notes dictionary looks like this:

```python
notes_dictionary = {
    440: "A",
    466.16: "A#",
    493.88: "B",
    523.25: "C",
    554.37: "C#",
    587.33: "D",
    622.25: "D#",
    659.25: "E",
    698.46: "F",
    739.99: "F#",
    783.99: "G",
    830.61: "G#"
}
```

Musicians: all pitches based on equal tempermanent, taken from [here](http://pages.mtu.edu/~suits/notefreqs.html).

N="A A# B C C# D D# E F # F# G G#".split()
get_note=g=lambda n:12<n//1<27and N[int(n)-13]or g(n/2)


Solve in Python:
In my town ,there live a coder named Chef . He is a cool programmer . One day , he participate in a programming contest ,the contest give him only one problem . If he can’t solve the problem ,the problem setter will kill him . But the round allow you to help Chef. Can you save the life of Chef from problem setter ? :p
You are given two point of a straightline in X and Y axis and they are A(x1 , y1) and B(x2 ,y2) . Problem setter will give you another point C(x3 , y3) . If C exist in AB straightline ,then print “YES” . Otherwise ,print “NO” in first line and print the minimum distance from C to AB straightline in second line .
Please , save the life of Chef .
Note : It is not possible that A and B point is similar .

-----Input:-----
The first line of the input contains a single integer t (1≤t≤100) — the number of test cases .
Each test case starts with four integers( x1, y1 , x2 , y2 ) in first line .
Next line contains a single number q ,the number of queries . Each query contains two integers ( x3 ,y3 )

-----Output:-----
Print , q number of “YES” or “NO” (as it mentioned above) in each test case .For every test case , print “Test case : i ” ( 1<= i <=T )

-----Constraints-----
-1000 <=  x1 , y1 , x2 , y2 , x3 , y3 <= 1000

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

-----Sample Output:-----
Test case : 1
YES
NO
3.000000
Test case : 2
NO
3.328201

# cook your dish here
from math import sqrt
for i in range(int(input())):
 x1,y1,x2,y2=list(map(float,input().split()))
 m=(y2-y1)/(x2-x1)
 c=y2-m*x2
 print('Test case : ',i+1)
 q=int(input())
 for i in range(q):
  x3,y3=list(map(float,input().split()))
  if(y3-m*x3-c==0):
   print("YES")
  else:
   d=(abs(y3-m*x3-c))/sqrt(1+m*m)
   print("NO")
   print("%.6f" % d)


Solve in Python:
In number theory, Euler's totient is an arithmetic function, introduced in 1763 by Euler, that counts the positive integers less than or equal to `n` that are relatively prime to `n`. Thus, if `n` is a positive integer, then `φ(n)`, notation introduced by Gauss in 1801, is the number of positive integers `k ≤ n` for which `gcd(n, k) = 1`.
The totient function is important in number theory, mainly because it gives the order of the multiplicative group of integers modulo `n`. The totient function also plays a key role in the definition of the RSA encryption system.

For example `let n = 9`.
Then `gcd(9, 3) = gcd(9, 6) = 3` and `gcd(9, 9) = 9`.
The other six numbers in the range `1 ≤ k ≤ 9` i.e. `1, 2, 4, 5, 7, 8` are relatively prime to `9`.
Therefore, `φ(9) = 6`.
As another example, `φ(1) = 1` since `gcd(1, 1) = 1`.

There are generally two approaches to this function:

* Iteratively counting the numbers `k ≤ n` such that `gcd(n,k) = 1`.

* Using the Euler product formula.
  This is an explicit formula for calculating `φ(n)` depending on the prime divisor of `n`:
  `φ(n) = n * Product (1 - 1/p)` where the product is taken over the primes `p ≤ n` that divide `n`.
  For example: `φ(36) = 36 * (1 - 1/2) * (1 - 1/3) = 36 * 1/2 * 2/3 = 12`.
  This second method seems more complex and not likely to be faster, but in practice we will often look for `φ(n)` with `n` prime. It correctly gives `φ(n) = n - 1` if `n` is prime.

You have to code the Euler totient function, that takes an integer `1 ≤ n` as input and returns `φ(n)`.

```if:javascript
You do have to check if `n` is a number, is an integer and that `1 ≤ n`; if that is not the case, the function should return `0`.
```

```if:python
You do have to check if `n` is a number, is an integer and that `1 ≤ n`; if that is not the case, the function should return `0`.
```

```if:racket
`n` is always a positive integer.
```

Input range: `1 ≤ n ≤ 1e10`

def prod(a, s=1):
    for p in a: s *= p
    return s

def prime_factors(n):
    for d in range(2, int(n ** 0.5) + 1):
        while n % d == 0:
            yield d
            n //= d
    if n > 1:
        yield n

def totient(n):
    if type(n) is not int or n < 0: return 0
    return round(n * prod(1 - 1 / p for p in set(prime_factors(n))))


Solve in Python:
In number theory, an  **[abundant](https://en.wikipedia.org/wiki/Abundant_number)** number or an **[excessive](https://en.wikipedia.org/wiki/Abundant_number)** number is one for which the sum of it's **[proper divisors](http://mathworld.wolfram.com/ProperDivisor.html)** is greater than the number itself.  The integer **12** is the first abundant number. Its proper divisors are 1, 2, 3, 4 and 6 for a total of **16**. The amount by which the sum exceeds the number is the **abundance**. The number **12** has an abundance of **4**, for example. Other initial abundant numbers are : 12, 18, 20, 24, 30, 36, 40, 42, 48, 54 etc . **Infinitely** many **odd** and **even** abundant numbers exist.
As you should have guessed by now, in this kata your function will take a positive integer **h** as range input and return a nested array/list that will contain the following informations-

* Highest available **odd** or **even** abundant number in that range
* It's **abundance**

Examples
--------
A few examples never hurt nobody, right???

```rust
abundant(15)  = [[12], [4]]
abundant(19)  = [[18], [3]]
abundant(100) = [[100], [17]]
abundant(999) = [[996], [360]]
```

Tips
----
The problem involves some pretty big random numbers. So try to optimize your code for performance as far as you can. And yes, the input argument will always be positive integers. So no need to check there.

Good luck!

def abundant(h):
    for n in range(h,0,-1):
        s = sum(i for i in range(1,n//2+1) if not n%i)
        if s > n:
            return [[n],[s-n]]


Solve in Python:
In number world, two different numbers are friends if they have a lot in common, but also each one has unique perks.

More precisely, two different numbers $a$ and $b$ are friends if $gcd(a,b)$, $\frac{a}{gcd(a,b)}$, $\frac{b}{gcd(a,b)}$ can form sides of a triangle.

Three numbers $a$, $b$ and $c$ can form sides of a triangle if $a + b > c$, $b + c > a$ and $c + a > b$.

In a group of numbers, a number is lonely if it doesn't have any friends in that group.

Given a group of numbers containing all numbers from $1, 2, 3, ..., n$, how many numbers in that group are lonely?

-----Input-----

The first line contains a single integer $t$ $(1 \leq t \leq 10^6)$ - number of test cases.

On next line there are $t$ numbers, $n_i$ $(1 \leq n_i \leq 10^6)$ - meaning that in case $i$ you should solve for numbers $1, 2, 3, ..., n_i$.

-----Output-----

For each test case, print the answer on separate lines: number of lonely numbers in group $1, 2, 3, ..., n_i$.

-----Example-----
Input
3
1 5 10

Output
1
3
3

-----Note-----

For first test case, $1$ is the only number and therefore lonely.

For second test case where $n=5$, numbers $1$, $3$ and $5$ are lonely.

For third test case where $n=10$, numbers $1$, $5$ and $7$ are lonely.

import os
import sys
from io import BytesIO, IOBase

def main():
    pass

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

primes = []
prime = [True] * (10 ** 6  +5)
prime[0] = False

for i in range(2, 10 ** 6):
    if prime[i]:
        for j in range(2 * i, 10 ** 6 + 5, i):
            prime[j] = False

pref = [0]
for i in range(1, 10 ** 6 + 5):
    pref.append(pref[-1])
    if prime[i]:
        pref[-1] += 1
    s =...


Solve in Python:
In order to celebrate Twice's 5th anniversary, Tzuyu and Sana decided to play a game.

Tzuyu gave Sana two integers $a$ and $b$ and a really important quest.

In order to complete the quest, Sana has to output the smallest possible value of ($a \oplus x$) + ($b \oplus x$) for any given $x$, where $\oplus$ denotes the bitwise XOR operation.

-----Input-----

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^{4}$). Description of the test cases follows.

The only line of each test case contains two integers $a$ and $b$ ($1 \le a, b \le 10^{9}$).

-----Output-----

For each testcase, output the smallest possible value of the given expression.

-----Example-----
Input
6
6 12
4 9
59 832
28 14
4925 2912
1 1

Output
10
13
891
18
6237
0

-----Note-----

For the first test case Sana can choose $x=4$ and the value will be ($6 \oplus 4$) + ($12 \oplus 4$) = $2 + 8$ = $10$. It can be shown that this is the smallest possible value.

def main():
    a, b = list(map(int, input().split()))
    print(a + b - 2*(a&b))
def __starting_point():
    t = int(input())
    for i in range(t):
        main()

__starting_point()


Solve in Python:
In order to establish dominance amongst his friends, Chef has decided that he will only walk in large steps of length exactly $K$ feet. However, this has presented many problems in Chef’s life because there are certain distances that he cannot traverse. Eg. If his step length is $5$ feet, he cannot travel a distance of $12$ feet. Chef has a strict travel plan that he follows on most days, but now he is worried that some of those distances may become impossible to travel. Given $N$ distances, tell Chef which ones he cannot travel.

-----Input:-----
- The first line will contain a single integer $T$, the number of test cases.
- The first line of each test case will contain two space separated integers - $N$, the number of distances, and $K$, Chef’s step length.
- The second line of each test case will contain $N$ space separated integers, the $i^{th}$ of which represents $D_i$, the distance of the $i^{th}$ path.

-----Output:-----
For each testcase, output a string consisting of $N$ characters. The $i^{th}$ character should be $1$ if the distance is traversable, and $0$ if not.

-----Constraints-----
- $1 \leq T \leq 1000$
- $1 \leq N \leq 1000$
- $1 \leq K \leq 10^9$
- $1 \leq D_i \leq 10^9$

-----Subtasks-----
- 100 points : No additional constraints.

-----Sample Input:-----
1
5 3
12 13 18 20 27216

-----Sample Output:-----
10101

-----Explanation:-----
The first distance can be traversed in $4$ steps.

The second distance cannot be traversed.

The third distance can be traversed in $6$ steps.

The fourth distance cannot be traversed.

The fifth distance can be traversed in $9072$ steps.

# cook your dish here
t=int(input())
for i in range(t):
 n,k=map(int,input().split())
 s=""
 arr=list(map(int,input().split()))
 for z in range(n):
  if arr[z]%k==0:
   s=s+"1"
  else:
    s=s+"0"
 print(s)


Solve in Python:
In order to fly to the Moon Mister B just needs to solve the following problem.

There is a complete indirected graph with n vertices. You need to cover it with several simple cycles of length 3 and 4 so that each edge is in exactly 2 cycles.

We are sure that Mister B will solve the problem soon and will fly to the Moon. Will you?

-----Input-----

The only line contains single integer n (3 ≤ n ≤ 300).

-----Output-----

If there is no answer, print -1.

Otherwise, in the first line print k (1 ≤ k ≤ n^2) — the number of cycles in your solution.

In each of the next k lines print description of one cycle in the following format: first print integer m (3 ≤ m ≤ 4) — the length of the cycle, then print m integers v_1, v_2, ..., v_{m} (1 ≤ v_{i} ≤ n) — the vertices in the cycle in the traverse order. Each edge should be in exactly two cycles.

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

Output
2
3 1 2 3
3 1 2 3

Input
5

Output
6
3 5 4 2
3 3 1 5
4 4 5 2 3
4 4 3 2 1
3 4 2 1
3 3 1 5

#!/usr/bin/env python3

from collections import defaultdict

DEBUG = False

def main():
    if DEBUG:
        test()

    n = int(input())

    paths = cycles(n)

    print(len(paths))
    for p in paths:
        print('%d %s' % (len(p), ' '.join([str(v) for v in p])))

def cycles(n):
    """Builds a set of cycles for a fully connected graph with n vertices."""
    if n % 2 == 0:
        return even(n)
    else:
        return odd(n)

def even(n):
    """Builds a set of cycles that a graph with even vertices."""
    assert n % 2 == 0

    # Base case for complete graph such that V = {1, 2, 3, 4}.
    cycles = [[1, 2, 3], [2, 3, 4], [3, 4, 1], [4, 1, 2]]

    for i in range(6, n + 1, 2):
        a, b = i, i - 1

        # Use edges (a, 1), (a, 0), (b, 1), (b, 0), (a, b) exactly twice each.
        cycles += [[a, 1, b], [a, 2, b], [a, 1, b, 2]]

        # Similar to odd(...) as we are left with 2n - 2 edges to use
        # connected to i - 4 of the vertices V' = {3 ... i - 2}. Notice that
        # |V'| is even so we can apply the same strategy as in odd(...).
        for k in range(3, i - 1, 2):
            c, d = k, k + 1
            cycles += [[a, c, b, d]] * 2

    return cycles

def odd(n):
    """Builds a set of cycles that a graph with odd vertices."""
    assert n % 2 == 1

    # Base case for complete graph such that V = {1, 2, 3}.
    cycles = [[1, 2, 3]] * 2

    for i in range(5, n + 1, 2):
        a, b = i, i - 1
        # Say the new vertices are {a, b}. Since the graph is fully connected
        # adding these 2 vertices results in 2n + 1 more edges. We use a length
        # 3 cycle a -> b -> 1 > a twice to use up 3 of these edges.
        cycles += [[a, b, 1]] * 2

        # At this point we are left with 2n + 1 - 3 = 2n - 2 edges to use
        # connected to i - 3 of the vertices V' = {2 ... i - 2}. Notice that
        # |V'| is even. To use these edges and cover vertices V' we take pairs
        # c, d in V' and create two of each path a -> c -> b -> d -> a.
        for k in range(2, i...


Solve in Python:
In order to prove it's success and gain funding, the wilderness zoo needs to prove to environmentalists that it has x number of mating pairs of bears.

You must check within string (s) to find all of the mating pairs, and return a string containing only them. Line them up for inspection.

Rules:
Bears are either 'B' (male) or '8' (female),
Bears must be together in male/female pairs 'B8' or '8B',
Mating pairs must involve two distinct bears each ('B8B' may look fun, but does not count as two pairs).

Return an array containing a string of only the mating pairs available. e.g:

'EvHB8KN8ik8BiyxfeyKBmiCMj' ---> 'B88B'    (empty string if there are no pairs)

and true if the number is more than or equal to x, false if not:

(6, 'EvHB8KN8ik8BiyxfeyKBmiCMj') ---> ['B88B', false];

x will always be a positive integer, and s will never be empty

import re

def bears(x,s):
    matches = re.findall('(B8|8B)', s)
    return [''.join(matches), len(matches)>=x]


Solve in Python:
In order to win over and get noticed by his favorite streamer Daenerys, Jon decides to donate a significant amount of money . Every donation made to Daenerys is of $at$ $least$ $1$ $beastcoin$ and is displayed on Daenerys's stream alongside any message written and is visible to every viewer.
After spotting that Daenerys had set out a target for the streaming day at minimum $X$   beastcoins, all her viewers would only donate amounts less than $X$ beastcoins. Jon decided to better all of them by straight out donating more than or equal to $X$ beastcoins. Further, he decides to write a message along with his special donation to leave her in awe. His message would be : "Crossing my donation with any other donation will only increase the value of my donation". By Crossing, he means to take the $XOR$ .
But even for all his intellectual brilliance, money doesn't grow on trees for Jon. After all he is an underpaid employee in his fancy big name MNC. Unlike Daenerys's daily cash cow who makes videos of how she donated carelessly to other people, Jon has a budget and in this case too, he is looking for the minimum donation he needs to make.
Can you tell Jon the minimum amount he needs to donate to Daenerys so that he is able to credibly put out the above comment alongside the donation in order to HOPEFULLY win her over.

-----Input Format-----
- First line contain an interger $T$, which denotes number of testcases. Next $T$ lines contain single interger $X$.

-----Output Format-----
- For every testcase print one integer, i.e. minimum donation Jon needs to make.

-----Constriants-----
- $ 1 \leq T \leq 100000 $
- $ 2 \leq X \leq 10^{18} $

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

3

7

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

8

# cook your dish here
t=int(input())
c=[]
for i in range(t):
    x=int(input())
    b=bin(x).replace("0b","")
    b=str(b)
    ans="1"
    ans+="0"*len(b)
    el="1"
    el+="0"*(len(b)-1)
    #print(ans)
    i=int(ans,2)
    if(el==b):
        c.append(x)
    else:
       c.append(i)

for k in c:
    print(k)


Solve in Python:
In poker, you have 5 cards. There are 10 kinds of poker hands (from highest to lowest):

-  royal flush - ace, king, queen, jack and ten, all in the same suit

-  straight flush - five cards of the same suit in sequence, such
as 10,9,8,7,6 of clubs; ace can be counted both as the highest card or as the
lowest card - A,2,3,4,5 of hearts is a straight flush. But 4,3,2,A,K of hearts is not a straight flush - it's just a flush.

-  four of a kind - four cards of the same rank, such as four kings.

-  full house - three cards of one rank plus two cards of another rank

-  flush - five cards of the same suit (but not a straight flush)

-  straight - five cards in order - just like the straight flush, but mixed suits

-  three of a kind - three cards of one rank and two other cards

-  two pairs - two cards of one rank, two cards of another rank, and one more card

-  pair - two cards of the same rank

-  high card - none of the above

Write a program that will help you play poker by telling you what kind of hand you have.

-----Input-----

The first line of input contains the number of test cases (no more than 20). Each test case consists of one line - five space separated cards. Each card is represented by a two-letter (or digit) word. The first character is the rank (A,K,Q,J,T,9,8,7,6,5,4,3 or 2), the second character is the suit (S,H,D,C standing for spades, hearts, diamonds and clubs). The cards can be in any order (but they will not repeat).

-----Output-----

For each test case output one line describing the type of a hand, exactly like in the list above.

-----Example-----
Input:
3
AH KH QH TH JH
KH 5S 3C 5C 7D
QH QD 2S QC 2C

Output:
royal flush
pair
full house

cards = ['A','2','3','4','5','6','7','8','9','T','J','Q','K']

def royal_flush(arr):
 nonlocal ans, confirm
 rf_set = 'TJQKA'
 rf = 1
 for char in arr:
  if char[0] not in rf_set:
   rf = 0
   break
 if rf :
  if len(set(suit)) == 1:
   ans = 'royal flush'
   confirm = 1
def straight_flush(arr):  # and 'straight'
 nonlocal ans,confirm
 sf = 1
 for i in range(1,5):
  if arr[i] - arr[i-1] != 1:
   sf = 0
   break
 if sf:
  if len(set(suit)) == 1 :
   ans = 'straight flush'
   confirm = 1
  else:
   ans = 'straight'
   confirm = 1
def four(arr):
 nonlocal ans, confirm
 f = 0
 for char in arr:
  if arr.count(char) == 4:
   f = 1
   break
 if f:
  confirm = 1
  ans = 'four of a kind'
def full_house(arr): # and three
 nonlocal ans, confirm
 fh = 0
 three = 0
 two = 0
 for char in arr:
  if arr.count(char) == 3:
   three = 1
  elif arr.count(char) == 2:
   two = 1
 if three and two:
  confirm = 1
  ans = 'full house'
 elif three:
  confirm = 1
  ans = 'three of a kind'
def two_pairs(arr):
 nonlocal ans, confirm
 temp = []
 for char in arr:
  if arr.count(char) == 2:
   if char not in temp:
    temp.append(char)
 if len(temp) == 2:
  confirm = 1
  ans = 'two pairs'
 elif len(temp) == 1:
  confirm = 1
  ans = 'pair'

def idex(char_x):
 return cards.index(char_x)
for _ in range(int(input())):
 onhand = list(input().split())
 cards_set = [[],[]]
 suit = []
 confirm = 0
 ans = ''
 for c in onhand:
  num = idex(c[0])
  cards_set[0].append(num)
  if num == 0:
   cards_set[1].append(13)
  else:
   cards_set[1].append(num)
  suit.append(c[1])
 royal_flush(onhand)
 if not confirm:
  cards_set[0] = sorted(cards_set[0])
  cards_set[1] = sorted(cards_set[1])
  straight_flush(cards_set[0])
  straight_flush(cards_set[1])
 if not confirm:
  four(cards_set[0])
  four(cards_set[1])
 if not confirm:
  full_house(cards_set[0])
  full_house(cards_set[1])
 if not confirm:
  if len(set(suit)) == 1:
   confirm = 1
   ans = 'flush'
 if not confirm:
  two_pairs(cards_set[0])
  two_pairs(cards_set[1])
 print(ans if confirm else 'high card')


Solve in Python:
In programming you know the use of the logical negation operator (**!**), it reverses the meaning of a condition.

Your task is to complete the function 'negationValue()' that takes a string of negations with a value and returns what the value would be if those negations were applied to it.

```python
negation_value("!", False) #=> True
negation_value("!!!!!", True) #=> False
negation_value("!!", []) #=> False
```

Do not use the `eval()` function or the `Function()` constructor in JavaScript.

Note: Always return a boolean value, even if there're no negations.

def negation_value(s, x):
    return len(s) % 2 ^ bool(x)


Solve in Python:
In recreational mathematics, a [Keith number](https://en.wikipedia.org/wiki/Keith_number) or repfigit number (short for repetitive Fibonacci-like digit) is a number in the following integer sequence:

`14, 19, 28, 47, 61, 75, 197, 742, 1104, 1537, 2208, 2580, 3684, 4788, 7385, 7647, 7909, ...` (sequence A007629 in the OEIS)

Keith numbers were introduced by Mike Keith in 1987. They are computationally very challenging to find, with only about 100 known.

Implement the code to check if the given number is a Keith number. Return the number number of iteration needed to confirm it; otherwise return `false`.

**Note:** 1-digit numbers are **not** Keith numbers by definition

## Examples

```
n = 197      # --> [1, 9, 7]

# calculation           iteration
1 + 9 + 7 = 17         #    1
9 + 7 + 17 = 33        #    2
7 + 17 + 33 = 57       #    3
17 + 33 + 57 = 107     #    4
33 + 57 + 107 = 197    #    5
```
As `197` is the same as the initial number, so it's a Keith number: return `5`

Another example:
```
n = 196

# calculation          iteration
1 + 9 + 6 = 16        #    1
...
```

`196` is not a Keith number, so return `false`

def is_keith_number(n):
    numList = [int(i) for i in str(n)]  # int array
    if len(numList) > 1:  # min 2 digits
        itr = 0
        while numList[0] <= n:
            # replace array entries by its sum:
            numList[itr % len(numList)] = sum(numList)
            itr += 1
            if n in numList:  # keith-condition
                return itr
    return False


Solve in Python:
In recreational mathematics, a magic square is an arrangement of distinct numbers (i.e., each number is used once), usually integers, in a square grid, where the numbers in each row, and in each column, and the numbers in the main and secondary diagonals, all add up to the same number, called the "magic constant."

For example, the following "square":

      4    9    2 -> 15
      3    5    7 -> 15
      8    1    6 -> 15
     /v    v    v \
    15 15   15   15  15

A 3x3 magic square will have its sums always resulting to 15, this number is called the "magic constant" and changes according to the square size.

In this problem you will have to create a function that receives a 3x3 'square' and returns True if it is magic and False otherwise.
The sum of rows, columns or diagonals should **always** equal **15**.

For example, the above square will be passed like: `[4, 9, 2, 3, 5, 7, 8, 1, 6]` and the output should be True

`[9, 4, 7, 3, 5, 2, 8, 6, 1]` should return False

### Note:
This kata is very easy. If you want to try some more "difficult" ones you may try these :
* [Magic Square - Verify 3x3](https://www.codewars.com/kata/magic-square-verify-3x3)
* [Double Even Magic Square](https://www.codewars.com/kata/double-even-magic-square)
* [Odd Magic Square](https://www.codewars.com/kata/odd-magic-square)

# Will work for any size (as long as it's a square)
def is_magical(sq):
    N = int(len(sq)**0.5)
    res = sum(sq[::N+1])
    return res == sum(sq[N-1:-1:N-1]) and all(sum(sq[i*N:(i+1)*N]) == sum(sq[i::N]) == res for i in range(N))


Solve in Python:
In some countries of former Soviet Union there was a belief about lucky tickets. A transport ticket of any sort was believed to posess luck if sum of digits on the left half of its number was equal to the sum of digits on the right half. Here are examples of such numbers:
```
003111    #             3 = 1 + 1 + 1
813372    #     8 + 1 + 3 = 3 + 7 + 2
17935     #         1 + 7 = 3 + 5  // if the length is odd, you should ignore the middle number when adding the halves.
56328116  # 5 + 6 + 3 + 2 = 8 + 1 + 1 + 6
```
Such tickets were either eaten after being used or collected for bragging rights.

Your task is to write a funtion ```luck_check(str)```, which returns ```true/True``` if argument is string decimal representation of a lucky ticket number, or ```false/False``` for all other numbers. It should throw errors for empty strings or strings which don't represent a decimal number.

def luck_check(s):
    q, r = divmod(len(s), 2)
    return sum(int(a) for a in s[:q]) == sum(int(b) for b in s[q + r:])


Solve in Python:
In some country there are exactly n cities and m bidirectional roads connecting the cities. Cities are numbered with integers from 1 to n. If cities a and b are connected by a road, then in an hour you can go along this road either from city a to city b, or from city b to city a. The road network is such that from any city you can get to any other one by moving along the roads.

You want to destroy the largest possible number of roads in the country so that the remaining roads would allow you to get from city s_1 to city t_1 in at most l_1 hours and get from city s_2 to city t_2 in at most l_2 hours.

Determine what maximum number of roads you need to destroy in order to meet the condition of your plan. If it is impossible to reach the desired result, print -1.

-----Input-----

The first line contains two integers n, m (1 ≤ n ≤ 3000, $n - 1 \leq m \leq \operatorname{min} \{3000, \frac{n(n - 1)}{2} \}$) — the number of cities and roads in the country, respectively.

Next m lines contain the descriptions of the roads as pairs of integers a_{i}, b_{i} (1 ≤ a_{i}, b_{i} ≤ n, a_{i} ≠ b_{i}). It is guaranteed that the roads that are given in the description can transport you from any city to any other one. It is guaranteed that each pair of cities has at most one road between them.

The last two lines contains three integers each, s_1, t_1, l_1 and s_2, t_2, l_2, respectively (1 ≤ s_{i}, t_{i} ≤ n, 0 ≤ l_{i} ≤ n).

-----Output-----

Print a single number — the answer to the problem. If the it is impossible to meet the conditions, print -1.

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

Output
0

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

Output
1

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

Output
-1

import sys
from collections import deque

n, m = [int(i) for i in sys.stdin.readline().split()]
neighbors = [set() for _ in range(n)]
for i in range(m):
    m1, m2 = [int(i) for i in sys.stdin.readline().split()]
    neighbors[m1-1].add(m2-1)
    neighbors[m2-1].add(m1-1)

s1, t1, l1 = [int(i) for i in sys.stdin.readline().split()]
s2, t2, l2 = [int(i) for i in sys.stdin.readline().split()]
s1 -= 1
s2 -= 1
t1 -= 1
t2 -= 1

# compute all pairs distance
dists = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
    # bfs
    q = deque([(i, 0)])
    visited = [False for _ in range(n)]
    visited[i] = True
    while len(q) != 0:
        v, dist = q.popleft()
        dists[i][v] = dist
        for neighbor in neighbors[v]:
            if not visited[neighbor]:
                q.append((neighbor, dist+1))
                visited[neighbor] = True

best_found = m+1
# first case: 2 paths don't share edge
if dists[s1][t1] <= l1 and dists[s2][t2] <= l2:
    best_found = min(best_found, dists[s1][t1] + dists[s2][t2])

# second case: there are points u, v such that they share path along u-v
for u in range(n):
    for v in range(n):
        if u == v:
            continue
        # case 1: s1-u-v-t1, s2-u-v-t2
        path1_length = dists[s1][u] + dists[u][v] + dists[v][t1]
        path2_length = dists[s2][u] + dists[u][v] + dists[v][t2]
        if path1_length <= l1 and path2_length <= l2:
            total_length = path1_length + path2_length - dists[u][v]
            best_found = min(best_found, total_length)
        # case 2: s1-u-v-t1, s2-v-u-t2
        path1_length = dists[s1][u] + dists[u][v] + dists[v][t1]
        path2_length = dists[s2][v] + dists[v][u] + dists[u][t2]
        if path1_length <= l1 and path2_length <= l2:
            total_length = path1_length + path2_length - dists[u][v]
            best_found = min(best_found, total_length)
        # case 3: s1-v-u-t1, s2-u-v-t2
        path1_length = dists[s1][v] + dists[v][u] + dists[u][t1]
        path2_length = dists[s2][u] + dists[u][v] +...


Solve in Python:
In some ranking people collects points. The challenge is sort by points and calulate position for every person. But remember if two or more persons have same number of points, they should have same position number and sorted by name (name is unique).

For example:
Input structure:

Output should be:

def ranking(people):
    S = sorted(d['points'] for d in people)[::-1]

    return [{**d, **{'position': S.index(d['points']) + 1}} for d in sorted(people, key=lambda k: (-k['points'], k['name']))]


Solve in Python:
In telecomunications we use information coding to detect and prevent errors while sending data.

A parity bit is a bit added to a string of binary code that indicates whether the number of 1-bits in the string is even or odd. Parity bits are used as the simplest form of error detecting code, and can detect a 1 bit error.

In this case we are using even parity: the parity bit is set to `0` if the number of `1`-bits is even, and is set to `1` if odd.

We are using them for the transfer of ASCII characters in binary (7-bit strings): the parity is added to the end of the 7-bit string, forming the 8th bit.

In this Kata you are to test for 1-bit errors and return a new string consisting of all of the correct ASCII caracters **in 7 bit format** (removing the parity bit), or `"error"` in place of ASCII characters in which errors were detected.

For more information on parity bits: https://en.wikipedia.org/wiki/Parity_bit

## Examples

Correct 7 bit string with an even parity bit as the 8th bit:
```
"01011001" <-- The "1" on the right is the parity bit.
```

In this example, there are three 1-bits. Three is an odd number, and the parity bit is set to `1`. No errors are detected, so return `"0101100"` (7 bits).

Example of a string of ASCII characters:
```
"01011001 01101110 01100000 01010110 10001111 01100011"
```
This should return:
```
"0101100 error 0110000 0101011 error 0110001"
```

def parity_bit(binary):

      return  ' '.join(map(lambda bits : 'error' if bits.count('1')%2 !=0  else bits[:-1] ,binary.split()))


Solve in Python:
In the 2-D world of Flatland, the Circles were having their sports day and wanted to end it with a nice formation. So, they called upon Mr. Sphere from Spaceland for help. Mr Sphere decides to arrange the Circles in square formations. He starts with $N$ Circles and forms the largest possible square using these Circles. He then takes the remaining Circles and repeats the procedure. A square of side $S$ requires $S^2$ Circles to create.
Find the number of squares he will be able to form at the end of the process.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single integer $N$.

-----Output:-----
For each testcase, output a single integer denoting the number of squares.

-----Constraints-----
- $1 \leq T \leq 1000$
- $1 \leq N \leq 1000$

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

85

114

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

4

-----EXPLANATION:-----
Test case 1 : Mr Sphere forms a square of side 9 using 81 Circles and then forms a square of side 2 using the remaining 4.

# cook your dish here
import math
for _ in range(int(input())):
 n=int(input())
 s=0
 while n!=0:
  s+=1
  n-=(int(math.sqrt(n)))**2
 print(s)