Solve in Python:
This is a classic needing (almost) no further introduction.

Given a N x N chess board, place N queens on it so none can attack another: I.e. no other queens can be found horizontally, vertically or diagonally to the current.

On the board below, no further queens can be positioned.

+-+-+
|Q| |
+-+-+
| | |
+-+-+

In this example a queen can be located in position a or position b - but not in both, thereby making (0,0) an invalid first position:
+-+-+-+
|Q| | |
+-+-+-+
| | |a|
+-+-+-+
| |b| |
+-+-+-+

Return value must by an array of N x-positions. That is, the y position is given by the index. For following board, expected answer is `[1, 3, 0, 2]`:

+-+-+-+-+
| |X| | |    x=1, y=0
+-+-+-+-+
| | | |X|    x=3, y=1
+-+-+-+-+
|X| | | |    x=0, y=2
+-+-+-+-+
| | |X| |    x=2, y=3
+-+-+-+-+

Only one solution per N is expected. If no solution can be found, return an empty array. That is, for a 1 x 1 board, the output is [0].

Input is a value positive number (N>0) and can be quite large, so try to make your solution efficient. See sample tests to check how large `N` can be.

Have fun :)

----
Next steps:
 - [N queens puzzle (with one mandatory queen position)](https://www.codewars.com/kata/561bed6a31daa8df7400000e)
 - [N queens problem (with one mandatory queen position) - challenge version](https://www.codewars.com/kata/5985ea20695be6079e000003)

def nQueen(n):
    if n == 1: return [0]
    if n <= 3: return []

    evens = [i for i in range(2, n+1, 2)]
    odds = [i for i in range(1, n+1, 2)]

    if n % 6 == 3:
        evens.remove(2)
        evens.append(2)
        odds.remove(1)
        odds.remove(3)
        odds.append(1)
        odds.append(3)
    elif n % 6 == 2:
        odds[0], odds[1] = 3, 1
        odds.remove(5)
        odds.append(5)

    return [a-1 for a in evens + odds]


Solve in Python:
This is a follow up from my kata Insert Dashes.
Write a function ```insertDashII(num)``` that will insert dashes ('-') between each two odd numbers and asterisk ('\*') between each even numbers in ```num```
For example:
```insertDashII(454793)``` --> 4547-9-3
```insertDashII(1012356895)``` --> 10123-56*89-5

Zero shouldn't be considered even or odd.


Solve in Python:
This is a follow up from my kata The old switcheroo

Write
```python
def encode(str)
```
that takes in a string ```str``` and replaces all the letters with their respective positions in the English alphabet.

```python
encode('abc') == '123'   # a is 1st in English alpabet, b is 2nd and c is 3rd
encode('codewars') == '315452311819'
encode('abc-#@5') == '123-#@5'
```
String are case sensitive.

def encode(string):
    return ''.join(str(ord(c.upper())-64) if c.isalpha() else c for c in string)


Solve in Python:
This is a follow-up from my previous Kata which can be found here: http://www.codewars.com/kata/5476f4ca03810c0fc0000098

This time, for any given linear sequence, calculate the function [f(x)] and return it as a function in Javascript or Lambda/Block in Ruby.

For example:

```python
get_function([0, 1, 2, 3, 4])(5) => 5
get_function([0, 3, 6, 9, 12])(10) => 30
get_function([1, 4, 7, 10, 13])(20) => 61
```

Assumptions for this kata are:
```
The sequence argument will always contain 5 values equal to f(0) - f(4).
The function will always be in the format "nx +/- m", 'x +/- m', 'nx', 'x' or 'm'
If a non-linear sequence simply return 'Non-linear sequence' for javascript, ruby, and python. For C#, throw an ArgumentException.
```

def get_function(sequence):
    slope = sequence[1] - sequence[0]
    for x in range(1,5):
        if sequence[x] - sequence[x-1] != slope:
            return "Non-linear sequence"

    return lambda a : slope * a + sequence[0]


Solve in Python:
This is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on $n$ are greater than in the easy version of the problem.

You are given an array $a$ of $n$ integers (the given array can contain equal elements). You can perform the following operations on array elements:  choose any index $i$ ($1 \le i \le n$) and move the element $a[i]$ to the begin of the array;  choose any index $i$ ($1 \le i \le n$) and move the element $a[i]$ to the end of the array.

For example, if $n = 5$, $a = [4, 7, 2, 2, 9]$, then the following sequence of operations can be performed:   after performing the operation of the first type to the second element, the array $a$ will become $[7, 4, 2, 2, 9]$;  after performing the operation of the second type to the second element, the array $a$ will become $[7, 2, 2, 9, 4]$.

You can perform operations of any type any number of times in any order.

Find the minimum total number of operations of the first and second type that will make the $a$ array sorted in non-decreasing order. In other words, what is the minimum number of operations must be performed so the array satisfies the inequalities $a[1] \le a[2] \le \ldots \le a[n]$.

-----Input-----

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

Each test case starts with a line containing an integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the size of the array $a$.

Then follow $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$) — an array that needs to be sorted by the given operations. The given array can contain equal elements.

The sum of $n$ for all test cases in one test does not exceed $2 \cdot 10^5$.

-----Output-----

For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order.

-----Example-----
Input
9
5
4 7 2 2 9
5
3 5 8 1 7
5
1 2 2 4 5
2
0 1
3
0 1 0
4
0 1 0 0
4
0 1 0 1
4
0...

for _ in range(int(input())):
    n = int(input())
    l = list(map(int,input().split()))
    id = list(zip(l,list(range(n))))
    id.sort()
    val, pos = zip(*id)
    blok = []
    cur = [pos[0]]
    for i in range(1,n):
        if val[i] == val[i-1]:
            cur.append(pos[i])
        else:
            cur.sort()
            blok.append(cur)
            cur = [pos[i]]
    cur.sort()
    blok.append(cur)
    best = 0
    m = len(blok)
    for j in range(m):
        best = max(len(blok[j]), best)
    i = 0
    while True:
        if i >= m-2:
            break
        cyk = min(blok[i+1])
        j = -1
        while j+1 < len(blok[i]) and blok[i][j+1] < cyk:
            j += 1
        su = (j+1)
        ii = i+2
        while ii < m:
            if min(blok[ii]) > max(blok[ii-1]):
                su += len(blok[ii-1])
                ii += 1
            else:
                break
        if ii == m:
            su += len(blok[-1])
            best = max(best, su)
        else:
            xxx = max(blok[ii-1])
            su += len(blok[ii-1])
            inde = len(blok[ii])-1
            while inde >= 0 and blok[ii][inde] >= xxx:
                su += 1
                inde -= 1
            best = max(best,su)
        i = max(i+1, ii-1)
    for i in range(1,m):
        b1 = blok[i];b0 = blok[i-1];l0,l1,i1 = len(b0),len(b1),0
        for ind in range(l0):
            while True:
                if i1 < l1 and b1[i1] <= b0[ind]:i1 += 1
                else:break
            if l1 == i1:break
            best = max(best, (ind+1)+(l1-i1))
    print(n-best)


Solve in Python:
This is a peculiar functioning setup.
Two Tanks are separated from each other by a wall .There is a pipe in the wall which connects  both tanks  which allows flow of water between them . Due to this ,there is change in temperature of both tanks , every minute temperature of Tank with larger temperature among two decreases by one and temperature of Tank  with smaller temperature among two increases by two until equilibrium is reached , But there is a problem .
The pipe can't control this flow of water if there is Non-equilibrium (inequality of temperature  on  both sides )  even after $m$ minutes and the pipe will burst after it , your task is to predict whether the pipe will burst or not .
Note: If equilibrium cannot be reached the process will continue forever.
The initial temperature of Cold Tank is $Tc$ , of Hot Tank it is $Th$.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, three  integers $m, Tc,Th$.

-----Output:-----
For each testcase, output in a single line answer "Yes" if Pipe will burst after m minutes "No" if pipe will not burst.

-----Constraints-----
- $1 \leq T \leq 100000$
- $1 \leq m,Tc,Th \leq 10^9$
- $Tc \leq Th $

-----Sample Input:-----
2
4 5 10
2 2 5

-----Sample Output:-----
Yes
No

# cook your dish here
t=int(input())
while t:
 m,c,h=input().split()
 m=int(m)
 c=int(c)
 h=int(h)

 x=abs(c-h)

 if(x%3!=0):
  print("Yes")

 else:
  if(x//3>m):
   print("Yes")
  else:
   print("No")

 t-=1


Solve in Python:
This is a problem that involves adding numbers to items in a list.
In a list you will have to add the item's remainder when divided by a given divisor to each item.

For example if the item is 40 and the divisor is 3 you would have to add 1 since 40 minus the closest multiple of 3 which is 39 is 1. So the 40 in the list will become 41. You would have to return the modified list in this problem.

For this problem you will receive a divisor called `div` as well as simple list of whole numbers called `nums`. Good luck and happy coding.

# Examples
```python
nums = [2, 7, 5, 9, 100, 34, 32, 0], div = 3
  ==>  [4, 8, 7, 9, 101, 35, 34, 0]

nums = [1000, 999, 998, 997], div = 5
   ==> [1000, 1003, 1001, 999]

nums = [], div = 2
   ==> []
```

**Note:** random tests check lists containing up to 10000 elements.

def solve(a, x):
    return [n + n % x for n in a]


Solve in Python:
This is a question from codingbat

Given an integer n greater than or equal to 0,
create and return an array with the following pattern:

    squareUp(3) => [0, 0, 1, 0, 2, 1, 3, 2, 1]
    squareUp(2) => [0, 1, 2, 1]
    squareUp(4) => [0, 0, 0, 1, 0, 0, 2, 1, 0, 3, 2, 1, 4, 3, 2, 1]
n<=1000.

# Check out my other kata!

Matrix Diagonal Sort OMG
String -> N iterations -> String
String -> X iterations -> String
ANTISTRING
Array - squareUp b!
Matrix - squareUp b!
Infinitely Nested Radical Expressions
pipi Numbers!

def square_up(n):
    return [j if j <= i else 0 for i in range(1, n+1) for j in range(n, 0, -1)]


Solve in Python:
This is a simple game you must have played around with during your school days, calculating FLAMES of you and your crush! Given the names of two people, cancel out the common letters (repeated occurrence of a letter is treated separately, so 2A's in one name and one A in the other would cancel one A in each name), count the total number of remaining letters (n) and repeatedly cut the letter in the word FLAMES which hits at the nth number when we count from F in cyclic manner.

For example:
NAME 1: SHILPA
NAME 2: AAMIR
After cutting the common letters:
NAME 1: SHILPA
NAME 2: AAMIR
Total number of letters left=7
FLAMES, start counting from F : 1=F, 2=L, 3=A, 4=M, 5=E, 6=S,7=F...So cut F
FLAMES: repeat this process with remaining letters of FLAMES for number 7 (start count from the letter after
the last letter cut) . In the end, one letter remains. Print the result corresponding to the last letter:
F=FRIENDS
L=LOVE
A=ADORE
M=MARRIAGE
E=ENEMIES
S=SISTER

-----Input-----
The no. of test cases (<100)
two names (may include spaces) for each test case.

-----Output-----
FLAMES result (Friends/Love/...etc) for each test case

-----Example-----
Input:
2
SHILPA
AAMIR
MATT
DENISE

Output:
ENEMIES
LOVE

By:
Chintan, Asad, Ashayam, Akanksha

import sys

def main():
    s = sys.stdin.readline
    t = int(s())
    for i in range(t):
        name = s().strip().lower()
        if ' ' in name:
            name = name.replace(' ', '')
        crush = s().strip().lower()
        if ' ' in crush:
            crush = crush.replace(' ', '')
        namecounter = {}
        crushcounter = {}
        for letter in name:
            if letter in namecounter:
                namecounter[letter] += 1
            else:
                namecounter[letter] = 1

        for letter in crush:
            if letter in crushcounter:
                crushcounter[letter] += 1
            else:
                crushcounter[letter] = 1
        counter = 0
        already = []
        for letter in name:
            if letter in crush:
                if letter not in already:
                    if namecounter[letter] == crushcounter[letter]:
                        already.append(letter)
                        continue
                    else:
                        counter += abs(namecounter[letter]-crushcounter[letter])
            else:
                counter += 1
            already.append(letter)
        for letter in crush:
            if letter not in already:
                counter += 1
        values = {1: 'FRIENDS', 2: 'LOVE', 3: 'ADORE', 4: 'MARRIAGE', 5: 'ENEMIES', 6: 'SISTER'}
        result = 0
        for i in range(1, 6+1):
                result = (result+counter)%i
        print(values[result+1])

def __starting_point():
    main()
__starting_point()


Solve in Python:
This is a spin off of my first [kata](http://www.codewars.com/kata/56bc28ad5bdaeb48760009b0). You are given a list of character sequences as a comma separated string. Write a function which returns another string containing all the character sequences except the first and the last ones, separated by spaces. If the input string is empty, or the removal of the first and last items would cause the string to be empty, return a null value.

def array(string):
  return " ".join(string.split(",")[1:-1]) or None


Solve in Python:
This is a very simply formulated task. Let's call an integer number `N` 'green' if `N²` ends with all of the digits of `N`. Some examples:

`5` is green, because `5² = 25` and `25` ends with `5`.

`11` is not green, because `11² = 121` and `121` does not end with `11`.

`376` is green, because `376² = 141376` and `141376` ends with `376`.

Your task is to write a function `green` that returns `n`th green number, starting with `1` - `green (1) == 1`

---

## Data range

```if:haskell
`n <= 4000` for Haskell
```
```if:java
`n <= 5000` for Java
```
```if:python
`n <= 5000` for Python
```
```if:javascript
`n <= 3000` for JavaScript

Return values should be `String`s, and should be exact. A BigNum library is recommended.
```

def green(n):
    vec = [1, 5, 6]
    m1 = 5
    m2 = 6
    tot = 3
    h = 0
    while tot < n:
        s1 = str(m1)
        s2 = str(m2)
        m1 = morph(m1)
        m2 = morph(m2)
        (tot, vec, h) = recover(str(m1), s1, str(m2), s2, vec, tot, h)
    vec.sort()
    return vec[n - 1]

def recover(p, s, r, q, vec, tot, h):
    d = len(p) - len(s)
    d2 = len(r) - len(q)
    for i in range(0, d):
        if p[d - 1 - i] != '0':
            vec.append(int(p[d - 1 - i: d] + s))
            tot += 1
        if r[d2 - 1 - i + h] != '0':
            vec.append(int(r[d2 - 1 - i + h: d2 + h] + q[h:]))
            tot += 1
    return tot, vec, len(r) - len(p)

def morph(m):
    return (3 * m * m - 2 * m * m * m) % 10 ** (2 * len(str(m)))


Solve in Python:
This is an easier version of the next problem. In this version, $q = 0$.

A sequence of integers is called nice if its elements are arranged in blocks like in $[3, 3, 3, 4, 1, 1]$. Formally, if two elements are equal, everything in between must also be equal.

Let's define difficulty of a sequence as a minimum possible number of elements to change to get a nice sequence. However, if you change at least one element of value $x$ to value $y$, you must also change all other elements of value $x$ into $y$ as well. For example, for $[3, 3, 1, 3, 2, 1, 2]$ it isn't allowed to change first $1$ to $3$ and second $1$ to $2$. You need to leave $1$'s untouched or change them to the same value.

You are given a sequence of integers $a_1, a_2, \ldots, a_n$ and $q$ updates.

Each update is of form "$i$ $x$" — change $a_i$ to $x$. Updates are not independent (the change stays for the future).

Print the difficulty of the initial sequence and of the sequence after every update.

-----Input-----

The first line contains integers $n$ and $q$ ($1 \le n \le 200\,000$, $q = 0$), the length of the sequence and the number of the updates.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 200\,000$), the initial sequence.

Each of the following $q$ lines contains integers $i_t$ and $x_t$ ($1 \le i_t \le n$, $1 \le x_t \le 200\,000$), the position and the new value for this position.

-----Output-----

Print $q+1$ integers, the answer for the initial sequence and the answer after every update.

-----Examples-----
Input
5 0
3 7 3 7 3

Output
2

Input
10 0
1 2 1 2 3 1 1 1 50 1

Output
4

Input
6 0
6 6 3 3 4 4

Output
0

Input
7 0
3 3 1 3 2 1 2

Output
4

n, q = map(int, input().split())
A = list(map(int, input().split()))
left = {}
right = {}
for i in range(n):
    if A[i] not in left:
        left[A[i]] = i
    right[A[i]] = i
E = []
for elem in left:
    E.append([left[elem], -1])
    E.append([right[elem], 1])
E.sort()
u = 0
b = 0
cntr = {}
ans = 0
for i in range(n):
    while u < len(E) and E[u][0] == i:
        b -= E[u][1]
        u += 1
    if A[i] not in cntr:
        cntr[A[i]] = 0
    cntr[A[i]] += 1
    if b == 0:
        s = 0
        m = 0
        for iss in cntr:
            s += cntr[iss]
            m = max(m, cntr[iss])
        ans += s - m
        cntr = {}
print(ans)


Solve in Python:
This is an easier version of the next problem. The difference is only in constraints.

You are given a rectangular $n \times m$ matrix $a$. In one move you can choose any column and cyclically shift elements in this column. You can perform this operation as many times as you want (possibly zero). You can perform this operation to a column multiple times.

After you are done with cyclical shifts, you compute for every row the maximal value in it. Suppose that for $i$-th row it is equal $r_i$. What is the maximal possible value of $r_1+r_2+\ldots+r_n$?

-----Input-----

The first line contains an integer $t$ ($1 \le t \le 40$), the number of test cases in the input.

The first line of each test case contains integers $n$ and $m$ ($1 \le n \le 4$, $1 \le m \le 100$) — the number of rows and the number of columns in the given matrix $a$.

Each of the following $n$ lines contains $m$ integers, the elements of $a$ ($1 \le a_{i, j} \le 10^5$).

-----Output-----

Print $t$ integers: answers for all test cases in the order they are given in the input.

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

Output
12
29

-----Note-----

In the first test case, you can shift the third column down by one, this way there will be $r_1 = 5$ and $r_2 = 7$.

In the second case you can don't rotate anything at all, this way there will be $r_1 = r_2 = 10$ and $r_3 = 9$.

q = int(input())
for rquer in range(q):
	c, r = list(map(int, input().split()))
	matt = [list(map(int,input().split())) for i in range(c)]
	mat = [[matt[i][j] for i in range(c)] for j in range(r)]
	for i in range(r):
		mat[i].append(max(mat[i]))
		mat[i].reverse()
	mat.sort()
	mat.reverse()
	work = mat[:min(4, r)]
	for t in work:
		t.pop(0)
	r = min(4, r)
	wyn = 0
	for num in range(c**r):
		shif = [(num//(c**i))%c for i in range(r)]
		new = 0
		for i in range(c):
			kol = [work[j][(i + shif[j])%c] for j in range(r)]
			new += max(kol)
		wyn = max(wyn, new)
	print(wyn)


Solve in Python:
This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on $n$ are less than in the hard version of the problem.

You are given an array $a$ of $n$ integers (there are no equals elements in the array). You can perform the following operations on array elements:  choose any index $i$ ($1 \le i \le n$) and move the element $a[i]$ to the begin of the array;  choose any index $i$ ($1 \le i \le n$) and move the element $a[i]$ to the end of the array.

For example, if $n = 5$, $a = [4, 7, 2, 3, 9]$, then the following sequence of operations can be performed:   after performing the operation of the first type to the second element, the array $a$ will become $[7, 4, 2, 3, 9]$;  after performing the operation of the second type to the second element, the array $a$ will become $[7, 2, 3, 9, 4]$.

You can perform operations of any type any number of times in any order.

Find the minimum total number of operations of the first and second type that will make the $a$ array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities $a[1] \le a[2] \le \ldots \le a[n]$.

-----Input-----

The first line contains a single integer $t$ ($1 \le t \le 100$) — the number of test cases in the test. Then $t$ test cases follow.

Each test case starts with a line containing an integer $n$ ($1 \le n \le 3000$) — length of the array $a$.

Then follow $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct.

The sum of $n$ for all test cases in one test does not exceed $3000$.

-----Output-----

For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order.

-----Example-----
Input
4
5
4 7 2 3 9
5
3 5 8 1 7
5
1 4 5 7 12
4
0 2 1 3

Output
2
2
0
2

-----Note-----

In the...

t = int(input())
for _ in range(t):
    n = int(input())
    a = list(map(int, input().split()))
    for i in range(n):
        a[i] = a[i] * n + i
    a.sort()
    p = [0 for _ in range(n)]
    for i in range(n):
        p[a[i]%n] = i
    q = [0 for _ in range(n)]
    for i in range(n):
        q[p[i]] = i
    cnt = 1
    m = 0
    for i in range(1, n):
        if q[i-1] < q[i]:
            cnt += 1
        else:
            m = max(cnt, m)
            cnt = 1
    m = max(cnt, m)
    print(n - m)


Solve in Python:
This is another problem about Indraneel's library. His library has one long shelf. His books are numbered and he identifies the books by their number. Each book has a distinct number.
He has lost many books, since many of his friends borrow his books and never bother to return them. He does not want to lose any more books and has decided to keep a record of all books that he lends to his friends. To make the task of borrowing a book a little difficult, he has given the following instructions to his friends: when they borrow a book, they must record in a register its position from the left among the books currently on the shelf.
Suppose there are $5$ books in the library and they are arranged as follows:
261421532614215326 \quad 1 \quad 42 \quad 15 \quad 3
If someone walks in and borrows the book $42$, then he will record $3$ in the register because this book is the third from the left on the shelf. Now the shelf looks like this:
26115326115326 \quad 1 \quad 15 \quad 3
If the next person borrow the book $3$, he writes down $4$ in the register since this is currently the fourth book from the left on the shelf, and so on.
Indraneel knows the initial arrangement of the books in his library at the time that he introduced the register system. After a while he examines his register and would like to know which books have been borrowed. Your task is to write a program to help Indraneel solve this problem.

-----Input:-----
The first line of the input contains a single integer $M$ indicating the number of books in Indraneel's library. The next line contains $M$ distinct positive integers describing the sequence in which the books are arranged on the library shelf. The third line of input contains a single integer $N$ indicating the number of entries in the register. This, in turn, is followed by $N$ lines (lines $4$ to $N+3$), each containing one positive integer. The integer on line $3+i$ indicates the position from left of the book ith book borrowed. (You may assume that the number on line $3+i$ is at most...

n=int(input())
L=list(map(int,input().split()))
friends=int(input())
li=[]
for _ in range(friends):
    fB=L.pop(int(input())-1)
    li.append(fB)
for i in li:
    print(i)


Solve in Python:
This is now a little serie :)

Funny Dots

You will get two Integer n (width) and m (height) and your task is to draw following pattern. Each line is seperated with '\n'.

Both integers are equal or greater than 1. No need to check for invalid parameters.

e.g.:

                                          +---+---+---+
            +---+                         | o | o | o |
dot(1,1) => | o |          dot(3,2) =>    +---+---+---+
            +---+                         | o | o | o |
                                          +---+---+---+

 Serie: ASCII Fun

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


Solve in Python:
This is one more story about our old friend, the Despotic King. Once every year, it was customary for the king to give audience to the rich merchants of his country in a large hall. On that day, the merchants were ushered in to meet the king one by one and after paying their respects to the king they were seated in the auditorium.
It was the job of the minister to introduce each merchant, as he arrived, to the others in the hall. He would announce his name and his wealth. However, our quirky king demanded that in addition, he should also announce the rank of the merchant among all those in the hall (at the time of his arrival) in terms of his wealth.
For example, let us suppose that the wealth of the 6 merchants who met the king (in the order in which they arrived) is given by the sequence
78246840398978246840398978 \quad 24 \quad 68 \quad 40 \quad 39 \quad 89
Then, clearly the first merchant is the richest in the hall when he enters it (since there are no others in the hall) and so his rank is $1$. Since $24 < 78$ the rank of the second merchant when he enters the hall is $2$. The rank of the third merchant is also $2$ since $24 < 68 < 78$. The rank of the fourth merchant is $3$ since $24 < 40 < 68 < 78$, the rank of the fifth merchant is $4$ since $24 < 39 < 40 < 68 < 78$ and finally the rank of the sixth merchant is $1$ since $24 < 39 < 40 < 68 < 78 < 89$. The sequence of ranks announced by the minister would thus be:
1223411223411 \quad 2 \quad 2 \quad 3 \quad 4 \quad 1
Your task is to write a program that takes as input a sequence of distinct positive integers indicating the wealth of the merchants in the order in which they visit the king and outputs the sequence of ranks announced by the minister.

-----Input:-----
The first line contains a single integer $N$ indicating the number of merchants. The next $N$ lines (line $2,...,N+1$) describe the wealth of these $N$ merchants. Line $i+1$ contains a single positive integer indicating the wealth of the $i^{th}$ merchant to enter the...

arr=[]
n=int(input())
for i in range(n):
    a=int(input())
    arr.append(a)
    arr.sort()
    p=arr.index(a)
    print((i-p)+1)


Solve in Python:
This is probably the simplest problem ever. You just need to count the number of ordered triples of different numbers (X1, X2, X3), where Xi could be any positive integer from 1 to Ni, inclusive (i = 1, 2, 3).
No, wait. I forgot to mention that numbers N1, N2, N3 could be up to 1018. Well, in any case it is still quite simple :)
By the way, because of this the answer could be quite large. Hence you should output it modulo 109 + 7. That is you need to find the remainder of the division of the number of required triples by 109 + 7.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The only line of each test case contains three space-separated integers N1, N2, N3.

-----Output-----
For each test case, output a single line containing the number of required triples modulo 109 + 7.

-----Constraints-----
- 1 ≤ T ≤ 1000
- 1 ≤ Ni ≤ 1018

-----Example-----
Input:
5
3 3 3
2 4 2
1 2 3
25 12 2012
1 1 2013

Output:
6
4
1
578880
0

-----Explanation-----
Example case 1. We have the following triples composed of different numbers up to 3:
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)
Example case 2. Here the triples are:
(1, 3, 2)
(1, 4, 2)
(2, 3, 1)
(2, 4, 1)
Example case 3. Here the only triple is (1, 2, 3).
Example case 4. Merry Christmas!
Example case 5. ... and Happy New Year! By the way here the answer is zero since the only choice for X1 and for is X2 is 1, so any such triple will have equal numbers.

m = 10**9 + 7
t=int(input())
for i in range(t):
 ls = list(map(int,input().split()))
 ls.sort()
 print( (ls[0]*(ls[1]-1)*(ls[2]-2 ))%m)


Solve in Python:
This is related to my other Kata about cats and dogs.

# Kata Task

I have a cat and a dog which I got as kitten / puppy.

I forget when that was, but I do know their current ages as `catYears` and `dogYears`.

Find how long I have owned each of my pets and return as a list [`ownedCat`, `ownedDog`]

NOTES:
* Results are truncated whole numbers of "human" years

## Cat Years

* `15` cat years for first year
* `+9` cat years for second year
* `+4` cat years for each year after that

## Dog Years

* `15` dog years for first year
* `+9` dog years for second year
* `+5` dog years for each year after that

**References**

* http://www.catster.com/cats-101/calculate-cat-age-in-cat-years
* http://www.slate.com/articles/news_and_politics/explainer/2009/05/a_dogs_life.html

def owned_cat_and_dog(cy, dy):
    cat = 0 if cy < 15 else 1 if cy < 24 else 2 + (cy - 24) // 4
    dog = 0 if dy < 15 else 1 if dy < 24 else 2 + (dy - 24) // 5
    return [cat, dog]


Solve in Python:
This is simple version of harder [Square Sums](/kata/square-sums).

# Square sums

Write function `square_sums_row` (or `squareSumsRow`/`SquareSumsRow` depending on language rules) that, given integer number `N` (in range `2..43`), returns array of integers `1..N` arranged in a way, so sum of each 2 consecutive numbers is a square.

Solution is valid if and only if following two criterias are met:
1. Each number in range `1..N` is used once and only once.
2. Sum of each 2 consecutive numbers is a perfect square.

### Example
For N=15 solution could look like this:

`[ 9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8 ]`

### Verification

1. All numbers are used once and only once. When sorted in ascending order array looks like this:

`[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]`

2. Sum of each 2 consecutive numbers is a perfect square:

```
   16    16     16     16     16     16     16
   /+\   /+\    /+\    /+\    /+\    /+\    /+\
[ 9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8 ]
      \+/    \+/    \+/    \+/    \+/    \+/    \+/
       9     25      9     25      9     25      9

9 = 3*3
16 = 4*4
25 = 5*5
```

If there is no solution, return `false` (or, `None` in scala). For example if `N=5`, then numbers `1,2,3,4,5` cannot be put into square sums row: `1+3=4`, `4+5=9`, but
`2` has no pairs and cannot link `[1,3]` and `[4,5]`

# Have fun!

Harder version of this Kata is [here](/kata/square-sums).

def square_sums_row(n):
    r=[]
    def dfs(r):
        if len(r)==n:return 1
        for i in range(1,n+1):
            if not len(r) or (i not in r and not(i+r[-1])**.5%1):
                r.append(i)
                if dfs(r):return 1
                r.pop()
        return 0
    return r if dfs(r) else 0


Solve in Python:
This is the easier version of the problem. In this version, $1 \le n \le 10^5$ and $0 \le a_i \le 1$. You can hack this problem only if you solve and lock both problems.

Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare $n$ boxes of chocolate, numbered from $1$ to $n$. Initially, the $i$-th box contains $a_i$ chocolate pieces.

Since Bob is a typical nice guy, he will not send Alice $n$ empty boxes. In other words, at least one of $a_1, a_2, \ldots, a_n$ is positive. Since Alice dislikes coprime sets, she will be happy only if there exists some integer $k > 1$ such that the number of pieces in each box is divisible by $k$. Note that Alice won't mind if there exists some empty boxes.

Charlie, Alice's boyfriend, also is Bob's second best friend, so he decides to help Bob by rearranging the chocolate pieces. In one second, Charlie can pick up a piece in box $i$ and put it into either box $i-1$ or box $i+1$ (if such boxes exist). Of course, he wants to help his friend as quickly as possible. Therefore, he asks you to calculate the minimum number of seconds he would need to make Alice happy.

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 10^5$) — the number of chocolate boxes.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 1$) — the number of chocolate pieces in the $i$-th box.

It is guaranteed that at least one of $a_1, a_2, \ldots, a_n$ is positive.

-----Output-----

If there is no way for Charlie to make Alice happy, print $-1$.

Otherwise, print a single integer $x$ — the minimum number of seconds for Charlie to help Bob make Alice happy.

-----Examples-----
Input
3
1 0 1

Output
2

Input
1
1

Output
-1

import math
import sys
input = sys.stdin.readline
n = int(input())
a = [int(_) for _ in input().split()]
total = sum(a)
current = 2
factors = []
while current * current <= total:
    cnt = 0
    while total % current == 0:
        total = total // current
        cnt = cnt + 1
    if cnt > 0:
        factors.append(current)
    current = current + 1
if total > 1:
    factors.append(total)

ans = sum(a) * n * n
for i in factors:
    total, moves = 0, 0
    for j in a:
        total += j
        moves += min(total % i, i - (total % i))
    ans = min(ans, moves)
if len(factors) == 0: ans = -1
print(ans)


Solve in Python:
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.

Pikachu is a cute and friendly pokémon living in the wild pikachu herd.

But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.

First, Andrew counted all the pokémon — there were exactly $n$ pikachu. The strength of the $i$-th pokémon is equal to $a_i$, and all these numbers are distinct.

As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $b$ from $k$ indices such that $1 \le b_1 < b_2 < \dots < b_k \le n$, and his army will consist of pokémons with forces $a_{b_1}, a_{b_2}, \dots, a_{b_k}$.

The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$.

Andrew is experimenting with pokémon order. He performs $q$ operations. In $i$-th operation Andrew swaps $l_i$-th and $r_i$-th pokémon.

Note: $q=0$ in this version of the task.

Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.

Help Andrew and the pokémon, or team R will realize their tricky plan!

-----Input-----

Each test contains multiple test cases.

The first line contains one positive integer $t$ ($1 \le t \le 10^3$) denoting the number of test cases. Description of the test cases follows.

The first line of each test case contains two integers $n$ and $q$ ($1 \le n \le 3 \cdot 10^5, q = 0$) denoting the number of pokémon and number of operations respectively.

The second line contains $n$ distinct positive integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$) denoting the strengths of the pokémon.

$i$-th of the last $q$ lines contains two positive integers $l_i$ and $r_i$ ($1 \le l_i...

INF = 10 ** 15

for _ in range(int(input())):
    n, q = tuple(map(int, input().split()))
    arr = list(map(int, input().split()))

    a = -INF
    b = 0
    for i in arr:
        if a == -INF:
            c = 0
            d = i
        else:
            c = b - i
            d = a + i
        a, b = max(a, c), max(b, d)

    print(max(a, b))


Solve in Python:
This is the easy version of the problem. The difference between the versions is the constraint on $n$ and the required number of operations. You can make hacks only if all versions of the problem are solved.

There are two binary strings $a$ and $b$ of length $n$ (a binary string is a string consisting of symbols $0$ and $1$). In an operation, you select a prefix of $a$, and simultaneously invert the bits in the prefix ($0$ changes to $1$ and $1$ changes to $0$) and reverse the order of the bits in the prefix.

For example, if $a=001011$ and you select the prefix of length $3$, it becomes $011011$. Then if you select the entire string, it becomes $001001$.

Your task is to transform the string $a$ into $b$ in at most $3n$ operations. It can be proved that it is always possible.

-----Input-----

The first line contains a single integer $t$ ($1\le t\le 1000$)  — the number of test cases. Next $3t$ lines contain descriptions of test cases.

The first line of each test case contains a single integer $n$ ($1\le n\le 1000$)  — the length of the binary strings.

The next two lines contain two binary strings $a$ and $b$ of length $n$.

It is guaranteed that the sum of $n$ across all test cases does not exceed $1000$.

-----Output-----

For each test case, output an integer $k$ ($0\le k\le 3n$), followed by $k$ integers $p_1,\ldots,p_k$ ($1\le p_i\le n$). Here $k$ is the number of operations you use and $p_i$ is the length of the prefix you flip in the $i$-th operation.

-----Example-----
Input
5
2
01
10
5
01011
11100
2
01
01
10
0110011011
1000110100
1
0
1

Output
3 1 2 1
6 5 2 5 3 1 2
0
9 4 1 2 10 4 1 2 1 5
1 1

-----Note-----

In the first test case, we have $01\to 11\to 00\to 10$.

In the second test case, we have $01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100$.

In the third test case, the strings are already the same. Another solution is to flip the prefix of length $2$, which will leave $a$ unchanged.

import sys
input = sys.stdin.readline
from collections import deque

t=int(input())
for tests in range(t):
    n=int(input())

    a=input().strip()
    b=input().strip()

    Q=deque(a)

    L=[]
    while Q:
        L.append(Q.popleft())

        if Q:
            L.append(Q.pop())

    ANS=[]
    for i in range(n):
        if i%2==0:
            if L[i]==b[-1-i]:
                ANS.append(1)
        else:
            if L[i]!=b[-1-i]:
                ANS.append(1)

        ANS.append(n-i)

    print(len(ANS),*ANS)


Solve in Python:
This is the easy version of the problem. The only difference between easy and hard versions is the constraint of $m$. You can make hacks only if both versions are solved.

Chiori loves dolls and now she is going to decorate her bedroom![Image]

As a doll collector, Chiori has got $n$ dolls. The $i$-th doll has a non-negative integer value $a_i$ ($a_i < 2^m$, $m$ is given). Chiori wants to pick some (maybe zero) dolls for the decoration, so there are $2^n$ different picking ways.

Let $x$ be the bitwise-xor-sum of values of dolls Chiori picks (in case Chiori picks no dolls $x = 0$). The value of this picking way is equal to the number of $1$-bits in the binary representation of $x$. More formally, it is also equal to the number of indices $0 \leq i < m$, such that $\left\lfloor \frac{x}{2^i} \right\rfloor$ is odd.

Tell her the number of picking ways with value $i$ for each integer $i$ from $0$ to $m$. Due to the answers can be very huge, print them by modulo $998\,244\,353$.

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n \le 2 \cdot 10^5$, $0 \le m \le 35$)  — the number of dolls and the maximum value of the picking way.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i < 2^m$)  — the values of dolls.

-----Output-----

Print $m+1$ integers $p_0, p_1, \ldots, p_m$  — $p_i$ is equal to the number of picking ways with value $i$ by modulo $998\,244\,353$.

-----Examples-----
Input
4 4
3 5 8 14

Output
2 2 6 6 0
Input
6 7
11 45 14 9 19 81

Output
1 2 11 20 15 10 5 0

MOD = 998244353
BOUND = 19

n, m = list(map(int, input().split()))
l = list(map(int,input().split()))

basis = []
for p in range(m-1,-1,-1):
    p2 = pow(2,p)
    nex = -1
    for i in range(n):
        if l[i] >= p2:
            nex = l[i]
            break
    if nex != -1:
        basis.append(nex)
        for i in range(n):
            if l[i] >= p2:
                l[i] ^= nex

extra = n - len(basis)

def add(a, b):
    out = [0] * (max(len(a), len(b)))
    for i in range(len(a)):
        out[i] = a[i]
    for i in range(len(b)):
        out[i] += b[i]
        out[i] %= MOD
    return out

def addSh(a, b):
    out = [0] * (max(len(a) + 1, len(b)))
    for i in range(len(a)):
        out[i + 1] = a[i]
    for i in range(len(b)):
        out[i] += b[i]
        out[i] %= MOD
    return out

i = 0
curr = dict()
curr[0] = [1]
for p in range(m-1,-1,-1):
    p2 = pow(2,p)
    if i < len(basis) and basis[i] >= p2:
        currN = dict(curr)
        for v in curr:
            if v ^ basis[i] not in currN:
                currN[v ^ basis[i]] = [0]
            currN[v ^ basis[i]] = add(curr[v], currN[v ^ basis[i]])
        curr = currN
        i += 1

    currN = dict(curr)
    for v in curr:
        if v >= p2:
            if v ^ p2 not in currN:
                currN[v ^ p2] = [0]
            currN[v ^ p2] = addSh(curr[v], currN[v ^ p2])
            del currN[v]
    curr = currN

out = curr[0]
while len(out) < m + 1:
    out.append(0)
for i in range(m + 1):
    out[i] *= pow(2, extra, MOD)
    out[i] %= MOD
print(' '.join(map(str,out)))


Solve in Python:
This is the first step to understanding FizzBuzz.

Your inputs:
a positive integer, n, greater than or equal to one.
n is provided, you have NO CONTROL over its value.

Your expected output is an array of positive integers from 1 to n (inclusive).

Your job is to write an algorithm that gets you from the input to the output.

def pre_fizz(n):
    numlist = []
    for shit in range(0, n):
        numlist.append(shit + 1)
    return numlist


Solve in Python:
This is the hard version of the problem. The difference between the versions is the constraint on $n$ and the required number of operations. You can make hacks only if all versions of the problem are solved.

There are two binary strings $a$ and $b$ of length $n$ (a binary string is a string consisting of symbols $0$ and $1$). In an operation, you select a prefix of $a$, and simultaneously invert the bits in the prefix ($0$ changes to $1$ and $1$ changes to $0$) and reverse the order of the bits in the prefix.

For example, if $a=001011$ and you select the prefix of length $3$, it becomes $011011$. Then if you select the entire string, it becomes $001001$.

Your task is to transform the string $a$ into $b$ in at most $2n$ operations. It can be proved that it is always possible.

-----Input-----

The first line contains a single integer $t$ ($1\le t\le 1000$)  — the number of test cases. Next $3t$ lines contain descriptions of test cases.

The first line of each test case contains a single integer $n$ ($1\le n\le 10^5$)  — the length of the binary strings.

The next two lines contain two binary strings $a$ and $b$ of length $n$.

It is guaranteed that the sum of $n$ across all test cases does not exceed $10^5$.

-----Output-----

For each test case, output an integer $k$ ($0\le k\le 2n$), followed by $k$ integers $p_1,\ldots,p_k$ ($1\le p_i\le n$). Here $k$ is the number of operations you use and $p_i$ is the length of the prefix you flip in the $i$-th operation.

-----Example-----
Input
5
2
01
10
5
01011
11100
2
01
01
10
0110011011
1000110100
1
0
1

Output
3 1 2 1
6 5 2 5 3 1 2
0
9 4 1 2 10 4 1 2 1 5
1 1

-----Note-----

In the first test case, we have $01\to 11\to 00\to 10$.

In the second test case, we have $01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100$.

In the third test case, the strings are already the same. Another solution is to flip the prefix of length $2$, which will leave $a$ unchanged.


Solve in Python:
This is the performance edition of [this kata](https://www.codewars.com/kata/ulam-sequences). If you didn't do it yet, you should begin there.

---

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

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

* Here, the first term after the initial `1, 2` is obviously `3` since `3=1+2`.
* The next term is `4=1+3` (we don't have to worry about `4=2+2` since it is a sum of a single term instead of two distinct terms)
* `5` is not a member of the sequence since it is representable in two ways: `5=1+4=2+3`, but `6=2+4` is a member (since `3+3` isn't a valid calculation).

You'll have to write a code that creates an Ulam Sequence starting with `u0`, `u1` and containing `n` terms.

---

# ___The pitfall...___

While the passing solutions of the first version could have a time complexity of O(N^(3)) (or even O(N^(4))!!), with 20 tests up to 100 terms only, here you'll have to manage generation of sequences up to 1500 terms before time out.

___Inputs:___

* `u0` and `u1`: integers, greater than or equal to 1
* `n`: integer greater than 1, length of the returned list

___Configuration of the tests:___

```if:python
* 6 small fixed tests
* 20 random tests on small sequences (10 to 30 terms)
* 13 large random tests (1500 terms)
```
```if:ruby
* 6 small fixed tests
* 20 random tests on small sequences (10 to 30 terms)
* 16 large random tests (1500 terms)
```
```if:javascript,go
* 6 small fixed tests
* 40 random tests on small sequences (10 to 30 terms)
* 30 large random tests (2450 terms)
```

---

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

def ulam_sequence(u, v, n):
    lst, seq, ex, q = [], 1, 1, 1 << v | 1 << u  # Put u and v into queue
    for _ in range(n):                           # Repeat n times
        w = q & -q                               # Take the smallest candidate
        l = w.bit_length() - 1                   # and its value
        s = seq << l                             # Generate its sums with all previous values
        seq |= w                                 # Append it afterwards to the sequence
        lst.append(l)                            # and to the list
        ex |= s & q                              # Update excluded values if any is already in queue
        q |= s                                   # Put previous sums into queue
        q &= ~ex                                 # Remove excluded values from queue
    return lst                                   # Return sequence list


Solve in Python:
This is the performance version of [this kata](https://www.codewars.com/kata/59afff65f1c8274f270020f5).

---

Imagine two rings with numbers on them. The inner ring spins clockwise and the outer ring spins anti-clockwise. We start with both rings aligned on 0 at the top, and on each move we spin each ring by 1. How many moves will it take before both rings show the same number at the top again?

The inner ring has integers from 0 to innerMax and the outer ring has integers from 0 to outerMax, where innerMax and outerMax are integers >= 1.

```
e.g. if innerMax is 2 and outerMax is 3 then after
1 move: inner = 2, outer = 1
2 moves: inner = 1, outer = 2
3 moves: inner = 0, outer = 3
4 moves: inner = 2, outer = 0
5 moves: inner = 1, outer = 1
Therefore it takes 5 moves for the two rings to reach the same number
Therefore spinningRings(2, 3) = 5
```
```
e.g. if innerMax is 3 and outerMax is 2 then after
1 move: inner = 3, outer = 1
2 moves: inner = 2, outer = 2
Therefore it takes 2 moves for the two rings to reach the same number
spinningRings(3, 2) = 2
```

---

Test input range:

- `100` tests with `1 <= innerMax, outerMax <= 10000`
- `400` tests with `1 <= innerMax, outerMax <= 2^48`

def spinning_rings(inner_max, outer_max):

    i = inner_max+1
    j = outer_max+1

    x = 1
    while x < i*j:
        a = -x % i
        b = x % j
        if a == b:
            return x
        elif a > b:
            if a > j:
                x += a-j
            else:
                x+= max((a-b)//2,1)
        elif b > a:
            if b > i:
                x+= j-b
            else:
                x+= max(min(j-b,a),1)


Solve in Python:
This is the second part of a two-part challenge. See [part I](https://www.codewars.com/kata/587387d169b6fddc16000002) if you haven't done so already.
The problem is the same, only with longer lists and larger values.

Imagine you have a number of jobs to execute. Your workers are not permanently connected to your network, so you have to distribute all your jobs in the beginning. Luckily, you know exactly how long each job is going to take.

Let
```
x = [2,3,4,6,8,2]
```
be the amount of time each of your jobs is going to take.

Your task is to write a function ```splitlist(x)```, that will return two lists ```a``` and ```b```, such that ```abs(sum(a)-sum(b))``` is minimised.

One possible solution to this example would be
```
a=[2, 4, 6]
b=[3, 8, 2]
```
with  ```abs(sum(a)-sum(b)) == 1```.

The order of the elements is not tested, just make sure that you minimise ```abs(sum(a)-sum(b))``` and that ```sorted(a+b)==sorted(x)```.

You may assume that ```len(x)<=40``` and ```0<=x[i]<=1000```.

#Re-use of my  dynamic programing approach for spliting the workload part I
#Given a set S of n non-negative integers:
# 1) make a partition of S with exactly two subsets A,B of S, such that the absolute
#    difference of the elements of each set is minimized

#To solve this problem, all we need to do is use the general subset sum program, but
# set the target sum to S/2 where S is the sum of all of the elements in the list
from collections import Counter     #for differencing lists with (possible) duplicates

#Build the dynamic programing table:  Column are the sums, and rows are the subsets
#   DP[i][j] == True if and only if there exists a subset of {a[0],...,a[i-1]} such
#               that the a[0]+...+a[i-1]==j
# Row i is the subset {a[0],...,a[i-1]}
# Col j is a number (representing a sum)
#The function additionally builds a 'parent' table that is used to determine
# the optimal path (which will allow us to get the elements in the subsets)
def getdDPTable( numList, sizeList, targetSum):

    numRows = sizeList + 1       #to account for empty set, we need +1
    numCols  = targetSum + 1     #to account for zero, we need +1

    #initialize both tables
    dp     = [ [False for _ in range(numCols)] for _ in range(numRows) ]
    parent = [ [ []   for _ in range(numCols)] for _ in range(numRows) ]

    #The sum of 0 can be achieved by selecting no elements from each possible subsets
    #  That is, it is true we can always acheive the sum of 0 from any possible subset
    for r in range(numRows):
        dp[r][0] = True

    #increasing in rows, and from left to right wrt columns, we build the rest
    # of the DP table row i corresponds to the set {a_0,...,a_i}, column j
    # corresponds to the target sum j.  If d[i][j] is true, that means there
    # exists a subset of  {a_0,...,a_i} whose elemenst sum to j
    for r in range(1, numRows):
        for c in range(1, numCols):
            if c < numList[r-1]:            #on row r, current column is less than numList[r-1]
                dp[r][c] =...


Solve in Python:
This is the simple version of Fastest Code series. If you need some challenges, please try the [Performance version](http://www.codewars.com/kata/5714594d2817ff681c000783)

## Task:

Give you a number array ```numbers``` and a number ```c```.

Find out a pair of numbers(we called them number a and number b) from the array ```numbers```, let a*b=c, result format is an array ```[a,b]```

The array ```numbers``` is a sorted array, value range: `-100...100`

The result will be the first pair of numbers, for example,```findAB([1,2,3,4,5,6],6)``` should return ```[1,6]```, instead of ```[2,3]```

Please see more example in testcases.

### Series:
 - [Bug in Apple](http://www.codewars.com/kata/56fe97b3cc08ca00e4000dc9)
 - [Father and Son](http://www.codewars.com/kata/56fe9a0c11086cd842000008)
 - [Jumping Dutch act](http://www.codewars.com/kata/570bcd9715944a2c8e000009)
 - [Planting Trees](http://www.codewars.com/kata/5710443187a36a9cee0005a1)
 - [Give me the equation](http://www.codewars.com/kata/56fe9b65cc08cafbc5000de3)
 - [Find the murderer](http://www.codewars.com/kata/570f3fc5b29c702c5500043e)
 - [Reading a Book](http://www.codewars.com/kata/570ca6a520c69f39dd0016d4)
 - [Eat watermelon](http://www.codewars.com/kata/570df12ce6e9282a7d000947)
 - [Special factor](http://www.codewars.com/kata/570e5d0b93214b1a950015b1)
 - [Guess the Hat](http://www.codewars.com/kata/570ef7a834e61306da00035b)
 - [Symmetric Sort](http://www.codewars.com/kata/5705aeb041e5befba20010ba)
 - [Are they symmetrical?](http://www.codewars.com/kata/5705cc3161944b10fd0004ba)
 - [Max Value](http://www.codewars.com/kata/570771871df89cf59b000742)
 - [Trypophobia](http://www.codewars.com/kata/56fe9ffbc25bf33fff000f7c)
 - [Virus in Apple](http://www.codewars.com/kata/5700af83d1acef83fd000048)
 - [Balance Attraction](http://www.codewars.com/kata/57033601e55d30d3e0000633)
 - [Remove screws I](http://www.codewars.com/kata/5710a50d336aed828100055a)
 - [Remove screws II](http://www.codewars.com/kata/5710a8fd336aed00d9000594)
 - [Regular expression...

from collections import Counter

def find_a_b(nums, target):
    # Edgy edge case 1
    if len(nums) <= 1: return None
    # Edgy edge case 2
    if target == 0:
        zeros = nums.count(0)
        if zeros == 0:
            return None
        elif zeros == 1:
            return [0, nums[1]] if nums[0] == 0 else [nums[0], 0]
        else:
            return [nums[0], 0]
    # The main stuff
    counter = Counter(nums)
    for num in nums:
        if num != 0 and target % num == 0:
            complement = target // num
            if ((num == complement and counter[complement] >= 2) or
                (num != complement and counter[complement] >= 1)):
                return [num, complement]


Solve in Python:
This is the simple version of Shortest Code series. If you need some challenges, please try the [challenge version](http://www.codewars.com/kata/56f928b19982cc7a14000c9d)

## Task:

  Every uppercase letter is Father, The corresponding lowercase letters is the Son.

  Give you a string ```s```, If the father and son both exist, keep them. If it is a separate existence, delete them. Return the result.

  For example:

   ```sc("Aab")``` should return ```"Aa"```

   ```sc("AabBc")``` should return ```"AabB"```

   ```sc("AaaaAaab")``` should return ```"AaaaAaa"```(father can have a lot of son)

   ```sc("aAAAaAAb")``` should return ```"aAAAaAA"```(son also can have a lot of father ;-)

### Series:
 - [Bug in Apple](http://www.codewars.com/kata/56fe97b3cc08ca00e4000dc9)
 - [Father and Son](http://www.codewars.com/kata/56fe9a0c11086cd842000008)
 - [Jumping Dutch act](http://www.codewars.com/kata/570bcd9715944a2c8e000009)
 - [Planting Trees](http://www.codewars.com/kata/5710443187a36a9cee0005a1)
 - [Give me the equation](http://www.codewars.com/kata/56fe9b65cc08cafbc5000de3)
 - [Find the murderer](http://www.codewars.com/kata/570f3fc5b29c702c5500043e)
 - [Reading a Book](http://www.codewars.com/kata/570ca6a520c69f39dd0016d4)
 - [Eat watermelon](http://www.codewars.com/kata/570df12ce6e9282a7d000947)
 - [Special factor](http://www.codewars.com/kata/570e5d0b93214b1a950015b1)
 - [Guess the Hat](http://www.codewars.com/kata/570ef7a834e61306da00035b)
 - [Symmetric Sort](http://www.codewars.com/kata/5705aeb041e5befba20010ba)
 - [Are they symmetrical?](http://www.codewars.com/kata/5705cc3161944b10fd0004ba)
 - [Max Value](http://www.codewars.com/kata/570771871df89cf59b000742)
 - [Trypophobia](http://www.codewars.com/kata/56fe9ffbc25bf33fff000f7c)
 - [Virus in Apple](http://www.codewars.com/kata/5700af83d1acef83fd000048)
 - [Balance Attraction](http://www.codewars.com/kata/57033601e55d30d3e0000633)
 - [Remove screws I](http://www.codewars.com/kata/5710a50d336aed828100055a)
 - [Remove screws...

def sc(s):
    return "".join(ch for ch in s if ch.upper() in s and ch.lower() in s);


Solve in Python:
This is the simple version of Shortest Code series. If you need some challenges, please try the [challenge version](http://www.codewars.com/kata/570f45fab29c705d330004e3)

## Task:

There is a rectangular land and we need to plant trees on the edges of that land.

I will give you three parameters:

```width``` and ```length```, two integers > 1 that represents the land's width and length;

```gaps```, an integer >= 0, that is the distance between two trees.

Return how many trees have to be planted, if you can't achieve a symmetrical layout(see Example 3) then return 0.

### Example:

```

    Example1:
    width=3, length=3, gaps=1       o - o
    we can plant 4 trees            -   -
    sc(3,3,1)=4                     o - o

    Example2:
    width=3, length=3, gaps=3       o - -
    we can plant 2 trees            -   -
    sc(3,3,3)=2                     - - o

    Example3:
    width=3, length=3, gaps=2       o - -
    if we plant 2 trees, some       x   o
    gaps of two trees will >2       x x x

    if we plant 3 trees, some       o - -
    gaps of two trees will <2       x   o
    so we can not finish it         o - -
    sc(3,3,2)=0

    Example4:
    width=7, length=7, gaps=3       o - - - o - -
    we can plant 6 trees            -           -
    sc(3,3,3)=6                     -           o
                                    -           -
                                    o           -
                                    -           -
                                    - - o - - - o

    some corner case:

    Example5:
    width=3, length=3, gaps=0       o o o
    we can plant 8 trees            o   o
    sc(3,3,0)=8                     o o o

    Example6:
    width=3, length=3, gaps=10      o 1 2
    in this case, the max gaps      1   3
    of two trees is 3               2 3 o
    gaps=10 can not finished
    so sc(3,3,10)=0

```

### Series:
 - [Bug in...

def sc(width, length, gaps):
    edges = (width + length - 2) * 2
    q, r = divmod(edges, gaps + 1)
    return q * (not r)


Solve in Python:
This is the simple version of [Fastest Code : Equal to 24](http://www.codewars.com/kata/574e890e296e412a0400149c).

## Task

A game I played when I was young: Draw 4 cards from playing cards, use ```+ - * / and ()``` to make the final results equal to 24.

You will coding in function ```equalTo24```. Function accept 4 parameters ```a b c d```(4 cards), value range is 1-13.

The result is a string such as ```"2*2*2*3"``` ,```(4+2)*(5-1)```; If it is not possible to calculate the 24, please return "It's not possible!"

All four cards are to be used, only use three or two cards are incorrect; Use a card twice or more is incorrect too.

You just need to return one correct solution, don't need to find out all the possibilities.

## Examples

from functools import lru_cache as memo
from itertools import permutations, product
from operator import add, sub, mul, truediv as div
operators = {add: '+', sub: '-', mul: '*', div: '/'}

@memo(None)
def evaluate_tree(terms, ops):
    if not ops: return {terms[0]: str(terms[0])}
    results = {}
    for idx, op in enumerate(ops, 1):
        left, right = evaluate_tree(terms[:idx], ops[:idx-1]), evaluate_tree(terms[idx:], ops[idx:])
        results.update({op(l, r): f'({left[l]}){operators[op]}({right[r]})'
                        for l, r in product(left, right) if not (op == div and r == 0)})
    return results

def equal_to_24(*terms):
    for operands in permutations(terms):
        for ops in product(operators, repeat=3):
            results = evaluate_tree(operands, ops)
            if 24 in results: return results[24]
    return "It's not possible!"


Solve in Python:
This kata aims to show the vulnerabilities of hashing functions for short messages.

When provided with a SHA-256 hash, return the value that was hashed. You are also given the characters that make the expected value, but in alphabetical order.

The returned value is less than 10 characters long. Return `nil` for Ruby and Crystal, `None` for Python, `null` for Java when the hash cannot be cracked with the given characters.

---

Example:
--------
```
Example arguments: '5694d08a2e53ffcae0c3103e5ad6f6076abd960eb1f8a56577040bc1028f702b', 'cdeo'
Correct output: 'code'
```

import hashlib
import itertools
def hashit(str):
    result = hashlib.sha256(str.encode())
    return result.hexdigest()
def guess(chars):
    yield from list(itertools.permutations(chars,len(chars)))
def sha256_cracker(hash, chars):
    for x in guess(chars):
        str = ''.join(x)
        if (hashit(str) == hash):
            return str
    return None


Solve in Python:
This kata explores writing an AI for a two player, turn based game called *NIM*.

The Board
--------------

The board starts out with several piles of straw.  Each pile has a random number of straws.

```
Pile 0: ||||

Pile 1: ||

Pile 2: |||||

Pile 3: |

Pile 4: ||||||

...or more concisely: [4,2,5,1,6]
```

The Rules
--------------

- The players take turns picking a pile, and removing any number of straws from the pile they pick
- A player must pick at least one straw
- If a player picks the last straw, she wins!

The Task
------------

In this kata, you have to write an AI to play the straw picking game.

You have to encode an AI in a function `choose_move` (or `chooseMove`, or `choose-move`) that takes a board, represented as a list of positive integers, and returns

```python
(pile_index, number_of_straws)
```

Which refers to an index of a pile on the board, and some none-zero number of straws to draw from that pile.

The test suite is written so that your AI is expected to play 50 games and win every game it plays.

from operator import xor
from functools import reduce
def choose_move(game_state):
    """Chooses a move to play given a game state"""
    nim_sum = reduce(xor, game_state)
    to_take = (s-(s^nim_sum) for s in game_state)
    return next((i,t) for i, t in enumerate(to_take) if t>0)


Solve in Python:
This kata focuses on the Numpy python package and you can read up on the Numpy array manipulation functions here: https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.array-manipulation.html

You will get two integers `N` and `M`. You must return an array with two sub-arrays with numbers in ranges `[0, N / 2)` and `[N / 2, N)` respectively, each of them being rotated `M` times.

```
reorder(10, 1)   =>  [[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]
reorder(10, 3)   =>  [[2, 3, 4, 0, 1], [7, 8, 9, 5, 6]]
reorder(10, 97)  =>  [[3, 4, 0, 1, 2], [8, 9, 5, 6, 7]]
```

reorder = lambda a, b: [x[-b%len(x):] + x[:-b%len(x)] for x in map(list, (range(a//2), range(a//2, a)))]


Solve in Python:
This kata generalizes [Twice Linear](https://www.codewars.com/kata/5672682212c8ecf83e000050). You may want to attempt that kata first.

## Sequence

Consider an integer sequence `U(m)` defined as:

1. `m` is a given non-empty set of positive integers.
2. `U(m)[0] = 1`, the first number is always 1.
3. For each `x` in `U(m)`, and each `y` in `m`, `x * y + 1` must also be in `U(m)`.
4. No other numbers are in `U(m)`.
5. `U(m)` is sorted, with no duplicates.

### Sequence Examples

#### `U(2, 3) = [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ...]`

1 produces 3 and 4, since `1 * 2 + 1 = 3`, and `1 * 3 + 1 = 4`.

3 produces 7 and 10, since `3 * 2 + 1 = 7`, and `3 * 3 + 1 = 10`.

#### `U(5, 7, 8) = [1, 6, 8, 9, 31, 41, 43, 46, 49, 57, 64, 65, 73, 156, 206, ...]`

1 produces 6, 8, and 9.

6 produces 31, 43, and 49.

## Task:

Implement `n_linear` or `nLinear`: given a set of postive integers `m`, and an index `n`, find `U(m)[n]`, the `n`th value in the `U(m)` sequence.

### Tips

* Tests use large n values. Slow algorithms may time-out.
* Tests use large values in the m set. Algorithms which multiply further than neccessary may overflow.
* Linear run time and memory usage is possible.
* How can you build the sequence iteratively, without growing extra data structures?

from collections import deque
from heapq import heappush, heappop

def n_linear(m, n):
    y, h, q = 1, [], {}
    for x in m:
        h.append((y, x))
        q[x] = deque([x * y + 1])
    while n:
        z, w = heappop(h)
        if y != z:
            y = z
            for x in m: q[x].append(x * y + 1)
            n -= 1
        heappush(h, (q[w].popleft(), w))
    return y


Solve in Python:
This kata is  blatantly copied from  inspired by This Kata
Welcome

this is the second in the series of the string iterations kata!

Here we go!

---------------------------------------------------------------------------------

We have a string s

Let's say you start with this: "String"

The first thing you do is reverse it: "gnirtS"

Then you will take the string from the 1st position and reverse it again: "gStrin"

Then you will take the string from the 2nd position and reverse it again: "gSnirt"

Then you will take the string from the 3rd position and reverse it again: "gSntri"

Continue this pattern until you have done every single position, and then you will return the string you have created. For this particular string, you would return:
"gSntir"

now,

The Task:

In this kata, we also have a number x

take that reversal function, and apply it to the string x times.

return the result of the string after applying the reversal function to it x times.

    example where s = "String" and x = 3:

    after 0 iteration  s = "String"
    after 1 iteration  s = "gSntir"
    after 2 iterations s = "rgiStn"
    after 3 iterations s = "nrtgSi"

    so you would return "nrtgSi".

 Note

String lengths may exceed 2 million

x exceeds a billion

be read to optimize

if this is too hard, go here https://www.codewars.com/kata/string-%3E-n-iterations-%3E-string/java

def string_func(s, n):
    m, table = len(s), {}
    for i in range(m):
        if i not in table:
            j, cycle = i, []
            while i != j or not cycle:
                cycle.append(j)
                j = min(2 * j + 1, 2 * (m - j - 1))
            table.update(zip(cycle[n % len(cycle):] + cycle, cycle))
    return ''.join(s[table[i]] for i in range(m))


Solve in Python:
This kata is a continuation of [Part 1](http://www.codewars.com/kata/the-fibfusc-function-part-1). The `fibfusc` function is defined recursively as follows:

    fibfusc(0) = (1, 0)
    fibfusc(1) = (0, 1)
    fibfusc(2n) = ((x + y)(x - y), y(2x + 3y)), where (x, y) = fibfusc(n)
    fibfusc(2n + 1) = (-y(2x + 3y), (x + 2y)(x + 4y)), where (x, y) = fibfusc(n)

Your job is to produce the code for the `fibfusc` function. In this kata, your function will be tested with large values of n (up to 2000 bits), so you should be concerned about stack overflow and timeouts. Moreover, since the `fibfusc` function grows exponentially, your function should take an extra argument `num_digits` with a default value of `None`. When not `None`, `num_digits` takes a positive `int` value and the returned values shall be truncated to the last `num_digits` digits.

For example, let `n = 101`. With `num_digits` not set or set to `None`, `fibfusc` should return:
`(-280571172992510140037611932413038677189525L, 734544867157818093234908902110449296423351L)`. If `num_digits = 12`, the function should return `(-38677189525L, 449296423351L)`. Notice in particular, that for any value of `n` greater than 1, `x` is negative, and the truncated value of `x` should also be negative.

Hint 1: Use modulo `10 ** num_digits` arithmetic to keep all intermediary results small.

Hint 2: Consider using an iterative ["number climber"](http://www.codewars.com/kata/number-climber) to avoid stack overflows.

def fibfusc(n, num_digits=None):
    if n < 2: return (1 - n, n)
    b = bin(n)[2:]

    x, y = fibfusc(int(b[0]))
    for bit in b[1:]:
        if bit == "1":
            x, y = (-y*(2*x + 3*y), (x + 2*y)*(x + 4*y))
        else:
            x, y = ((x + y) * (x - y), y * (2*x + 3*y))
        if num_digits:
            x, y = x % 10 ** num_digits - 10**num_digits, y % 10 ** num_digits
    return x, y


Solve in Python:
This kata is about multiplying a given number by eight if it is an even number and by nine otherwise.

def simple_multiplication(number) :
    mult = 9 if number % 2 else 8
    return number * mult


Solve in Python:
This kata is about singly
linked list.  A linked list is an ordered set of data elements, each containing a link to its successor (and sometimes its predecessor, known as a double linked list).  You are you to implement an algorithm to find the kth to last element.

For example given a linked list of:
a -> b -> c -> d

if k is the number one then d should be returned
if k is the number two then c should be returned
if k is the number three then b should be returned
if k is the number four then a should be returned
if k exceeds the size of the list then None returned

Special Note --> Node classes contain two fields; data and next.
And to access the head of the list, use head. e.g. linked_list.head

def search_k_from_end(linked_list, k):
    def rec(node, x):
        if not node: return x
        n = rec(node.next, x)
        return n if type(n) != int else n-1 if n else node
    res = rec(linked_list.head, k-1)
    if type(res) != int: return res.data


Solve in Python:
This kata is all about adding numbers.

You will create a function named add. It will return the sum of all the arguments. Sounds easy, doesn't it?

Well Here's the Twist. The inputs will gradually decrease with their index as parameter to the function.

```python
  add(3,4,6) #returns (3/1)+(4/2)+(6/3)=7
```

Remember the function will return 0 if no arguments are passed and it must round the result if sum is a float.

Example
```python
  add() #=> 0
  add(1,2,3) #=> 3
  add(1,4,-6,20) #=> 6
```

Check my another kata here!! http://www.codewars.com/kata/555b73a81a6285b6ce000047

def add(*args):
    return round(sum([args[i]/(i + 1) for i in range(len(args))]))


Solve in Python:
This kata is all about adding numbers.

You will create a function named add. This function will return the sum of all the arguments. Sounds easy, doesn't it??

Well here's the twist. The inputs will gradually increase with their index as parameter to the function.

```python
  add(3,4,5) #returns (3*1)+(4*2)+(5*3)=26
```
Remember the function will return 0 if no arguments are passed.

## Example

```python
  add() #=> 0
  add(1,2,3) #=> 14
  add(1,4,-5,5) #=> 14
```

def add(*args):
    return sum(n * i for i, n in enumerate(args, 1))


Solve in Python:
This kata is an extension of "Combinations in a Set Using Boxes":https://www.codewars.com/kata/5b5f7f7607a266914200007c

The goal for this kata is to get all the possible combinations (or distributions) (with no empty boxes) of a certain number of balls, but now, **with different amount of boxes.** In the previous kata, the number of boxes was always the same

Just to figure the goal for this kata, we can see in the picture below the combinations for four balls using the diagram of Hasse:

Points that are isolated represent balls that are unique in a box.
k points that are bonded in an area respresent a subset that is content in a box.

The unique square at the bottom of the diagram, means that there is only one possible combination for four balls in four boxes.

The above next line with 6 squares, means that we have 6 possible distributions of the four balls in 3 boxes. These six distributions have something in common, all of them have one box with 2 balls.

Going up one line more, we find the 7 possible distributions of the four balls in 2 boxes. As it is shown, we will have 7 distributions with: three balls in a box and only one ball in the another box, or two balls in each box.

Finally, we find again at the top, an unique square, that represents, the only possible distribution, having one box, the four balls together in the only available box.

So, for a set of 4 labeled balls, we have a total of 15 possible distributions (as always with no empty boxes) and with a maximum of 7 possible distributions for the case of two boxes.

Prepare a code that for a given number of balls (an integer), may output an array with required data in the following order:
```
[total_amount_distributions, maximum_amount_distributions_case_k_boxes, k_boxes]
```
Just see how it would be for the example given above:
```
combs_non_empty_boxesII(4) == [15, 7, 2] # A total of 15 combinations
                                         #The case with maximum distributions is 7 using 2 boxes.

```
Features of the random...

# this is [A000110, A002870, A024417]

# Stirling numbers of second kind
# http://mathworld.wolfram.com/StirlingNumberoftheSecondKind.html
# S(n,k) = S(n-1,k-1)+k*S(n-1,k)
S = {}
for n in range(1,1800):
    S[(n,1)] = S[(n,n)] = 1
    for k in range(2,n): S[(n,k)]=S[(n-1,k-1)]+k*S[(n-1,k)]

def combs_non_empty_boxesII(n):
    ss = [(S[(n,k)],k) for k in range(1,n+1)]
    return [sum(p[0] for p in ss), *max(ss)]


Solve in Python:
This kata is based on a [variation](https://www.codewars.com/kata/happy-numbers-5) of *Happy Numbers* by TySlothrop. It is advisable to complete it first to grasp the idea and then move on to this one.

___

Hello, my dear friend, and welcome to another *Happy Numbers* kata! What? You're not interested in them anymore? They are all the same? But what if I say that this one is a *performance version*...

___

# Your task:

Write a function `performant_numbers` which takes a number `n` as an argument and returns a list of all *happy numbers* from `1` to `n` inclusive. For example:

```
performant_numbers(10)   =>  [1, 7, 10]
performant_numbers(50)   =>  [1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49]
performant_numbers(100)  =>  [1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100]
```

# Test suite:

* `5000` tests with number `n` being up to `300000`
* The reference solution takes around `4.9` seconds to calculate the result
* you are not allowed to hardcode the sequence: you'll have to compute it (max length of the code: 1700 characters)

___

Will you take up the challenge?

from bisect import bisect

LIMIT = 1 + 300000
happySieve = [None] * LIMIT
happySieve[1] = 1

def happyOnes(n):
    seen = set()
    while 1:
        if happySieve[n] is not None: return happySieve[n], seen
        if n in seen or n == 1:  return n==1, seen
        seen.add(n)
        n = sum( int(d)**2 for d in str(n) )

for n in range(1,LIMIT):
    isH, seen = happyOnes(n)
    for x in seen: happySieve[x] = isH

HAPPY = [i for i in range(1,LIMIT) if happySieve[i]]

def performant_numbers(n): return HAPPY[:bisect(HAPPY,n)]


Solve in Python:
This kata is from check py.checkio.org

You are given an array with positive numbers and a number N. You should find the N-th power of the element in the array with the index N. If N is outside of the array, then return -1. Don't forget that the first element has the index 0.

Let's look at a few examples:

* array = [1, 2, 3, 4] and N = 2, then the result is 3^2 == 9;
* array = [1, 2, 3] and N = 3, but N is outside of the array, so the result is -1.

def index(arr, n):
    return arr[n] ** n if n < len(arr) else -1


Solve in Python:
This kata is inspired by Space Invaders (Japanese: スペースインベーダー), an arcade video game created by Tomohiro Nishikado and released in 1978.
Alien invaders are attacking Earth and you've been conscripted to defend.
The Bad News: You performed poorly in the manual training. As a result, you're ranked low priority and you're piloting a space jalopy.
The Good News: Your coding skill is better than your piloting and you know the movement pattern of the alien spaceships.
You're going to program an algorithm that aids in shooting down the incoming alien wave despite your limitations.
Input
The action takes place on an m x n matrix. Your function will receive two arguments:

a 2-D array where each subarray represents a row of alien ships. Subarrays consist of integers that represent each alien ship. Zero values (0) are empty spaces.

your [row,column] coordinates

The width (n) of a row is equal to the length of a subarray in the first argument and all rows are of the same length.
Your row coordinate will be the last row of the matrix (m - 1).
Alien Ship Movement Pattern

Each alien ship is given in the form of an integer that represents its movement speed and direction.
Alien ships move left or right. A positive integer means an alien moves right, a negative integer means an alien moves left. The absolute value of the integer is the distance the alien moves in 1 turn.
When an alien reaches an edge, it moves down one position and reverses lateral (left/right) direction.

Your Ship's Limitations

Your position is fixed.
Your pulse cannon has a time delay of 1 turn. After the delay, your cannon blasts the first target in its path.
You can fire up to one shot per turn.

Output
Your function should return an array of integers. Each integer represents the turn for each shot fired from your ship's cannon. If it is not possible to destroy all alien ships before they reach the last row, return null or None.
Test Example

Above: Turn 0 (Initial State)
Below: Turn 1

The images above represent the matrix states at Turn 0...

def blast_sequence(aliensStart,position):

    def moveAliens(aliens, furthest):
        lst, shootPath = [], []
        for x,y,s in aliens:
            y += s
            if not (0 <= y < N):                                           #Out of the grid: move down and reverse
                x, s = x+1, -s
                y = -y-1 if y < 0 else 2*N-y-1
            (shootPath if y == Y else lst).append((x,y,s))
            if x > furthest: furthest = x
        return lst, shootPath, furthest

    def shootTarget(shootPath):
        if shootPath:
            z = max(shootPath, key=lambda a: (a[0], abs(a[2]), a[2]))     # Furthest, fastest, going right is considered the highest
            shootPath.remove(z)                                           # MUTATION
            shots.append(turn)                                            # MUTATION

    (X,Y), N = position, len(aliensStart[0])
    aliens   = [(x,y,s) for x,r in enumerate(aliensStart) for y,s in enumerate(r) if s]
    shots, furthest, turn = [], 0, -1

    while aliens and furthest < X:
        turn += 1
        aliens, shootPath, furthest = moveAliens(aliens, furthest)        # Move all the aliens, splitting them in 2 groups: those facing "my" ship (shootPath) and the others
        shootTarget(shootPath)                                            # Extract the target in shootPath and pop it if possible (mutation). Mutate 'shots' list at the same time
        aliens += shootPath                                               # Put the remaining aliens in the list

    return shots if not aliens else None


Solve in Python:
This kata is inspired by Tower Defense (TD), a subgenre of strategy video games where the goal is to defend a player's territories or possessions by obstructing enemy attackers, usually by placing defensive structures on or along their path of attack.

Objective
It's the future, and hostile aliens are attacking our planet. We've set up a defense system in the planet's outer perimeter. You're tasked with calculating the severity of a breach.
Input
Your function will receive three arguments:

Battle Area Map: An array/list of strings representing an n x n battle area.
        Each string will consist of any of the following characters:

0: entrance point (starting position on alien path)
1: alien path
" "(space character): not alien path
A - Z: turret positions

Turret Stats: An object/dict where keys are upper-case characters from the English alphabet (A - Z) and the values are subarrays in the following format:
[n,m] - where n is the attack range of a turret, and m is its shot frequency per move
Alien Wave Stats: An array of integers representing each individual alien in sequence. Each value is an integer representing the health points of each alien; health points are the number of turret shots required to take down a given alien. Integer zero (0) counts as a gap in sequence.

Output
Return the integer sum of total health points of all aliens that successfully penetrate our defense.

The image above shows the game state for the test example (below) at the 11th move.
The green square in the north-west quadrant represents the starting position of the alien wave, and the red square in the south-east quadrant represents the last position before breaching the defensive perimeter.
The blue circles represent the turret positions and are labeled A,B,C, and D.
The red alien is the first alien in the sequence.
Technical Details

There is only one path and it maintains a width of 1.
Aliens move one square per turn
Turrets only fire toward enemies in range.
        In the image above, the turret labeled A has the...

class Turret:
    def __init__(self, tid, r, c, size, info):
        self.tid = tid
        self.attack = info[1]
        self.targets = set()
        atkRange = info[0]
        for dr in range(-atkRange, atkRange + 1):
            for dc in range(-atkRange, atkRange + 1):
                if dr == 0 and dc == 0:
                    continue
                ra, ca = r + dr, c + dc
                if not(0 <= ra < size and 0 <= ca < size):
                    continue
                if dr * dr + dc * dc <= atkRange * atkRange:
                    self.targets.add((ra, ca))

class Alien:
    def __init__(self, pathIdx, pos, hp):
        self.pathIdx = pathIdx
        self.pos = pos
        self.hp = hp

def tower_defense(grid, _turrets, _wave):
    answer = 0
    size = len(grid)
    lWave = len(_wave)
    wave = _wave[:]
    ones = set()
    turrets, aliens = [], []
    for r, row in enumerate(grid):
        for c, square in enumerate(row):
            if square == "1":
                ones.add((r, c))
            elif square.isalpha():
                turrets.append(Turret(square, r, c, size, _turrets[square]))
            elif square == "0":
                start = (r, c)
    for turret in turrets:
        turret.targets = turret.targets & (ones | {start})
    turrets.sort(key = lambda t: t.tid)
    path = [start]
    r, c = start
    while ones:
        for r1, c1 in ones:
            if abs(r1 - r) + abs(c1 - c) == 1:
                path.append((r1, c1))
                ones.discard((r1, c1))
                r, c = r1, c1
                break
    lPath = len(path)
    time = -1
    while time < lWave or aliens:
        time += 1
        for i in range(len(aliens) - 1, -1, -1):
            alien = aliens[i]
            if alien.hp <= 0:
                del aliens[i]
                continue
            alien.pathIdx += 1
            if alien.pathIdx == lPath:
                answer += alien.hp
                del aliens[i]
                continue
            alien.pos = path[alien.pathIdx]
        if...


Solve in Python:
This kata is inspired on the problem #50 of the Project Euler.

The prime ``` 41```  is the result of the sum of many consecutive primes.

In fact, ``` 2 + 3 + 5 + 7 + 11 + 13 = 41 , (6 addens)   ```

Furthermore, the prime ``` 41```  is the prime below ``` 100 (val_max)```  that has the longest chain of consecutive prime addens.

The prime with longest chain of addens for ```val_max = 500``` is ```499``` with ```17``` addens.

In fact:
```3+5+7+11+13+17+19+23+29+31+37+41+43+47+53+59+61= 499```

Find the function ```prime_maxlength_chain()```(primeMaxlengthChain() javascript), that receives an argument ```val_max```, the upper limit, all the found primes should be less than ```val_max``` and outputs this found prime.

Let's see some cases:
```python
prime_maxlength_chain(100) == [41]
prime_maxlength_chain(500) == [499]
```
If we have more than one prime with these features, the function should output an array with the found primes sorted.
```python
prime_maxlength_chain(499) == [379, 491]
```
Random Tests for `val_max` (`valMax`)
```
100 ≤ val_max ≤ 500.000
```
Enjoy it!

def sieve(n):
    n = n - 1 # finding primes smaller than the limit
    primes = [True for i in range(n+1)]
    result = []
    p = 2
    while p * p <= n:
        if primes[p]:
            for i in range(p * 2, n+1, p):
                primes[i] = False
        p += 1
    for p in range(2, n+1):
        if primes[p]:
            result.append(p)
    #print(result)
    return result

def prime_maxlength_chain(n):
    prime_num = sieve(n)
    prime_sums = [[0,2]]
    count_max = 0
    results = []
    if n == 0:
        return []
    i, j = 0, 0

    while sum(prime_num[i:count_max+i+j]) < n:
        while sum(prime_num[i:count_max+i+j]) < n:
            #print(prime_num[i:count_max+i+j], i, j, count_max)
            count = len(prime_num[i:count_max+i+j])
            summe = sum(prime_num[i:count_max+i+j])
            if summe in prime_num:
                prime_sums.append([count, summe])

            j += 1
        if count_max <= prime_sums[-1][0]:
            count_max = prime_sums[-1][0]
        i += 1
        j = 0
    prime_sums.sort()
    for p in prime_sums:
        if p[0] == prime_sums[-1][0]:
            results.append(p[1])

    return results


Solve in Python:
This kata is part of the collection [Mary's Puzzle Books](https://www.codewars.com/collections/marys-puzzle-books).

# Zero Terminated Sum

Mary has another puzzle book, and it's up to you to help her out! This book is filled with zero-terminated substrings, and you have to find the substring with the largest sum of its digits. For example, one puzzle looks like this:
```
"72102450111111090"
```
Here, there are 4 different substrings: `721`, `245`, `111111`, and `9`. The sums of their digits are `10`, `11`, `6`, and `9` respectively. Therefore, the substring with the largest sum of its digits is `245`, and its sum is `11`.

Write a function `largest_sum` which takes a string and returns the maximum of the sums of the substrings. In the example above, your function should return `11`.

### Notes:

- A substring can have length 0. For example, `123004560` has three substrings, and the middle one has length 0.
- All inputs will be valid strings of digits, and the last digit will always be `0`.

def largest_sum(s):
    return max(sum(map(int, e)) for e in s.split('0'))


Solve in Python:
This kata is part of the collection [Mary's Puzzle Books](https://www.codewars.com/collections/marys-puzzle-books).

Mary brought home a "spot the differences" book. The book is full of a bunch of problems, and each problem consists of two strings that are similar. However, in each string there are a few characters that are different. An example puzzle from her book is:
```
String 1: "abcdefg"
String 2: "abcqetg"
```
Notice how the "d" from String 1 has become a "q" in String 2, and "f" from String 1 has become a "t" in String 2.

It's your job to help Mary solve the puzzles. Write a program `spot_diff`/`Spot` that will compare the two strings and return a list with the positions where the two strings differ. In the example above, your program should return `[3, 5]` because String 1 is different from String 2 at positions 3 and 5.

NOTES:

```if-not:csharp
• If both strings are the same, return `[]`
```
```if:csharp
• If both strings are the same, return `new List()`
```

• Both strings will always be the same length

• Capitalization and punctuation matter

def spot_diff(s1, s2):
  r=[]
  for i in range (len(s1)):
    if s1[i]!=s2[i]: r.append(i)
  return r


Solve in Python:
This kata is part one of precise fractions series (see pt. 2: http://www.codewars.com/kata/precise-fractions-pt-2-conversion).

When dealing with fractional values, there's always a problem with the precision of arithmetical operations. So lets fix it!

Your task is to implement class ```Fraction``` that takes care of simple fraction arithmetics. Requirements:

* class must have two-parameter constructor `Fraction(numerator, denominator)`; passed values will be non-zero integers, and may be positive or negative.
* two conversion methods must be supported:
 * `toDecimal()` returns decimal representation of fraction
 * `toString()` returns string with fractional representation of stored value in format:

    [ SIGN ] [ WHOLES ] [ NUMERATOR / DENOMINATOR ]
   * **Note**: each part is returned only if it is available and non-zero, with the only possible space character going between WHOLES and fraction. Examples: '-1/2', '3', '-5 3/4'

* The fractional part must always be normalized (ie. the numerator and denominators must not have any common divisors).
* Four operations need to be implemented: `add`, `subtract`, `multiply` and `divide`. Each of them may take integers as well as another `Fraction` instance as an argument, and must return a new `Fraction` instance.
* Instances must be immutable, hence none of the operations may modify either of the objects it is called upon, nor the passed argument.

 #### Python Notes
* If one integer is passed into the initialiser, then the fraction should be assumed to represent an integer not a fraction.
* You must implement the standard operator overrides `__add__`, `__sub__`, `__mul__`, `__div__`, in each case you should support `other` being an `int` or another instance of `Fraction`.
* Implement `__str__` and `to_decimal` in place of `toString` and `toDecimal` as described above.

from fractions import Fraction, gcd

def to_string(self):
    n, d = self.numerator, self.denominator
    s, w, n = "-" if n < 0 else "", *divmod(abs(n), d)
    r = " ".join((str(w) if w else "", f"{n}/{d}" if n else "")).strip()
    return f"{s}{r}"

Fraction.__str__ = to_string
Fraction.to_decimal = lambda self: float(self.numerator) / self.denominator


Solve in Python:
This kata is the first of a sequence of four about "Squared Strings".

You are given a string of `n` lines, each substring being `n` characters long: For example:

`s = "abcd\nefgh\nijkl\nmnop"`

We will study some transformations of this square of strings.

- Vertical mirror:
vert_mirror (or vertMirror or vert-mirror)
```
vert_mirror(s) => "dcba\nhgfe\nlkji\nponm"
```
- Horizontal mirror:
hor_mirror (or horMirror or hor-mirror)
```
 hor_mirror(s) => "mnop\nijkl\nefgh\nabcd"
```

or printed:

```
vertical mirror   |horizontal mirror
abcd --> dcba     |abcd --> mnop
efgh     hgfe     |efgh     ijkl
ijkl     lkji     |ijkl     efgh
mnop     ponm     |mnop     abcd
```

# Task:
- Write these two functions

and

- high-order function `oper(fct, s)` where

 - fct is the function of one variable f to apply to the string `s`
(fct will be one of `vertMirror, horMirror`)

# Examples:
```
s = "abcd\nefgh\nijkl\nmnop"
oper(vert_mirror, s) => "dcba\nhgfe\nlkji\nponm"
oper(hor_mirror, s) => "mnop\nijkl\nefgh\nabcd"
```
# Note:
The form of the parameter `fct` in oper
changes according to the language. You can see each form according to the language in "Sample Tests".

# Bash Note:
The input strings are separated by `,` instead of `\n`. The output strings should be separated by `\r` instead of `\n`. See "Sample Tests".

Forthcoming katas will study other transformations.

def vert_mirror(strng):
    strng_list = strng.split('\n')
    for i in range(len(strng_list)):
        strng_list[i] = strng_list[i][::-1]
    return "\n".join(strng_list)

def hor_mirror(strng):
    strng_list = strng.split('\n')
    strng_list.reverse()
    return "\n".join(strng_list)

def oper(fct, s):
    return fct(s)


Solve in Python:
This kata is the second part of a series: [Neighbourhood kata collection](https://www.codewars.com/collections/5b2f4db591c746349d0000ce). If this one is to easy you can try out the harder Katas.;)

___
The neighbourhood of a cell (in a matrix) are cells that are near to it. There are two popular types:
- The [Moore neighborhood](https://en.wikipedia.org/wiki/Moore_neighborhood) are eight cells which surround a given cell.
- The [Von Neumann neighborhood](https://en.wikipedia.org/wiki/Von_Neumann_neighborhood) are four cells which share a border with the given cell.

___

# Task
Given a neighbourhood type (`"moore"` or `"von_neumann"`), a 2D matrix (a list of lists) and a pair of coordinates, return the list of neighbours of the given cell.

Notes:
- The order of the elements in the output list is not important.
- If the input indexes are outside the matrix, return an empty list.
- If the the matrix is empty, return an empty list.
- Order of the indices: The first index should be applied for the outer/first matrix layer. The last index for the most inner/last layer. `coordinates = (m, n)` should be apllied like `mat[m][n]`

___

## Examples
```
\ n   0    1    2    3    4
m  --------------------------
0  |  0 |  1 |  2 |  3 |  4 |
1  |  5 |  6 |  7 |  8 |  9 |
2  | 10 | 11 | 12 | 13 | 14 |
3  | 15 | 16 | 17 | 18 | 19 |
4  | 20 | 21 | 22 | 23 | 24 |
   --------------------------

get_neighborhood("moore", mat, (1,1)) == [0, 1, 2, 5, 7, 10, 11, 12]
get_neighborhood("moore", mat, (0,0)) == [1, 6, 5]
get_neighborhood("moore", mat, (4,2)) == [21, 16, 17, 18, 23]
get_neighborhood("von_neumann", mat, (1,1)) == [1, 5, 7, 11]
get_neighborhood("von_neumann", mat, (0,0)) == [1, 5]
get_neighborhood("von_neumann", mat, (4,2)) == [21, 17, 23]
```
___

Translations are appreciated.^^

If you like chess take a look at [Chess Aesthetics](https://www.codewars.com/kata/5b574980578c6a6bac0000dc)

If you like puzzles and take a look at [Rubik's cube](https://www.codewars.com/kata/5b3bec086be5d8893000002e)

vn = [(-1, 0), (0, -1), (0, 1), (1, 0)]
mr = vn + [(-1, -1), (-1, 1), (1, -1), (1, 1)]

def get_neighbourhood(nh, a, p):
    h, w, nh, x, y = list(range(len(a))), list(range(len(a[0] if a else []))), mr if "r" in nh else vn, *p
    return [a[x+i][y+j] for i, j in nh if ((x+i) in h and (y+j) in w)] if x in h and y in w else []


Solve in Python:
This kata provides you with a list of parent-child pairs `family_list`, and from this family description you'll need to find the relationship between two members(what is the relation of latter with former) which is given as `target_pair`.

For example, the family list may be given as:

`[('Enid', 'Susan'), ('Susan', 'Deborah'), ('Enid', 'Dianne')]`

This describes the family:

          Enid
            |
       |---------|
     Susan     Dianne
       |
    Deborah

The relationship pair `('Deborah', 'Enid')` should return 'Grandmother' as Enid is Deborah's Grandmother.

This family tree can cover up to 3 generations, with varying numbers of children for each parent. We only focus on the females in the family, and so children will have only one parent.

The possible responses are Mother, Daughter, Grandmother, Granddaughter, Sister, Cousin, Aunt, Niece (each matching their 'real life' equivalents). There will always be a valid answer.

Enjoy, and be nice to your Mother!

def relations(family_list, target_pair):
    tree = {}
    for parent, child in family_list:
        tree[child] = parent

    a = tree.get(target_pair[0], 0)
    b = tree.get(target_pair[1], 0)
    if a==b:
        return 'Sister'
    elif a == target_pair[1]:
        return 'Mother'
    elif b == target_pair[0]:
        return 'Daughter'

    cnt_a = 0
    while a and a != target_pair[1]:
        cnt_a += 1
        a = tree.get(a, 0)

    cnt_b = 0
    while b and b != target_pair[0]:
        cnt_b += 1
        b = tree.get(b, 0)

    if a and not b and cnt_a == 1:
        return 'Grandmother'
    elif not a and not b and cnt_a==cnt_b:
        return 'Cousin'
    elif not a and not b and cnt_a < cnt_b:
        return 'Niece'
    elif not a and not b and cnt_a > cnt_b:
        return 'Aunt'
    elif not a and cnt_b == 1:
        return 'Granddaughter'
    else:
        return None


Solve in Python:
This kata requires you to convert minutes (`int`) to hours and minutes in the format `hh:mm` (`string`).

If the input is `0` or negative value, then you should return `"00:00"`

**Hint:** use the modulo operation to solve this challenge. The modulo operation simply returns the remainder after a division. For example the remainder of 5 / 2 is 1, so 5 modulo 2 is 1.

## Example

If the input is `78`, then you should return `"01:18"`, because 78 minutes converts to 1 hour and 18 minutes.

Good luck! :D

def time_convert(num):
    a=num//60
    b=num%60
    if num<=0:
        return '00:00'
    elif 0<num<10:
        return '00:0'+str(num)
    elif 10<=num<60:
        return '00:'+str(num)
    else:
        if a<10 and b<10:
            return "0"+str(a)+':'+"0"+str(b)
        elif a>=10 and b<10:
            return str(a)+':'+"0"+str(b)
        elif a<10 and b>=10:
            return "0"+str(a)+':'+str(b)
        elif a>=10 and b>=10:
            return str(a)+':'+str(b)