Solve in Python:
> [Run-length encoding](https://en.wikipedia.org/w/index.php?title=Run-length_encoding) (RLE) is a very simple form of data compression in which runs of data (that is, sequences in which the same data value occurs in many consecutive data elements) are stored as a single data value and count, rather than as the original run. Wikipedia

## Task

Your task is to write such a run-length encoding. For a given string, return a list (or array) of pairs (or arrays)
[
 (i1, s1),
 (i2, s2),
 …,
 (in, sn)
], such that one can reconstruct the original string by replicating the character sx ix times and concatening all those strings. Your run-length encoding should be minimal, ie. for all i the values si and si+1 should differ.

## Examples

As the article states, RLE is a _very_ simple form of data compression. It's only suitable for runs of data, as one can see in the following example:

```python
run_length_encoding("hello world!")
 //=>      [[1,'h'], [1,'e'], [2,'l'], [1,'o'], [1,' '], [1,'w'], [1,'o'], [1,'r'], [1,'l'], [1,'d'], [1,'!']]
```

It's very effective if the same data value occurs in many consecutive data elements:
```python
run_length_encoding("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbb")
# => [[34,'a'], [3,'b']]
```

from itertools import groupby

def run_length_encoding(s):
    return [[len(x), x[0]] for x in [list(g) for k, g in groupby(s)]]


Solve in Python:
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process  --myjinxin2015 said

# Description:

```if:javascript
Given an array `arr` that contains some integers(positive, negative or 0), and a `range` list such as `[[start1,end1],[start2,end2],...]`, start and end are the index of `arr` and start always less than end. Your task is to calculate the sum value of each range (start index and end index are both inclusive), and return the maximum sum value.
```
```if:ruby
Given an array (`arr`) of integers and an array (`ranges`) of ranges (e.g. `[[1, 32], [16, 24],...]`), which represent an index range of `arr`, calculate the sum of each range (start index and end index are both inclusive) of `arr`, and return the maximum sum.
```
```if:php
Given an array `$a` that contains some integers and a `$range` list such as `[[$start1, $end1], [$start2, $end2], ... ]` where `$start(n)` and `$end(n)` are valid keys of the non-associative array `$a` and `$start(n)` is always guaranteed to be strictly less than `$end(n)`.  Your task is to calculate the sum value of each range (start index and end index are both inclusive) and return the maximum sum value.
```
```if:haskell
Given a list `arr` that contains some integers(positive, negative or 0), and a `range` list such as `[(start1,end1),(start2,end2),...]`, start and end are the index of `arr` and start always less than end. Your task is to calculate the sum value of each range (start index and end index are both inclusive), and return the maximum sum value.
```

For example:

# Note:

 - `arr`/`$a` always has at least 5 elements;
 - `range`/`$range`/`ranges` always has at least 1 element;
 - All inputs are valid;
 - This is a simple version, if you want some challenge, please [try the challenge version](https://www.codewars.com/kata/the-maximum-sum-value-of-ranges-challenge-version/).

# Some Examples

def max_sum(arr, ranges):
    return max(sum(arr[a:b + 1]) for a, b in ranges)


Solve in Python:
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process  --myjinxin2015 said

# Description:

 Give you two arrays `arr1` and `arr2`. They have the same length(length>=2). The elements of two arrays always be integer.

 Sort `arr1` according to the ascending order of arr2; Sort `arr2` according to the ascending order of arr1. Description is not easy to understand, for example:
 ```
 arr1=[5,4,3,2,1],
 arr2=[6,5,7,8,9]
 ```
 Let us try to sorting arr1.
 First, we need know the ascending order of arr2:
 ```
 [5,6,7,8,9]
 ```
 We can see, after sort arr2 to ascending order, some elements' index are changed:
 ```
 unsort arr2      ascending order arr2
 [6,5,7,8,9]--->      [5,6,7,8,9]

 index0(6)  --->      index1
 index1(5)  --->      index0
 index2(7)            index2(no change)
 index3(8)            index3(no change)
 index4(9)            index4(no change)
 ```
 So, wo need according to these changes to sorting arr1:
 ```
 unsort arr1          sorted arr1
 [5,4,3,2,1]--->      [4,5,3,2,1]

 index0(5)  --->      index1
 index1(4)  --->      index0
 index2(3)            index2(no change)
 index3(2)            index3(no change)
 index4(1)            index4(no change)

 So: sorted arr1= [4,5,3,2,1]
 ```
 And then, we sorting arr2 with the same process:
 ```
 unsort arr1      ascending order arr1
 [5,4,3,2,1]--->      [1,2,3,4,5]

 index0(5)  --->      index4
 index1(4)  --->      index3
 index2(3)            index2(no change)
 index3(2)  --->      index1
 index4(1)  --->      index0

 unsort arr2          sorted arr2
 [6,5,7,8,9]--->      [9,8,7,5,6]

 index0(6)  --->      index4
 index1(5)  --->      index3
 index2(7)            index2(no change)
 index3(8)  --->      index1
 index4(9)  --->      index0

 So: sorted arr2= [9,8,7,5,6]

 ```
 Finally, returns the sorted arrays by a 2D array: `[sorted arr1, sorted arr2]`

 Note: In ascending order sorting process(not the final sort), if some elements have same value, sort them...

def sort_two_arrays(arr1, arr2):
    k1=sorted((v,i)for i,v in enumerate(arr1))
    k2=sorted((v,i)for i,v in enumerate(arr2))
    return[[arr1[i]for v,i in k2],[arr2[i]for v,i in k1]]


Solve in Python:
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process  --myjinxin2015 said

# Description:

 John learns to play poker with his uncle. His uncle told him: Poker to be in accordance with the order of "2 3 4 5 6 7 8 9 10 J Q K A". The same suit should be put together. But his uncle did not tell him the order of the four suits.

 Give you John's cards and Uncle's cards(two string `john` and `uncle`). Please reference to the order of Uncle's cards, sorting John's cards.

# Examples

```
For Python:

Suits are defined as S, D, H, C.

sort_poker("D6H2S3D5SJCQSKC7D2C5H5H10SA","S2S3S5HJHQHKC8C9C10D4D5D6D7")
should return "S3SJSKSAH2H5H10C5C7CQD2D5D6"
sort_poke("D6H2S3D5SJCQSKC7D2C5H5H10SA","C8C9C10D4D5D6D7S2S3S5HJHQHK")
should return "C5C7CQD2D5D6S3SJSKSAH2H5H10"

```

S=lambda h,t={ord(s):' '+s for s in 'SDHC'}:h.translate(t).split()
sort_poker=lambda a,b:(lambda s,r:''.join(sorted(S(a),key=lambda c:(s[c[0]],r[c[1]])))
)(*[{c[0]:i for i,c in enumerate(S(p))}for p in(b,"2 3 4 5 6 7 8 9 10 J Q K A")])


Solve in Python:
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process  --myjinxin2015 said

# Description:
 Give you two number `m` and `n`(two positive integer, m < n), make a triangle pattern with number sequence `m to n`. The order is clockwise, starting from the top corner, like this:

```
 When m=1 n=10  triangle is:
    1
   9 2
  8 0 3
 7 6 5 4
```
 Note: The pattern only uses the last digit of each number; Each row separated by "\n"; Each digit separated by a space; Left side may need pad some spaces, but don't pad the right side; If `m to n` can not make the triangle, return `""`.

# Some examples:

```
makeTriangle(1,3) should return:
 1
3 2

makeTriangle(6,20) should return:

    6
   7 7
  6 8 8
 5 0 9 9
4 3 2 1 0

makeTriangle(1,12) should return ""

```

def make_triangle(m,n):
    size = ((8*(n-m+1)+1)**.5-1)/2
    if size % 1 : return ''

    grid = [[' ' for _ in range(int(size)*2-1)] for _ in range(int(size))]
    i,j = 0,int(size-1)
    grid[i][j] = str(m%10)

    while m<n:
        for inc,dec in [(1,1),(0,-2),(-1,1)]:
            while 0<=i+inc<size and 0<=j+dec<size*2-1 and grid[i+inc][j+dec].isspace():
                i, j, m = i+inc, j+dec, m+1
                grid[i][j] = str(m%10)

    return '\n'.join([''.join(i).rstrip() for i in grid])


Solve in Python:
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process  --myjinxin2015 said

# Description:
 Given a string `str` that contains some "(" or ")". Your task is to find the longest substring in `str`(all brackets in the substring are closed). The result is the length of the longest substring.

 For example:
 ```
 str = "()()("
 findLongest(str) === 4
 "()()" is the longest substring
 ```

# Note:
 - All inputs are valid.
 - If no such substring found, return 0.
 - Please pay attention to the performance of code. ;-)
 - In the performance test(100000 brackets str x 100 testcases), the time consuming of each test case should be within 35ms. This means, your code should run as fast as a rocket ;-)

# Some Examples
 ```
 findLongest("()") === 2
 findLongest("()(") === 2
 findLongest("()()") === 4
 findLongest("()()(") === 4
 findLongest("(()())") === 6
 findLongest("(()(())") === 6
 findLongest("())(()))") === 4
 findLongest("))((") === 0
 findLongest("") === 0
 ```

def find_longest(st):
    res,pos=0,[0]
    for i,b in enumerate(st,1):
        if b=="(": pos.append(i)
        else:
            try:pos.pop();res=max(res,i-pos[-1])
            except:pos.append(i)
    return res


Solve in Python:
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process  --myjinxin2015 said

# Description:
 Given two array of integers(`arr1`,`arr2`). Your task is going to find a pair of numbers(an element in arr1, and another element in arr2), their difference is as big as possible(absolute value); Again, you should to find a pair of numbers, their difference is as small as possible. Return the maximum and minimum difference values by an array: `[  max difference,  min difference  ]`

 For example:
 ```
 Given arr1 = [3,10,5], arr2 = [20,7,15,8]
 should return [17,2] because 20 - 3 = 17, 10 - 8 = 2
 ```

# Note:
 - arr1 and arr2 contains only integers(positive, negative or 0);
 - arr1 and arr2 may have different lengths, they always has at least one element;
 - All inputs are valid.
 - This is a simple version, if you want some challenges, [try the challenge version](https://www.codewars.com/kata/583c592928a0c0449d000099).

# Some Examples
 ```
 maxAndMin([3,10,5],[20,7,15,8]) === [17,2]
 maxAndMin([3],[20]) === [17,17]
 maxAndMin([3,10,5],[3,10,5]) === [7,0]
 maxAndMin([1,2,3,4,5],[6,7,8,9,10]) === [9,1]
 ```

def max_and_min(arr1,arr2):
    return [max(abs(a-b) for a in arr1 for b in arr2), min(abs(a-b) for a in arr1 for b in arr2)]


Solve in Python:
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process  --myjinxin2015 said

# Description:
 In kindergarten, the teacher gave the children some candies. The number of candies each child gets is not always the same. Here is an array `candies`(all elements are positive integer). It's the number of candy for each child:
 ```
 candies = [10,2,8,22,16,4,10,6,14,20]
 ```
 The teacher asked the children to form a circle and play a game: Each child gives half of his candies to the child on his right(at the same time). If the number of children's candy is an odd number, the teacher will give him an extra candy, so that he can evenly distribute his candy.

 Repeat such distribute process, until all the children's candies are equal in number.

 You should return two numbers: 1.How many times of distribution; 2. After the game, the number of each child's candy. Returns the result using an array that contains two elements.

# Some examples:

```
      candies = [ 1,2,3,4,5 ]
Distribution 1: [ 4,2,3,4,5 ]
Distribution 2: [ 5,3,3,4,5 ]
Distribution 3: [ 6,5,4,4,5 ]
Distribution 4: [ 6,6,5,4,5 ]
Distribution 5: [ 6,6,6,5,5 ]
Distribution 6: [ 6,6,6,6,6 ]
So, we need return: [6,6]

distributionOfCandy([1,2,3,4,5]) === [6,6]

       candies = [ 10,  2,  8, 22, 16,  4, 10,  6, 14, 20 ]
distribution  1: [ 15,  6,  5, 15, 19, 10,  7,  8, 10, 17 ]
distribution  2: [ 17, 11,  6, 11, 18, 15,  9,  8,  9, 14 ]
distribution  3: [ 16, 15,  9,  9, 15, 17, 13,  9,  9, 12 ]
distribution  4: [ 14, 16, 13, 10, 13, 17, 16, 12, 10, 11 ]
distribution  5: [ 13, 15, 15, 12, 12, 16, 17, 14, 11, 11 ]
distribution  6: [ 13, 15, 16, 14, 12, 14, 17, 16, 13, 12 ]
distribution  7: [ 13, 15, 16, 15, 13, 13, 16, 17, 15, 13 ]
distribution  8: [ 14, 15, 16, 16, 15, 14, 15, 17, 17, 15 ]
distribution  9: [ 15, 15, 16, 16, 16, 15, 15, 17, 18, 17 ]
distribution 10: [ 17, 16, 16, 16, 16, 16, 16, 17, 18, 18 ]
distribution 11: [ 18, 17, 16, 16, 16, 16, 16, 17, 18, 18 ]
distribution 12:...

from itertools import count

def distribution_of_candy(a):
    for i in count():
        if all(x == a[0] for x in a):
            return [i, a[0]]
        a = [x + x % 2 for x in a]
        a = [(x + y) // 2 for x, y in zip(a, a[1:] + [a[0]])]


Solve in Python:
A "graph" consists of "nodes", also known as "vertices". Nodes may or may not be connected with one another.
In our definition below the node "A0" is connected with the node "A3", but "A0" is not connected with "A1".

The connecting line between two nodes is called an edge. If the edges between the nodes are undirected,
the graph is called an undirected graph. A weighted graph is a graph in which a number (the weight) is assigned to each edge.
A graph is acyclic if it has no loop.

A graph can be represented as a dictionary:

`graph = {'A0': [('A3', 1), ('A5', 4)],
 'A1': [('A2', 2)],
 'A2': [('A1', 1), ('A2', 2), ('A3', 1), ('A4', 1)],
 'A3': [('A0', 1), ('A2', 1)],
 'A4': [('A2', 1), ('A4', 1)],
 'A5': [('A3', 3)]
}`

Here the nodes are A0...A5; following each nodes is the edges list of linked nodes with their weight.
A0 is linked to A3 with a weight of 1 and to A5 with weight 4. A dictionary is not ordered but the list
of linked nodes is sorted. So:

`'A0': [('A3', 1), ('A5', 4)]`is correct but `'A0': [('A5', 4), ('A3', 1)]`is not.

The edges E of a graph G induce a binary relation that is called the adjacency relation of G.
One can associate an adjacency matrix:

`M =
[[0, 0, 0, 1, 0, 4],
 [0, 0, 2, 0, 0, 0],
 [0, 1, 2, 1, 1, 0],
 [1, 0, 1, 0, 0, 0],
 [0, 0, 1, 0, 1, 0],
 [0, 0, 0, 3, 0, 0]]`

Let us imagine that lines are numbered from A0 to A5 and the same for columns.
The first line correspond to A0 and we can see that A0 is connected to A3 with weight 1, A0 is also connected to A5 with weight 4.

Another way is to use an adjacency list: An adjacency list representation for a graph
associates each vertex in the graph with the collection of its neighboring edges:

`L = [['A0', [('A3', 1), ('A5', 4)]],
     ['A1', [('A2', 2)]],
     ['A2', [('A1', 1), ('A2', 2), ('A3', 1), ('A4', 1)]],
     ['A3', [('A0', 1), ('A2', 1)]],
     ['A4', [('A2', 1), ('A4', 1)]],
     ['A5', [('A3', 3)]]] `

L is sorted in order A0 to A5 and each sublist is sorted as in a graph dictionary.

In the kata...

class Graph():

    def __init__(self, vertices_num):
        self.v = vertices_num
        self.nodes = [f'A{n}' for n in range(vertices_num)]

    # adjacency matrix to dictionary
    def adjmat_2_graph(self, adjm):
        return {
            self.nodes[src_index]: [
                (self.nodes[dst_index], weight)
                for dst_index, weight in enumerate(weights)
                if weight > 0
            ]
            for src_index, weights in enumerate(adjm)
            if any(weight > 0 for weight in weights)
        }

    # dictionary to adjacency matrix
    def graph_2_mat(self, graph):
        result = [[0 for _ in range(self.v)] for _ in range(self.v)]
        for src, edges in graph.items():
            src_index = self.nodes.index(src)
            for dst, weight in edges:
                dst_index = self.nodes.index(dst)
                result[src_index][dst_index] = weight
        return result

    # dictionary to adjacency list
    def graph_2_list(self, graph):
        return sorted([
            [src, edges]
            for src, edges in graph.items()
        ], key=lambda x: x[0])

    # adjacency list to dictionary
    def list_2_graph(self, lst):
        return {
            src: edges
            for src, edges in lst
        }

    # adjacency matrix to adjacency list
    def mat_2_list(self, mat):
        return self.graph_2_list(self.adjmat_2_graph(mat))

    # adjacency list to adjacency matrix
    def list_2_mat(self, lst):
        return self.graph_2_mat(self.list_2_graph(lst))

    # all paths from node start_vertex to node end_vertex
    def find_all_paths(self, graph, start_vertex, end_vertex, seen=None):
        if start_vertex == end_vertex and seen is None: # Non-recursive case only
            return [start_vertex]

        if seen is None:
            seen = set()
        seen = seen | {start_vertex}
        next_options = [dst for dst, weight in graph.get(start_vertex, []) if dst not in seen]
        paths = [
    ...


Solve in Python:
A **Seven Segment Display** is an electronic display device, used to display decimal or hexadecimal numerals. It involves seven led segments that are lit in specific combinations to represent a specific numeral. An example of each combination is shown below:

![seven segment display](https://upload.wikimedia.org/wikipedia/commons/9/97/7-segments_Indicator.gif)

For this Kata, you must accept an integer in the range `0 - 999999` and print it as a string (in decimal format), with each digit being represented as its own seven segment display (6x seven segment displays in total). Each of the individual led segments per display should be represented by three hashes `###`. Vertical bars `|` (ASCII 124) represent the edges of each display, with a single whitespace on either side between the edge and the area of the led segments. An example of the expected output is shown below:
```
segment_display(123456) =
|       |  ###  |  ###  |       |  ###  |  ###  |
|     # |     # |     # | #   # | #     | #     |
|     # |     # |     # | #   # | #     | #     |
|     # |     # |     # | #   # | #     | #     |
|       |  ###  |  ###  |  ###  |  ###  |  ###  |
|     # | #     |     # |     # |     # | #   # |
|     # | #     |     # |     # |     # | #   # |
|     # | #     |     # |     # |     # | #   # |
|       |  ###  |  ###  |       |  ###  |  ###  |
```
For clarity, the entire set of required combinations is provided below:

```
|  ###  |       |  ###  |  ###  |       |  ###  |  ###  |  ###  |  ###  |  ###  |
| #   # |     # |     # |     # | #   # | #     | #     |     # | #   # | #   # |
| #   # |     # |     # |     # | #   # | #     | #     |     # | #   # | #   # |
| #   # |     # |     # |     # | #   # | #     | #     |     # | #   # | #   # |
|       |       |  ###  |  ###  |  ###  |  ###  |  ###  |       |  ###  |  ###  |
| #   # |     # | #     |     # |     # |     # | #   # |     # | #   # |     # |
| #   # |     # | #     |     # |     # |     # | #   # |     # | #   # |     # |
| #   # |     # | #    ...


Solve in Python:
A **bouncy number** is a positive integer whose digits neither increase nor decrease. For example, `1235` is an increasing number, `5321` is a decreasing number, and `2351` is a bouncy number. By definition, all numbers under `100` are non-bouncy, and `101` is the first bouncy number. To complete this kata, you must write a function that takes a number and determines if it is bouncy.

Input numbers will always be positive integers, but it never hurts to throw in some error handling : )

For clarification, the bouncy numbers between `100` and `125` are: `101, 102, 103, 104, 105, 106, 107, 108, 109, 120, and 121`.

def is_bouncy(number):
    string = str(number)
    sort = "".join(sorted(string))
    reverse = "".join(reversed(string))
    return sort != string and sort != reverse


Solve in Python:
A **pandigital number** is one that has its digits from ```1``` to ```9``` occuring only once (they do not have the digit 0).

The number ```169```, is the first pandigital square, higher than ```100```, having its square root, ```13```, pandigital too.

The number ```1728``` is the first pandigital cubic, higher than ```1000```, having its cubic root, ```12```, pandigital too.

Make the function ```pow_root_pandigit()```, that receives three arguments:

- a minimum number, ```val```

- the exponent of the n-perfect powers to search, ```n```

- ```k```, maximum amount of terms that we want in the output

The function should output a 2D-array with an amount of k pairs of numbers(or an array of an only pair if we have this case). Each pair has a nth-perfect power pandigital higher than val with its respective nth-root that is pandigital, too.

The function should work in this way:
```python
pow_root_pandigit(val, n, k) = [[root1, pow1], [root2, pow2], ...., [rootk, powk]]
"""
root1 < root2 <.....< rootk
val < pow1 < pow2 < ....< powk
root1 ^ n = pow1 // root2 ^ n = pow2 //........// rootk ^ n = powk
all pairs rooti, powi are pandigitals
"""
```
Let's see some examples:
```python
pow_root_pandigit(388, 2, 3)== [[23, 529], [24, 576], [25, 625]] # 3 pairs (k = 3)
```
For a different power:
```python
pow_root_pandigit(1750, 3, 5) == [[13, 2197], [17, 4913], [18, 5832], [19, 6859], [21, 9261]] # 5 pairs (k = 5)
```

The output in not inclusive for val.
```python
pow_root_pandigit(1728, 3, 4) == [[13, 2197], [17, 4913], [18, 5832], [19, 6859]]
# ∛1728 = 12
```

The result may have less terms than the required:
```python
pow_root_pandigit(600000000, 2, 5) == [25941, 672935481] # If the result has an only one pair, the output is an array
```
Furthermore, if the minimum value, ```val``` is high enough, the result may be an empty list:
```python
pow_root_pandigit(900000000, 2, 5) == []
```

You may suposse that the input ```val```, ```n``` will be always:  ```val > 10``` and ```n > 2```.

Enjoy it!!

from math import *

def pow_root_pandigit(val, n, k):
    '''
    Create a function to give k smaller couples of the root - pandigital numbers with the power n
    and bigger than val.
    '''
    # Create the empty list to return
    l = []
    # Put the value to zero
    if val < 0:
        val = 0
    # Case where val is bigger than the bigger pandigital number
    if val > 987654321:
        return l
    r = 1./n
    # Look for all the powers bigger than val and stop when it reach the len of the list or the
    # end of the possibility
    for i in range(int(ceil(((val+1) ** r))), int(987654322 ** r)):
        string = str(i ** n)
        if len(set(string)) == len(string) and '0' not in string and '0' not in str(i) and len(set(str(i))) == len(str(i)):
            l.append([i, int(string)])
        if len(l) == k : break
    # Check if only one element
    if len(l) == 1:
        l = l[0]
    return l


Solve in Python:
A *Vampire number* is a positive integer `z` with a factorization `x * y = z` such that

- `x` and `y` have the same number of digits and
- the multiset of digits of `z` is equal to the multiset of digits of `x` and `y`.
- Additionally, to avoid trivialities, `x` and `y` may not both end with `0`.

In this case, `x` and `y` are called *fangs* of `z`. (The fangs of a Vampire number may not be unique, but this shouldn't bother us.) The first three Vampire numbers are

```
1260 = 21*60
1395 = 15*93
1435 = 35*41
```

Write an algorithm that on input `k` returns the `k`th Vampire number. To avoid time-outs, the Python version will test with `1 <= k <= 155`.

PS: In the OEIS, the Vampire numbers are sequence [A014575](https://oeis.org/A014575).

PPS: So called *Pseudo-Vampire Numbers* are treated in [this kata](http://www.codewars.com/kata/vampire-numbers-1).

import requests
from bs4 import BeautifulSoup

page = requests.get(url='https://oeis.org/A014575/b014575.txt').text
soup = BeautifulSoup(page, 'html.parser')
vampire = {int(v.split(' ')[0]): int(v.split(' ')[1]) for v in soup.text.split('\n') if v}

def VampireNumber(i):
    return vampire[i]


Solve in Python:
A *[Hamming number][1]* is a positive integer of the form 2*i*3*j*5*k*, for some non-negative integers *i*, *j*, and *k*.

Write a function that computes the *n*th smallest Hamming number.

Specifically:

  - The first smallest Hamming number is 1 = 2^(0)3^(0)5^(0)
  - The second smallest Hamming number is 2 = 2^(1)3^(0)5^(0)
  - The third smallest Hamming number is 3 = 2^(0)3^(1)5^(0)
  - The fourth smallest Hamming number is 4 = 2^(2)3^(0)5^(0)
  - The fifth smallest Hamming number is 5 = 2^(0)3^(0)5^(1)

The 20 smallest Hamming numbers are given in example test fixture.

Your code should be able to compute all of the smallest 5,000 (Clojure: 2000, NASM: 13282) Hamming numbers without timing out.

[1]:https://en.wikipedia.org/wiki/Regular_number

from heapq import *

H,Q = [1], [(2,2,1),(3,3,1),(5,5,1)]

def hamming(n):
    while len(H)<=n:
        v,root,i = heappop(Q)
        if H[-1]!=v: H.append(v)
        heappush(Q, (H[i]*root,root,i+1))
    return H[n-1]


Solve in Python:
A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.
Given a row x col grid of integers, how many 3 x 3 "magic square" subgrids are there?  (Each subgrid is contiguous).

Example 1:

Input: grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]
Output: 1
Explanation:
The following subgrid is a 3 x 3 magic square:

while this one is not:

In total, there is only one magic square inside the given grid.

Example 2:
Input: grid = [[8]]
Output: 0

Example 3:
Input: grid = [[4,4],[3,3]]
Output: 0

Example 4:
Input: grid = [[4,7,8],[9,5,1],[2,3,6]]
Output: 0

Constraints:

row == grid.length
col == grid[i].length
1 <= row, col <= 10
0 <= grid[i][j] <= 15

class Solution:
    def numMagicSquaresInside(self, grid: List[List[int]]) -> int:
        # slide window and call isMagicSquare
        if len(grid) < 3 or len(grid[0]) < 3:
            return 0
        rows = len(grid)
        cols = len(grid[0])
        magic_squares = 0
        for i in range(rows - 2):
            for j in range(cols - 2):
                window = [tmp[j:j + 3] for tmp in grid[i: i + 3]]
                if self.isMagicSquare(window):
                    magic_squares += 1

        return magic_squares

    def isMagicSquare(self, square: List[List[int]]) -> bool:
        target = square[0][0] + square[0][1] + square[0][2]
        seen = {}
        print(square)
        # check rows
        for row in square:
            tmp = 0
            for i in row:
                tmp += i
                if i in seen or i > 9 or i < 1:
                    return False
                else:
                    seen[i] = 1
            if tmp != target:
                return False

        # check cols
        for i in range(3):
            tmp = 0
            for row in square:
                tmp += row[i]

            if tmp != target:
                return False

        # check left to right diag
        tmp = 0
        for i in range(3):
            tmp += square[i][i]
        if tmp != target:
            return False

        # check right to left diag
        tmp = 0
        for i in range(3):
            tmp += square[i][2 - i]
        if tmp != target:
            return False

        return True


Solve in Python:
A Little Elephant from the Zoo of Lviv likes lucky strings, i.e., the strings that consist only of the lucky digits 4 and 7.
The Little Elephant calls some string T of the length M balanced if there exists at least one integer X (1 ≤ X ≤ M) such that the number of digits 4 in the substring T[1, X - 1] is equal to the number of digits 7 in the substring T[X, M]. For example, the string S = 7477447 is balanced since S[1, 4] = 7477 has 1 digit 4 and S[5, 7] = 447 has 1 digit 7. On the other hand, one can verify that the string S = 7 is not balanced.
The Little Elephant has the string S of the length N. He wants to know the number of such pairs of integers (L; R) that 1 ≤ L ≤ R ≤ N and the substring S[L, R]  is balanced. Help him to find this number.
Notes.

Let S be some lucky string. Then

- |S| denotes the length of the string S;

- S[i] (1 ≤ i ≤ |S|) denotes the ith character of S (the numeration of characters starts from 1);

-  S[L, R] (1 ≤ L ≤ R ≤ |S|) denotes the string with the following sequence of characters: S[L], S[L + 1], ..., S[R], and is called a substring of S. For L > R we mean by S[L, R] an empty string.

-----Input-----
The first line of the input file contains a single integer T, the number of test cases. Each of the following T lines contains one string, the string S for the corresponding test case. The input file does not contain any whitespaces.

-----Output-----
For each test case output a single line containing the answer for this test case.

-----Constraints-----
1 ≤ T ≤ 10

1 ≤ |S| ≤ 100000

S consists only of the lucky digits 4 and 7.

-----Example-----
Input:
4
47
74
477
4747477

Output:
2
2
3
23

-----Explanation-----

In the first test case balance substrings are S[1, 1] = 4 and S[1, 2] = 47.
In the second test case balance substrings are S[2, 2] = 4 and S[1, 2] = 74.
Unfortunately, we can't provide you with the explanations of the third and the fourth test cases. You should figure it out by yourself. Please, don't ask about this in comments.

tcase=int(eval(input()))
i=0
while(tcase):
    tcase-=1
    a=str(input())
    j=0
    i=0
    rem=0
    length=len(a)
    ans=(length*(length+1))/2
    #print ans,
    while(i<length):
        if(a[i]=='7'):
            rem+=(i-j+1)
            #print i,j,
        else:
            j=i+1
        i+=1
    ans-= rem;
    print(ans);


Solve in Python:
A Madhav array has the following property:

```a[0] = a[1] + a[2] = a[3] + a[4] + a[5] = a[6] + a[7] + a[8] + a[9] = ...```

Complete the function/method that returns `true` if the given array is a Madhav array, otherwise it returns `false`.

*Edge cases: An array of length* `0` *or* `1` *should not be considered a Madhav array as there is nothing to compare.*

def is_madhav_array(arr):
    def check(a, n=1):
        return True if len(a) == n else sum(a[:n]) == sum(a[n:2*n+1]) and check(a[n:], n + 1)
    return False if len(arr) <= 1 else check(arr)


Solve in Python:
A Magic Square contains the integers 1 to n^(2), arranged in an n by n array such that the columns, rows and both main diagonals add up to the same number.For doubly even positive integers (multiples of 4) the following method can be used to create a magic square.
Fill an array with the numbers 1 to n^(2) in succession. Then, for each 4 by 4 subarray, replace the entries on the blue and red diagonals by n^(2)+1-aij.
So, in the following example, a11 (row 1, column 1) was initially 1 and is replaced by 8^(2)+1-1 = 64

    tab1 { padding-left: 2em; }
    fc1  { font color="blue"}

n=8
642 3 61606 7 57
9 55541213515016
1747462021434224
4026273736303133
3234352928383925
4123224445191848
4915145253111056
8 58595 4 62631

The function even_magic() should return a 2D array as follows:-
Example:
n=4: Output: [[16,2,3,13],[5,11,10,8],[9,7,6,12],[4,14,15,1]]

162 3 13
5 11108
9 7 6 12
4 14151

Only doubly even numbers will be passed to the function in the tests.

See mathworld.wolfram.com for further details.

def even_magic(n):
    n2_1 = n ** 2 + 1
    return [
        [n2_1 - (i*n+j+1) if i % 4 == j % 4 or (i + j) % 4 == 3 else i*n+j+1 for j in range(n)]
        for i in range(n)
    ]


Solve in Python:
A Narcissistic Number is a number of length n in which the sum of its digits to the power of n is equal to the original number. If this seems confusing, refer to the example below.

Ex: 153, where n = 3 (number of digits in 153)
1^(3) + 5^(3) + 3^(3) = 153

Write a method is_narcissistic(i) (in Haskell: isNarcissistic :: Integer -> Bool) which returns whether or not i is a Narcissistic Number.

def is_narcissistic(i):
    n = len(str(i))
    lst = list(str(i))
    answer = 0
    for value in lst:
        answer += int(value)**n
    return answer == i


Solve in Python:
A Tic-Tac-Toe board is given as a string array board. Return True if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game.

The board is a 3 x 3 array, and consists of characters " ", "X", and "O".  The " " character represents an empty square.

Here are the rules of Tic-Tac-Toe:

       Players take turns placing characters into empty squares (" ").
       The first player always places "X" characters, while the second player always places "O" characters.
       "X" and "O" characters are always placed into empty squares, never filled ones.
       The game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal.
       The game also ends if all squares are non-empty.
       No more moves can be played if the game is over.

Example 1:
Input: board = ["O  ", "   ", "   "]
Output: false
Explanation: The first player always plays "X".

Example 2:
Input: board = ["XOX", " X ", "   "]
Output: false
Explanation: Players take turns making moves.

Example 3:
Input: board = ["XXX", "   ", "OOO"]
Output: false

Example 4:
Input: board = ["XOX", "O O", "XOX"]
Output: true

Note:

       board is a length-3 array of strings, where each string board[i] has length 3.
       Each board[i][j] is a character in the set {" ", "X", "O"}.

class Solution:
     def swimInWater(self, grid):
         """
         :type grid: List[List[int]]
         :rtype: int
         """
         m, n = len(grid), len(grid[0])
         seen = set()
         seen.add((0, 0))
         heap = [(grid[0][0], 0, 0)]
         ans = 0
         while heap:
             h, i, j = heapq.heappop(heap)
             ans = max(ans, h)
             if i == m-1 and j == n-1:
                 return ans
             for a, b in [[i-1, j], [i+1, j], [i, j-1], [i, j+1]]:
                 if 0 <= a < m and 0 <= b < n and (a, b) not in seen:
                     heapq.heappush(heap, (grid[a][b], a, b))
                     seen.add((a, b))


Solve in Python:
A Train started its journey at x=-infinity is travelling on the x-Coordinate Axis. Given n passengers and the coordinates $b_i$ and $d_i$ for each of the $ith$ passenger at which they board and leave from the train respectively. Due to current COVID-19 crisis, the train is monitored at each mile/coordinate. The infection degree of the train at each mile is equal to the total passengers present in the train at that mile/coordinate. The train stops its journey if no more passengers are there to board the train. The term infection severity of the journey is defined as the sum of infection degrees noted at each mile. Find the Infection severity of the journey. Note: A passenger is considered for calculation of infection degree at both boarding and leaving stations.

Since the answer can be very large, print it modulo $(10^9)+7$.

-----Input:-----
- First line will contain $N$, number of passengers. Then the $N$ lines follow.
- $i$th line contains two integers $b_i, d_i$ , the boarding and departure mile of $i$th passenger.

-----Output:-----
Print a single value, the Infection Severity of the journey modulo $(10^9)+7$.

-----Constraints-----
- $0 \leq N \leq 100000$
- $-500000 \leq b_i \leq 500000$
- $-500000 \leq d_i \leq 500000$

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

0 2

1 3

-1 4

-----Sample Output:-----
12

-----EXPLANATION:-----
Infection degree at :

-1 is 1

0 is 2

1 is 3

2 is 3

3 is 2

4 is 1

Calculation started at mile -1 and ended at mile 4. Infection Severity = 1+2+3+3+2+1 =12

# cook your dish here
M=int(1e9+7)
I=lambda:list(map(int,input().split()))
n=I()[0]
d,e={},{}
for i in range(-500000,500001):
    d[i],e[i]=0,0
for i in range(n):
    a,b=I()
    d[a]+=1
    e[b]+=1

ans,cnt=0,0

for i in range(-500000,500001):
    if(d[i]):
        cnt+=d[i]
    ans+=cnt
    if(ans>=M):
        ans-=M
    if(ans<0):
        ans+=M
    if(e[i]):
        cnt-=e[i]
print(ans)


Solve in Python:
A [Mersenne prime](https://en.wikipedia.org/wiki/Mersenne_prime) is a prime number that can be represented as:
Mn = 2^(n) - 1. Therefore, every Mersenne prime is one less than a power of two.

Write a function that will return whether the given integer `n` will produce a Mersenne prime or not.

The tests will check random integers up to 2000.


Solve in Python:
A [Narcissistic Number](https://en.wikipedia.org/wiki/Narcissistic_number) is a positive number which is the sum of its own digits, each raised to the power of the number of digits in a given base. In this Kata, we will restrict ourselves to decimal (base 10).

For example, take 153 (3 digits):
```
    1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
```
and 1634 (4 digits):
```
    1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634
```

The Challenge:

Your code must return **true or false** depending upon whether the given number is a Narcissistic number in base 10.

Error checking for text strings or other invalid inputs is not required, only valid positive non-zero integers will be passed into the function.

def narcissistic( value ):
    vstr = str(value)
    nvalue = sum(int(i)**len(vstr) for i in vstr)
    return nvalue == value


Solve in Python:
A [Power Law](https://en.wikipedia.org/wiki/Power_law) distribution occurs whenever "a relative change in one quantity results in a proportional relative change in the other quantity." For example, if *y* = 120 when *x* = 1 and *y* = 60 when *x* = 2 (i.e. *y* halves whenever *x* doubles) then when *x* = 4, *y* = 30 and when *x* = 8, *y* = 15.

Therefore, if I give you any pair of co-ordinates (x1,y1) and (x2,y2) in a power law distribution, you can plot the entire rest of the distribution and tell me the value of *y* for any other value of *x*.

Given a pair of co-ordinates (x1,y1) and (x2,y2) and another x co-ordinate *x3*, return the value of *y3*

```
powerLaw(x1y1, x2y2, x3)
e.g. powerLaw([1,120], [2,60], 4)
- when x = 1, y = 120
- when x = 2, y = 60
- therefore whenever x doubles, y halves
- therefore when x = 4, y = 60 * 0.5
- therfore solution = 30
```

(x1,y1) and (x2,y2) will be given as arrays. Answer should be to the nearest integer, but random tests will give you leeway of 1% of the reference solution to account for possible discrepancies from different methods.

from math import log

def power_law(x1y1, x2y2, x3):
    try:
        k = (log(x1y1[1]) - log(x2y2[1])) / (log(x1y1[0]) - log(x2y2[0]))
        a = x1y1[1] / (x1y1[0] ** k)
        return round(a * x3 ** k)
    except ZeroDivisionError:
        return x2y2[1]


Solve in Python:
A [Word Square](https://en.wikipedia.org/wiki/Word_square) is a set of words written out in a square grid, such that the same words can be read both horizontally and vertically. The number of words, equal to the number of letters in each word, is known as the *order* of the square.

For example, this is an *order* `5` square found in the ruins of Herculaneum:

![](https://i.gyazo.com/e226262e3ada421d4323369fb6cf66a6.jpg)

Given a string of various uppercase `letters`, check whether a *Word Square* can be formed from it.

Note that you should use each letter from `letters` the exact number of times it occurs in the string. If a *Word Square* can be formed, return `true`, otherwise return `false`.

__Example__

  * For `letters = "SATORAREPOTENETOPERAROTAS"`, the output should be
  `WordSquare(letters) = true`.
    It is possible to form a *word square* in the example above.

  * For `letters = "AAAAEEEENOOOOPPRRRRSSTTTT"`, (which is sorted form of `"SATORAREPOTENETOPERAROTAS"`), the output should also be
  `WordSquare(letters) = true`.

  * For `letters = "NOTSQUARE"`, the output should be
  `WordSquare(letters) = false`.

__Input/Output__

* [input] string letters

  A string of uppercase English letters.

  Constraints: `3 ≤ letters.length ≤ 100`.

* [output] boolean

  `true`, if a Word Square can be formed;

  `false`, if a Word Square cannot be formed.

def word_square(s):
    li = [s.count(i) for i in set(s)]
    t = sum(i for i in li)**0.5
    return int(t) == t and sum(i&1 for i in li) <= t


Solve in Python:
A [binary search tree](https://en.wikipedia.org/wiki/Binary_search_tree) is a binary tree that is ordered. This means that if you were to convert the tree to an array using an in-order traversal, the array would be in sorted order. The benefit gained by this ordering is that when the tree is balanced, searching is a logarithmic time operation, since each node you look at that isn't the one you're searching for lets you discard half of the tree.

If you haven't worked with binary trees before or don't understand what a traversal is, you can learn more about that here: https://www.codewars.com/kata/binary-tree-traversal.

In this kata, you will write a function that will validate that a given binary tree is a binary search tree. The sort order is not predefined so it should work with either.

These are valid binary search trees:

        5
       / \
      2   7
     / \   \
    1   3   9

      7
     / \
    9   2

while these are not:

      1
     / \
    2   3

      5
     / \
    2   9
     \
      7

There are several different approaches you can take to solve this kata. If you're not as comfortable with recursion I'd recommend practicing that.

Note: no test case tree will contain duplicate numbers.

class T:
    def __init__(self,value,left=None,right=None):
        self.value=value
        self.left=left
        self.right=right

def inorder(self):
    if not self:
        return []
    return inorder(self.left) + [self.value] + inorder(self.right)

def is_bst(node):
    curr=inorder(node)
    return sorted(curr) in (curr, curr[::-1])


Solve in Python:
A [perfect power](https://en.wikipedia.org/wiki/Perfect_power) is a classification of positive integers:

> In mathematics, a **perfect power** is a positive integer that can be expressed as an integer power of another positive integer. More formally, n is a perfect power if there exist natural numbers m > 1, and k > 1 such that m^(k) = n.

Your task is to check wheter a given integer is a perfect power. If it is a perfect power, return a pair `m` and `k` with m^(k) = n as a proof. Otherwise return `Nothing`, `Nil`, `null`, `NULL`, `None` or your language's equivalent.

**Note:** For a perfect power, there might be several pairs. For example `81 = 3^4 = 9^2`, so `(3,4)` and `(9,2)` are valid solutions. However, the tests take care of this, so if a number is a perfect power, return any pair that proves it.

### Examples
```python
isPP(4) => [2,2]
isPP(9) => [3,2]
isPP(5) => None
```

from math import log
def isPP(n):
    for m in range(2,int(n**0.5)+1):
        k = round(log(n, m), 13)
        if k % 1 == 0:
            return [m ,k]
    return


Solve in Python:
A [sequence or a series](http://world.mathigon.org/Sequences), in mathematics, is a string of objects, like numbers, that follow a particular pattern. The individual elements in a sequence are called terms. A simple example is `3, 6, 9, 12, 15, 18, 21, ...`, where the pattern is: _"add 3 to the previous term"_.

In this kata, we will be using a more complicated sequence:   `0, 1, 3, 6, 10, 15, 21, 28, ...`
This sequence is generated with the pattern: _"the nth term is the sum of numbers from 0 to n, inclusive"_.

```
[ 0,  1,    3,      6,   ...]
  0  0+1  0+1+2  0+1+2+3
```

## Your Task

Complete the function that takes an integer `n` and returns a list/array of length `abs(n) + 1` of the arithmetic series explained above. When`n < 0` return the sequence with negative terms.

## Examples

```
 5  -->  [0,  1,  3,  6,  10,  15]
-5  -->  [0, -1, -3, -6, -10, -15]
 7  -->  [0,  1,  3,  6,  10,  15,  21,  28]
```

def sum_of_n(n):
    sign, n = (1, -1)[n < 0], abs(n)
    return [sign * (i * i + i) / 2 for i in range (n + 1)]


Solve in Python:
A `Nice array` is defined to be an array where for every value `n` in the array, there is also an element `n-1` or `n+1` in the array.

example:

```
[2,10,9,3] is Nice array because

2=3-1
10=9+1
3=2+1
9=10-1
```
Write a function named `isNice`/`IsNice` that returns `true` if its array argument is a Nice array, else `false`. You should also return `false` if `input` array has `no` elements.

def is_nice(arr):
    for x in arr:
        if x + 1 not in arr and x - 1 not in arr:
            return False
    return True and len(arr) > 0


Solve in Python:
A `bouncy number` is a positive integer whose digits neither increase nor decrease. For example, 1235 is an increasing number, 5321 is a decreasing number, and 2351 is a bouncy number. By definition, all numbers under 100 are non-bouncy, and 101 is the first bouncy number.

Determining if a number is bouncy is easy, but counting all bouncy numbers with N digits can be challenging for large values of N. To complete this kata, you must write a function that takes a number N and return the count of bouncy numbers with N digits. For example, a "4 digit" number includes zero-padded, smaller numbers, such as 0001, 0002, up to 9999.

For clarification, the bouncy numbers between 100 and 125 are: 101, 102, 103, 104, 105, 106, 107, 108, 109, 120, and 121.

from functools import reduce

def nCr(n, k):

  numer = reduce(lambda x, y: x * y,
                 list(range(n, n - k, -1)))
  denom = reduce(lambda x, y: x * y,
                 list(range(1, k + 1)))

  return numer // denom

def bouncy_count(number):
    r = int((nCr(number + 10, 10) +
         nCr(number + 9, 9)
         - 2 - 10 * number))

    return 10**number - r % (1000000000000000000 + 7) - 1


Solve in Python:
A balanced parenthesis string is defined as follows:
- The empty string is balanced
- If P is balanced, (P) is also
- If P and Q are balanced, PQ is also balanced
You are given two even integers n$n$ and k$k$. Find any balanced paranthesis string of length n$n$ that doesn't contain a balanced substring of length k$k$, or claim that no such string exists.

-----Input-----
- First line will contain T$T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line containing n$n$ and k$k$.

-----Output-----
For every testcase, print on a new line, any balanced paranthesis string of length n$n$ that doesn't contain a balanced substring of length k$k$. If there doesn't exist any such string, print −1$-1$ instead.

-----Constraints-----
- 1≤T≤50000$1 \leq T \leq 50000$
- 2≤k≤n≤105$2 \leq k \leq n \leq 10^5$
- Sum of n$n$ over all testcases doesn't exceed 105$10^5$.
- n$n$ and k$k$ are both even integers.

-----Example Input-----
2
4 2
8 6

-----Example Output-----
-1
(())(())

-----Explanation-----
In the first testcase, the only balanced strings of length 4$4$ are (()) and ()(), both of which contain () as a substring.
In the second testcase, (())(()) is a balanced string that doesn't contain any balanced substring of length 6$6$.

a = int(input())
while a!=0:
    b,c = map(int,input().split())
    p = c-2
    if p==0 or p==2 or b==c:
        print(-1)
    else:
        q = b//p
        r = b%p
        k=0

        if p+r == c:
            print("(", end="")
            while k != q:

                for i in range(1, p + 1):

                    if i <= (p) // 2:
                        print("(", end="")
                    else:
                        print(")", end="")
                k+=1

            print(")")

            a-=1
            print()
            continue

        while k!=q:

            for i in range(1,p+1):

                if i<= p//2:
                    print("(",end="")
                else:
                    print(")",end="")
            k+=1
        for i in range(1,r+1):
            if i<=r//2:
                print("(",end="")
            else:
                print(")",end="")

        print()

    a-=1


Solve in Python:
A beautiful sequence is defined as a sequence that do not have any repeating elements in it.
You will be given any random sequence of integers, and you have to tell whether it is a beautiful sequence or not.

-----Input:-----
- The first line of the input contains a single integer $T$. $T$ denoting the number of test cases. The description of $T$ test cases is as follows.
- The next line of the input contains a single integer $N$. $N$ denotes the total number of elements in the sequence.
- The next line of the input contains $N$ space-separated integers $A1, A2, A3...An$ denoting the sequence.

-----Output:-----
- Print "prekrasnyy"(without quotes) if the given sequence is a beautiful sequence, else print "ne krasivo"(without quotes)
Note: each test case output must be printed on new line

-----Constraints:-----
- $1 \leq T \leq 10^2$
- $1 \leq N \leq 10^3$
- $1 \leq A1, A2, A3...An \leq 10^5$

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

-----Sample Output:-----
prekrasnyy
ne krasivo

-----Explanation:-----
-
As 1st sequence do not have any elements repeating, hence it is a beautiful sequence
-
As in 2nd sequence the element 1 is repeated twice, hence it is not a beautiful sequence

for _ in range(int(input())):
    n = int(input())
    arr = sorted([int(k) for k in input().split()])
    res = True
    for i in range(len(arr) - 1):
        if(arr[i] == arr[i+1]):
            res = False
            break
    if(res):
        print("prekrasnyy")
    else:
        print("ne krasivo")


Solve in Python:
A binary gap within a positive number ```num``` is any sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of  ```num```.
    For example:
    ```9``` has binary representation ```1001``` and contains a binary gap of length ```2```.
    ```529``` has binary representation ```1000010001``` and contains two binary gaps: one of length ```4``` and one of length ```3```.
    ```20``` has binary representation ```10100``` and contains one binary gap of length ```1```.
    ```15``` has binary representation ```1111``` and has ```0``` binary gaps.
    Write ```function gap(num)```
that,  given a positive ```num```,  returns the length of its longest binary gap. The function should return ```0``` if ```num``` doesn't contain a binary gap.

def gap(num):
    return len(max((bin(num)[2:]).rstrip('0').split('1')))


Solve in Python:
A binary string is called a self-destructing string if it can reduced to an empty string by performing the following operation some number of times (possibly zero): Choose a valid integer $i$ such that the $i$-th character of the current string is different from the $i+1$-th character, and remove these two characters from the string.
You are given a binary string $s$. Your task is to convert $s$ to a self-destructing string. To do that, you may perform the following operation any number of times (possibly zero): Choose an integer $i$ ($1 \le i \le |s|-1$) such that the $i$-th character of $s$ is different from the $i+1$-th character, and invert one of these characters (inverting a character means changing '0' to '1' or '1' to '0', e.g. the string "01" can be changed to "00").
Find the smallest number of operations required to convert $s$ to a self-destructing string or determine that it is impossible.

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

-----Output-----
For each test case, print a single line containing one integer ― the smallest required number of operations or $-1$ if it is impossible to convert $s$ to a self-destructing string.

-----Constraints-----
- $1 \le T \le 1,000$
- $1 \le |s| \le 10^6$
- $s$ contains only characters '0' and '1'
- the sum of $|s|$ over all test cases does not exceed $10^6$

-----Example Input-----
3
001101
1101
110

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

-----Explanation-----
Example case 1: We already have a self-destructing string because "001101" can be converted to "0101", to "01" and finally to an empty string.
Example case 2: We can choose $i=3$ (since $s_3 \neq s_4$) and then invert $s_4$ to obtain "1100", which is a self-destructing string.
Example case 3: It can be shown that "110" cannot be converted to a self-destructing string.

# cook your dish here
t = int(input())
for _ in range(t):
 s = input();
 a = s.count('0')
 b = s.count('1');
 if(len(s)%2==1 or a==0 or b==0):
  ans = -1
 else:
  ans = abs(a-b)//2;
 print(ans)


Solve in Python:
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called $k$-balanced if every substring of size $k$ of this bitstring has an equal amount of 0 and 1 characters ($\frac{k}{2}$ of each).

You are given an integer $k$ and a string $s$ which is composed only of characters 0, 1, and ?. You need to determine whether you can make a $k$-balanced bitstring by replacing every ? characters in $s$ with either 0 or 1.

A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.

-----Input-----

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

The first line of each test case contains two integers $n$ and $k$ ($2 \le k \le n \le 3 \cdot 10^5$, $k$ is even)  — the length of the string and the parameter for a balanced bitstring.

The next line contains the string $s$ ($|s| = n$). It is given that $s$ consists of only 0, 1, and ?.

It is guaranteed that the sum of $n$ over all test cases does not exceed $3 \cdot 10^5$.

-----Output-----

For each test case, print YES if we can replace every ? in $s$ with 0 or 1 such that the resulting bitstring is $k$-balanced, or NO if it is not possible.

-----Example-----
Input
9
6 4
100110
3 2
1?1
3 2
1?0
4 4
????
7 4
1?0??1?
10 10
11??11??11
4 2
1??1
4 4
?0?0
6 2
????00

Output
YES
YES
NO
YES
YES
NO
NO
YES
NO

-----Note-----

For the first test case, the string is already a $4$-balanced bitstring.

For the second test case, the string can be transformed into 101.

For the fourth test case, the string can be transformed into 0110.

For the fifth test case, the string can be transformed into 1100110.

import sys
input = sys.stdin.readline

t=int(input())
for tests in range(t):
    n,k=list(map(int,input().split()))
    S=input().strip()

    A=[-1]*k

    for i in range(n):
        if S[i]=="0":
            if A[i%k]==1:
                print("NO")
                break
            else:
                A[i%k]=0

        if S[i]=="1":
            if A[i%k]==0:
                print("NO")
                break
            else:
                A[i%k]=1
    else:
        Z=0
        O=0
        for i in range(k):
            if A[i]==0:
                Z+=1
            if A[i]==1:
                O+=1
        if Z>k//2 or O>k//2:
            print("NO")
        else:
            print("YES")


Solve in Python:
A boomerang is a set of 3 points that are all distinct and not in a straight line.
Given a list of three points in the plane, return whether these points are a boomerang.

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

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

Note:

points.length == 3
points[i].length == 2
0 <= points[i][j] <= 100

class Solution:
    def isBoomerang(self, points: List[List[int]]) -> bool:
        x1, y1 = points[0]
        x2, y2 = points[1]
        x3, y3 = points[2]

        return (y2 - y1) * (x3 - x1) != (y3 - y1) * (x2 - x1)


Solve in Python:
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.

Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.

You are given a regular bracket sequence $s$ and an integer number $k$. Your task is to find a regular bracket sequence of length exactly $k$ such that it is also a subsequence of $s$.

It is guaranteed that such sequence always exists.

-----Input-----

The first line contains two integers $n$ and $k$ ($2 \le k \le n \le 2 \cdot 10^5$, both $n$ and $k$ are even) — the length of $s$ and the length of the sequence you are asked to find.

The second line is a string $s$ — regular bracket sequence of length $n$.

-----Output-----

Print a single string — a regular bracket sequence of length exactly $k$ such that it is also a subsequence of $s$.

It is guaranteed that such sequence always exists.

-----Examples-----
Input
6 4
()(())

Output
()()

Input
8 8
(()(()))

Output
(()(()))

n, k = map(int, input().split())
a = [0] * n
b = ['0'] * n
c = []
s = input()
for i in range(n):
    if k != 0:
        if s[i] == '(':
            c.append(i)
        else:
            d = c.pop()
            a[i] = 1
            a[d] = 1
            k -= 2
for i in range(n):
    if a[i] == 1:
        print(s[i], end = '')


Solve in Python:
A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n.
The bus goes along both directions i.e. clockwise and counterclockwise.
Return the shortest distance between the given start and destination stops.

Example 1:

Input: distance = [1,2,3,4], start = 0, destination = 1
Output: 1
Explanation: Distance between 0 and 1 is 1 or 9, minimum is 1.

Example 2:

Input: distance = [1,2,3,4], start = 0, destination = 2
Output: 3
Explanation: Distance between 0 and 2 is 3 or 7, minimum is 3.

Example 3:

Input: distance = [1,2,3,4], start = 0, destination = 3
Output: 4
Explanation: Distance between 0 and 3 is 6 or 4, minimum is 4.

Constraints:

1 <= n <= 10^4
distance.length == n
0 <= start, destination < n
0 <= distance[i] <= 10^4

class Solution:
    def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:
        if start == destination:
            return 0

        if start > destination:
            start, destination = destination, start

        assert(start != destination)
        return min(sum(distance[start:destination]), sum(distance[:start] + distance[destination:]))


Solve in Python:
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations.  Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it.  It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination?  If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there.  If the car reaches the destination with 0 fuel left, it is still considered to have arrived.

Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.

Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).

Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel.  We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas.  We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.

Note:

1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target

class Solution:
    def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
        n = len(stations)
        dp = [[0] * (n + 1) for _ in range(n + 1)]

        for row in dp:
            row[0] = startFuel

        if startFuel >= target: return 0
        for refuels in range(1, n+1):
            for stas in range(refuels, n+1):
                station = stations[stas-1]
                dp[stas][refuels] = dp[stas-1][refuels]
                if dp[stas-1][refuels-1] >= station[0]:
                    dp[stas][refuels] = max(station[1] + dp[stas-1][refuels-1], dp[stas][refuels])

            if dp[n][refuels] >= target: return refuels

        return -1

#             for refue in range(1, n + 1):
#             for station in range(1, n + 1):
#                 dp[station][refue] = dp[station - 1][refue]
#                 if dp[station - 1][refue - 1] >= stations[station - 1][0]:
#                     dp[station][refue] = max(dp[station - 1][refue - 1] + stations[station - 1][1], dp[station][refue])

#             if dp[n][refue] >= target:
#                 return refue

#         return -1


Solve in Python:
A carpet shop sells carpets in different varieties. Each carpet can come in a different roll width and can have a different price per square meter.

Write a function `cost_of_carpet` which calculates the cost (rounded to 2 decimal places) of carpeting a room, following these constraints:

* The carpeting has to be done in one unique piece. If not possible, retrun `"error"`.
* The shop sells any length of a roll of carpets, but always with a full width.
* The cost has to be minimal.
* The length of the room passed as argument can sometimes be shorter than its width (because we define these relatively to the position of the door in the room).
* A length or width equal to zero is considered invalid, return `"error"` if it occurs.

INPUTS:

`room_width`, `room_length`, `roll_width`, `roll_cost` as floats.

OUTPUT:

`"error"` or the minimal cost of the room carpeting, rounded to two decimal places.

def cost_of_carpet(rW, rL, cW, cCost):
    rW, rL = sorted((rW, rL))
    return "error" if cW < rW or 0 in (rL, rW, cW) else round(min([rL] + [rW]*(rL<=cW)) * cW * cCost, 2)


Solve in Python:
A category page displays a set number of products per page, with pagination at the bottom allowing the user to move from page to page.

Given that you know the page you are on, how many products are in the category in total, and how many products are on any given page, how would you output a simple string showing which products you are viewing..

examples

In a category of 30 products with 10 products per page, on page 1 you would see

'Showing 1 to 10 of 30 Products.'

In a category of 26 products with 10 products per page, on page 3 you would see

'Showing 21 to 26 of 26 Products.'

In a category of 8 products with 10 products per page, on page 1 you would see

'Showing 1 to 8 of 8 Products.'

def pagination_text(page_number, page_size, total_products):
    lower = (page_number - 1) * page_size + 1
    upper = min(total_products, page_number * page_size)
    return "Showing {} to {} of {} Products.".format(lower, upper, total_products)


Solve in Python:
A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:

For 1-byte character, the first bit is a 0, followed by its unicode code.
For n-bytes character, the first n-bits are all one's, the n+1 bit is 0, followed by n-1 bytes with most significant 2 bits being 10.

This is how the UTF-8 encoding would work:

   Char. number range  |        UTF-8 octet sequence
      (hexadecimal)    |              (binary)
   --------------------+---------------------------------------------
   0000 0000-0000 007F | 0xxxxxxx
   0000 0080-0000 07FF | 110xxxxx 10xxxxxx
   0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
   0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

Given an array of integers representing the data, return whether it is a valid utf-8 encoding.

Note:
The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data.

Example 1:

data = [197, 130, 1], which represents the octet sequence: 11000101 10000010 00000001.

Return true.
It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.

Example 2:

data = [235, 140, 4], which represented the octet sequence: 11101011 10001100 00000100.

Return false.
The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character.
The next byte is a continuation byte which starts with 10 and that's correct.
But the second continuation byte does not start with 10, so it is invalid.

class Solution:
     def validUtf8(self, data):
         """
         :type data: List[int]
         :rtype: bool
         """
         count = 0
         for d in data:
             if count == 0:
                 if d >> 5 == 0b110:
                     count = 1
                 elif d >> 4 == 0b1110:
                     count = 2
                 elif d >> 3 == 0b11110:
                     count = 3
                 elif d >> 7 != 0:
                     return False
             else:
                 if d >> 6 == 0b10:
                     count -= 1
                 else:
                     return False
         return count == 0


Solve in Python:
A checksum is an algorithm that scans a packet of data and returns a single number. The idea is that if the packet is changed, the checksum will also change, so checksums are often used for detecting
transmission errors, validating document contents, and in many other situations where it is necessary to detect undesirable changes in data.

For this problem, you will implement a checksum algorithm called Quicksum. A Quicksum packet allows only uppercase letters and spaces. It always begins and ends with an uppercase letter.

Otherwise, spaces and uppercase letters can occur in any combination, including consecutive spaces.

A Quicksum is the sum of the products of each character’s position in the packet times the character’s value. A space has a value of zero, while letters have a value equal to their position in the alphabet.

So, ```A = 1```, ```B = 2```, etc., through ```Z = 26```. Here are example Quicksum calculations for the packets “ACM” and “A C M”:

  ACM
1 × 1 + 2 × 3 + 3 × 13 = 46

A C M
1 x 1 + 3 x 3 + 5 * 13 = 75

When the packet doesn't have only uppercase letters and spaces or just spaces the result to quicksum have to be zero (0).

  AbqTH #5 = 0

VALID = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"

def quicksum(packet):
    return 0 if (set(packet) - set(VALID)) else sum(VALID.index(char) * i for i, char in enumerate(packet, 1))

#    checksum = 0
#    for char in packet:
#        if not char in VALID:
#            return 0
#        checksum += VALID.index(char)
#    return checksum

    # in respect to given instructions (packet has to begin and end with uppercase)
#    if any(not char.isupper() for char in (packet[0], packet[-1])):
#        return 0


Solve in Python:
A chef has collected data on the satisfaction level of his n dishes. Chef can cook any dish in 1 unit of time.
Like-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level  i.e.  time[i]*satisfaction[i]
Return the maximum sum of Like-time coefficient that the chef can obtain after dishes preparation.
Dishes can be prepared in any order and the chef can discard some dishes to get this maximum value.

Example 1:
Input: satisfaction = [-1,-8,0,5,-9]
Output: 14
Explanation: After Removing the second and last dish, the maximum total Like-time coefficient will be equal to (-1*1 + 0*2 + 5*3 = 14). Each dish is prepared in one unit of time.
Example 2:
Input: satisfaction = [4,3,2]
Output: 20
Explanation: Dishes can be prepared in any order, (2*1 + 3*2 + 4*3 = 20)

Example 3:
Input: satisfaction = [-1,-4,-5]
Output: 0
Explanation: People don't like the dishes. No dish is prepared.

Example 4:
Input: satisfaction = [-2,5,-1,0,3,-3]
Output: 35

Constraints:

n == satisfaction.length
1 <= n <= 500
-10^3 <= satisfaction[i] <= 10^3

class Solution:
    def maxSatisfaction(self, satisfaction: List[int]) -> int:
        satisfaction.sort()
        n = len(satisfaction)
        dp = [-1000000009]*(n+1)
        dp[0] = 0
        for i in range(n):
            for j in range(i, -1, -1):
                dp[j+1] = max(dp[j+1], satisfaction[i]*(j+1) + dp[j])
        answer = -1000000009
        for i in range(n+1):
            answer = max(dp[i], answer)
        return answer


Solve in Python:
A chess board is normally played with 16 pawns and 16 other pieces, for this kata a variant will be played with only the pawns.  All other pieces will not be on the board.
For information on how pawns move, refer [here](http://www.chesscorner.com/tutorial/basic/pawn/pawn.htm)

Write a function that can turn a list of pawn moves into a visual representation of the resulting board.
A chess move will be represented by a string,
```
"c3"
```
This move represents a pawn moving to `c3`.  If it was white to move, the move would represent a pawn from `c2` moving to `c3`.  If it was black to move, a pawn would move from `c4` to `c3`, because black moves in the other direction.
The first move in the list and every other move will be for white's pieces.

The letter represents the column, while the number represents the row of the square where the piece is moving

Captures are represented differently from normal moves:

```
"bxc3"
```
represents a pawn on the column represented by 'b' (the second column) capturing a pawn on `c3`.

For the sake of this kata a chess board will be represented by a list like this one:
```
[[".",".",".",".",".",".",".","."],
 ["p","p","p","p","p","p","p","p"],
 [".",".",".",".",".",".",".","."],
 [".",".",".",".",".",".",".","."],
 [".",".",".",".",".",".",".","."],
 [".",".",".",".",".",".",".","."],
 ["P","P","P","P","P","P","P","P"],
 [".",".",".",".",".",".",".","."]]
```
Here is an example of the board with the squares labeled:
```
[["a8","b8","c8","d8","e8","f8","g8","h8"],
 ["a7","b7","c7","d7","e7","f7","g7","h7"],
 ["a6","b6","c6","d6","e6","f6","g6","h6"],
 ["a5","b5","c5","d5","e5","f5","g5","h5"],
 ["a4","b4","c4","d4","e4","f4","g4","h4"],
 ["a3","b3","c3","d3","e3","f3","g3","h3"],
 ["a2","b2","c2","d2","e2","f2","g2","h2"],
 ["a1","b1","c1","d1","e1","f1","g1","h1"]]
```
White pawns are represented by capital `'P'` while black pawns are lowercase `'p'`.

A few examples
```
If the list/array of moves is:...

def pawn_move_tracker(moves):
    board = [
    [".",".",".",".",".",".",".","."],
    ["p","p","p","p","p","p","p","p"],
    [".",".",".",".",".",".",".","."],
    [".",".",".",".",".",".",".","."],
    [".",".",".",".",".",".",".","."],
    [".",".",".",".",".",".",".","."],
    ["P","P","P","P","P","P","P","P"],
    [".",".",".",".",".",".",".","."]]

    for i in range(len(moves)):
        # Flip row to work with array indexing
        row = abs(int(moves[i][1])-8) if moves[i][1] != 'x' else abs(int(moves[i][3])-8)
        col = ord(moves[i][0])-97 if moves[i][1] != 'x' else ord(moves[i][2])-97
        white_turn = bool((i % 2) == 0)
        piece1 = "P" if white_turn == True else "p" #piece to move
        piece2 = "p" if white_turn == True else "P" #piece to take
        # Back is down if white's turn, and up if black's turn
        back1 = row + 1 if white_turn == True else row - 1
        back2 = row + 2 if white_turn == True else row - 2
        # Most likely current position, updated if necessary
        current_row, current_col = back1, col

        # If capturing enemy pawn
        if 'x' in moves[i] and board[row][col] == piece2:
            current_col = ord(moves[i][0]) - 97
            if board[back1][current_col] != piece1:
                return f"{moves[i]} is invalid"
        # If moving 2 squares from starting position
        elif board[back1][col] == "." and board[back2][col] == piece1:
            if (white_turn == True and back2 == 6) or (white_turn == False and back2 == 1):
                current_row = back2
            else:
                return f"{moves[i]} is invalid"
        # Standard move forward, ensure move is valid
        elif board[back1][col] != piece1 or board[row][col] != ".":
            return f"{moves[i]} is invalid"

        # Update board
        board[current_row][current_col] = "."
        board[row][col] = piece1

    return board


Solve in Python:
A chess position can be expressed as a string using the  Forsyth–Edwards Notation (FEN). Your task is to write a parser that reads in a FEN-encoded string and returns a depiction of the board using the Unicode chess symbols (♔,♕,♘,etc.). The board should be drawn from the perspective of the active color (i.e. the side making the next move).

Using the CodeWars dark theme is strongly recommended for this kata. Otherwise, the colors will appear to be inverted.

The complete FEN format contains 6 fields separated by spaces, but we will only consider the first two fields: Piece placement and active color (side-to-move). The rules for these fields are as follows:

The first field of the FEN describes piece placement.
Each row ('rank') of the board is described one-by-one, starting with rank 8 (the far side of the board from White's perspective) and ending with rank 1 (White's home rank). Rows are separated by a forward slash ('/').
Within each row, the contents of the squares are listed starting with the "a-file" (White's left) and ending with the "h-file" (White's right).
Each piece is identified by a single letter: pawn = P, knight = N, bishop = B, rook = R, queen = Q and king = K. White pieces are upper-case (PNBRQK), while black pieces are lowercase (pnbrqk).
Empty squares are represented using the digits 1 through 8 to denote the number of consecutive empty squares.
The piece placement field is followed by a single space, then a single character representing the color who has the next move ('w' for White and 'b' for Black).
Four additional fields follow the active color, separated by spaces. These fields can be ignored.

Using this encoding, the starting position is:

```rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1```

Using the characters "＿" and "▇" to represent dark and light unoccupied spaces, respectively, the starting position using the Unicode pieces would be:

♖♘♗♕♔♗♘♖
♙♙♙♙♙♙♙♙
▇＿▇＿▇＿▇＿
＿▇＿▇＿▇＿▇
▇＿▇＿▇＿▇＿
＿▇＿▇＿▇＿▇
♟♟♟♟♟♟♟♟
♜♞♝♛♚♝♞♜

After the move 1. Nf3, the FEN would...

BOARD = '▇＿▇＿▇＿▇＿\n＿▇＿▇＿▇＿▇\n▇＿▇＿▇＿▇＿\n＿▇＿▇＿▇＿▇\n▇＿▇＿▇＿▇＿\n＿▇＿▇＿▇＿▇\n▇＿▇＿▇＿▇＿\n＿▇＿▇＿▇＿▇'
PIECES = dict(zip('kqrbnpKQRBNP', '♔♕♖♗♘♙♚♛♜♝♞♟'))

def parse_fen(string):
    board = list(map(list, BOARD.splitlines()))
    pieces, color = string.split()[:2]

    for r, rank in enumerate(pieces.split('/')):
        f = 0
        for square in rank:
            if square.isdigit():
                f += int(square)
            else:
                board[r][f] = PIECES[square]
                f += 1
    return '\n'.join(map(''.join, board if color == 'w' else [rank[::-1] for rank in board[::-1]])) + '\n'


Solve in Python:
A cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above.
Given the array reservedSeats containing the numbers of seats already reserved, for example, reservedSeats[i] = [3,8] means the seat located in row 3 and labelled with 8 is already reserved.
Return the maximum number of four-person groups you can assign on the cinema seats. A four-person group occupies four adjacent seats in one single row. Seats across an aisle (such as [3,3] and [3,4]) are not considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in that case, the aisle split a four-person group in the middle, which means to have two people on each side.

Example 1:

Input: n = 3, reservedSeats = [[1,2],[1,3],[1,8],[2,6],[3,1],[3,10]]
Output: 4
Explanation: The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group.

Example 2:
Input: n = 2, reservedSeats = [[2,1],[1,8],[2,6]]
Output: 2

Example 3:
Input: n = 4, reservedSeats = [[4,3],[1,4],[4,6],[1,7]]
Output: 4

Constraints:

1 <= n <= 10^9
1 <= reservedSeats.length <= min(10*n, 10^4)
reservedSeats[i].length == 2
1 <= reservedSeats[i][0] <= n
1 <= reservedSeats[i][1] <= 10
All reservedSeats[i] are distinct.

class Solution:
    def maxNumberOfFamilies(self, n: int, reservedSeats: List[List[int]]) -> int:
        rowseats = defaultdict(list)
        for s in reservedSeats:
            rowseats[s[0]].append(s[1])

        subtract = 0
        for _, seats in rowseats.items():
            left = True
            right = True
            middle = True
            for s in seats:
                if 2 <= s <= 5:
                    left = False
                if 4 <= s <= 7:
                    middle = False
                if 6 <= s <= 9:
                    right = False
            if left and right:
                subtract += 0
            elif left or right or middle:
                subtract += 1
            else:
                subtract += 2

        return n*2 - subtract


Solve in Python:
A circle is defined by three coplanar points that are not aligned.

You will be given a list of circles and a point [xP, yP]. You have to create a function, ```count_circles()``` (Javascript ```countCircles()```), that will count the amount of circles that contains the point P inside (the circle border line is included).

```python
list_of_circles = ([[[-3,2], [1,1], [6,4]], [[-3,2], [1,1], [2,6]], [[1,1], [2,6], [6,4]], [[[-3,2],[2,6], [6,4]]]

point1 = [1, 4] # P1
count_circles(list_of_circles, point1) == 4 #(The four circles have P1 inside)
```

It may happen that the point may be external to all the circles.

```python
list_of_circles = ([[[-3,2], [1,1], [6,4]], [[-3,2], [1,1], [2,6]], [[1,1], [2,6], [6,4]], [[-3,2],[2,6], [6,4]]]

point2 = [10, 6] # P2
count_circles(list_of_circles, point2) == 0 #(P2 is exterior to the four circles)
```
The point may be in the circle line and that will be consider as an internal point of it, too.
For practical purposes a given point ```P``` will be in the circle line if:
         |r - d|/r < 10^(-10)

```r```: radius of the circle that should be calculated from the coordinates of the three given points.

```d```: distance from the point ```P``` to the center of the circle. Again we have to do a calculation, the coordinates of the center should be calculated using the coordinates of the three given points.

Let's see a case when the pints is in the circle line.

```python
list_of_circles = ([[[-3,2], [1,1], [6,4]], [[-3,2], [1,1], [2,6]], [[1,1], [2,6], [6,4]], [[[-3,2],[2,6], [6,4]]]

point3 = point2 = [2, 6] # P3
count_circles(list_of_circles, point3) == 4 #(P3  is an internal point of the four circles)
```

All these three cases are shown in the image below:

Your code should be able to skip these cases:

- inexistent circle when we have three points aligned

- undefined circles when two or three of given points coincides.

First ten people to solve it will receive extra points.

Hints: This kata will give you important formulas: ```Give The Center And The Radius...

def count_circles(list_of_circles, point, count = 0):
    return sum(1 for circle in list_of_circles if point_in(circle, point))

def point_in(points, point):
    helper = lambda x,y: (-1)**y*(points[(x+1)%3][(y+1)%2] - points[(x+2)%3][(y+1)%2])
    D = 2*sum(points[i][0]*helper(i,0) for i in range(3))
    U = [1.0 * sum(sum(points[i][j]**2 for j in range(2))*helper(i,k) for i in range(3))/D for k in range(2)]
    return compare(point, U, radius(points,D)) if (not invalid(points, D)) else False

compare = lambda p, U, r: ((distance(U,p) < r) or (abs(r-distance(U,p))/r < 10**-10))
distance = lambda p1, p2: ((p2[0] - p1[0])**2 + (p2[1] - p1[1])**2)**0.5
invalid = lambda p, D: ((D == 0) or (p[0] == p[1]) or (p[0] == p[2]) or (p[1] == p[2]))
radius = lambda p, D: distance(p[0],p[1])*distance(p[0],p[2])*distance(p[1],p[2])/abs(D)


Solve in Python:
A city of dimension N x N is constructed with grid of lanes. These lanes are fenced by government so that no one can cross any grid diagonally. Although a train
line runs diagonally from (0,0) to (N,N).
Our chef has a weird kind of phobia and is very afraid to cross the railway line. He is at point (0,0) and wants to get to the point (N,N). Calculate number of path
through which it is possible to reach to its destination travelling the minimum distance. .
Note that:

1. Since he is already at position (0,0) he can go to either part of grid (i.e. left or right part - divided by diagonal) but he will remain in that part for the whole path.
2. He is only afraid to "cross" the line, i.e. during the route he can go to position (m,m) where 0
3. You have to calculate the number of path possible. If there is more than one path then you have to print the number of path of minimum distances.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases, for each test case enter the grid size i.e value of N.

-----Output-----
For each test case, output a single line with number of such paths possible.
(Note : If no such path possible print 0)

-----Constraints-----
- 1 <= T <= 100
- 0 <= N <= 30

-----Example-----
Input:
2
2
5
Output:
4
84

ar = []
ar.append(1)
for i in range(1, 31):
 ar.append(ar[i-1]*(4*i-2)/(i+1))
t = int(input())
while(t>0):
 n = int(input())
 if(n==0):
  print(0)
 else:
  print(ar[n]*2)
 t=t-1


Solve in Python:
A common problem in number theory is to find x given a such that:

a * x = 1 mod [n]

Then x is called the inverse of a modulo n.

Your goal is to code a function inverseMod wich take a and n as parameters and return x.

You may be interested by these pages:

http://en.wikipedia.org/wiki/Modular_multiplicative_inverse

http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm

a and n should be co-prime to have a solution, if it is not the case, you should return None (Python), nil (Ruby) or null (Javascript).

a and n will be positive integers. The problem can easily be generalised to negative integer with some sign changes so we won't deal with them.


Solve in Python:
A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company has is the one with headID.
Each employee has one direct manager given in the manager array where manager[i] is the direct manager of the i-th employee, manager[headID] = -1. Also it's guaranteed that the subordination relationships have a tree structure.
The head of the company wants to inform all the employees of the company of an urgent piece of news. He will inform his direct subordinates and they will inform their subordinates and so on until all employees know about the urgent news.
The i-th employee needs informTime[i] minutes to inform all of his direct subordinates (i.e After informTime[i] minutes, all his direct subordinates can start spreading the news).
Return the number of minutes needed to inform all the employees about the urgent news.

Example 1:
Input: n = 1, headID = 0, manager = [-1], informTime = [0]
Output: 0
Explanation: The head of the company is the only employee in the company.

Example 2:

Input: n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0]
Output: 1
Explanation: The head of the company with id = 2 is the direct manager of all the employees in the company and needs 1 minute to inform them all.
The tree structure of the employees in the company is shown.

Example 3:

Input: n = 7, headID = 6, manager = [1,2,3,4,5,6,-1], informTime = [0,6,5,4,3,2,1]
Output: 21
Explanation: The head has id = 6. He will inform employee with id = 5 in 1 minute.
The employee with id = 5 will inform the employee with id = 4 in 2 minutes.
The employee with id = 4 will inform the employee with id = 3 in 3 minutes.
The employee with id = 3 will inform the employee with id = 2 in 4 minutes.
The employee with id = 2 will inform the employee with id = 1 in 5 minutes.
The employee with id = 1 will inform the employee with id = 0 in 6 minutes.
Needed time = 1 + 2 + 3 + 4 + 5 + 6 = 21.

Example 4:
Input: n = 15, headID = 0, manager = [-1,0,0,1,1,2,2,3,3,4,4,5,5,6,6], informTime =...

class Node:
    def __init__(self, val, weight=0):
        self.root = val
        self.weight = weight
        self.children = []

class Solution:
    def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:

        hashmap = {}

        for i in range(n):
            hashmap.update({i: Node(i)})

        for i, item in enumerate(manager):
            if item == -1:
                head = hashmap[i]
            else:
                hashmap[item].children.append(hashmap[i])

        for i, time in enumerate(informTime):
            hashmap[i].weight = time

        def recur(root) -> int:
            if not root.children:
                return root.weight

            max_time = 0
            for child in root.children:
                time = recur(child)
                if time > max_time:
                    max_time = time

            return root.weight + max_time

        return recur(head)


Solve in Python:
A company is opening a bank, but the coder who is designing the user class made some errors. They need  you  to help them.

You must include the following:

- A withdraw method
  - Subtracts money from balance
  - One parameter, money to withdraw
  - Raise ValueError if there isn't enough money to withdraw
  - Return a string with name and balence(see examples)

* A check method
  - Adds money to baleance
  - Two parameters, other user and money
  - Other user will always be valid
  - Raise a ValueError if other user doesn't have enough money
  - Raise a ValueError if checking_account isn't true for other user
  - Return a string with name and balance plus other name and other balance(see examples)

- An add_cash method
  - Adds money to balance
  - One parameter, money to add
  - Return a string with name and balance(see examples)

Additional Notes:
  * Checking_account should be stored as a boolean
  - No input numbers will be negitive
  * Output must end with period
  - Float numbers will not be used so, balance should be integer
  * No currency will be used

Examples:
``` Python
Jeff = User('Jeff', 70, True)
Joe = User('Joe', 70, False)

Jeff.withdraw(2) # Returns 'Jeff has 68.'

Joe.check(Jeff, 50) # Returns 'Joe has 120 and Jeff has 18.'

Jeff.check(Joe, 80) # Raises a ValueError

Joe.checking_account = True # Enables checking for Joe

Jeff.check(Joe, 80) # Returns 'Jeff has 98 and Joe has 40'

Joe.check(Jeff, 100) # Raises a ValueError

Jeff.add_cash(20.00) # Returns 'Jeff has 118.'
```

 Good Luck

class User:
    def __init__(self, name, balance, checking_account):
        self.name, self.balance, self.checking_account = name, balance, checking_account
    def __str__(self):
        return "{} has {:d}.".format(self.name, self.balance)
    def withdraw(self, amount):
        if self.balance < amount: raise ValueError("Not enough money.")
        self.balance -= amount
        return str(self)
    def add_cash(self, amount):
        self.balance += amount
        return str(self)
    def check(self, other, amount):
        if not other.checking_account:
            raise ValueError("Can't transfer money from this account.")
        other.withdraw(amount)
        self.add_cash(amount)
        return "{} and {}".format(str(self)[:-1], other)


Solve in Python:
A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, and the cost of flying the ith person to city b is bCosti.
Return the minimum cost to fly every person to a city such that exactly n people arrive in each city.

Example 1:
Input: costs = [[10,20],[30,200],[400,50],[30,20]]
Output: 110
Explanation:
The first person goes to city A for a cost of 10.
The second person goes to city A for a cost of 30.
The third person goes to city B for a cost of 50.
The fourth person goes to city B for a cost of 20.

The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.

Example 2:
Input: costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]
Output: 1859

Example 3:
Input: costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]
Output: 3086

Constraints:

2n == costs.length
2 <= costs.length <= 100
costs.length is even.
1 <= aCosti, bCosti <= 1000

class Solution:
    def twoCitySchedCost(self, costs: List[List[int]]) -> int:
        lc = len(costs)
        c = lc//2
        cost1 = 0
        cost2 = 0
        al = c
        bl = c
        for i in range(lc):
            for j in range(i+1, lc):
                if abs(costs[i][0]-costs[i][1]) < abs(costs[j][0]-costs[j][1]):
                    costs[i], costs[j] = costs[j], costs[i]

        for i in range(lc):
            if (costs[i][0] <= costs[i][1] and al>0) or bl==0:
                cost1 += costs[i][0]
                al -= 1
            elif bl>0:
                cost1 += costs[i][1]
                bl -= 1
        al = c
        bl = c
        for i in range(lc):
            if (costs[i][0] < costs[i][1] and al>0) or bl == 0:
                cost2 += costs[i][0]
                al -= 1
            elif bl>0:
                cost2 += costs[i][1]
                bl -= 1
        return min(cost1,cost2)


Solve in Python:
A conveyor belt has packages that must be shipped from one port to another within D days.
The i-th package on the conveyor belt has a weight of weights[i].  Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship.
Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within D days.

Example 1:
Input: weights = [1,2,3,4,5,6,7,8,9,10], D = 5
Output: 15
Explanation:
A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
1st day: 1, 2, 3, 4, 5
2nd day: 6, 7
3rd day: 8
4th day: 9
5th day: 10

Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.

Example 2:
Input: weights = [3,2,2,4,1,4], D = 3
Output: 6
Explanation:
A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:
1st day: 3, 2
2nd day: 2, 4
3rd day: 1, 4

Example 3:
Input: weights = [1,2,3,1,1], D = 4
Output: 3
Explanation:
1st day: 1
2nd day: 2
3rd day: 3
4th day: 1, 1

Constraints:

1 <= D <= weights.length <= 50000
1 <= weights[i] <= 500

class Solution:
    def shipWithinDays(self, weights: List[int], D: int) -> int:
        l = 0
        r = sum(weights)
        best = r
        while l <= r:
            mid = l + (r - l) // 2
            if self.works(mid, weights, D):
                best = mid
                r = mid - 1
            else:
                l = mid + 1

        return best

    def works(self, cap, weights, d):
        if cap < max(weights):
            return False
        idx = 0
        total_days = 0
        while idx < len(weights):
            cur_cap = 0
            while cur_cap < cap and idx < len(weights):
                if cur_cap + weights[idx] > cap:
                    break
                cur_cap += weights[idx]
                idx += 1

            total_days += 1

        return total_days <= d


Solve in Python:
A core idea of several left-wing ideologies is that the wealthiest should *support* the poorest, no matter what and that is exactly what you are called to do using this kata (which, on a side note, was born out of the necessity to redistribute the width of `div`s into a given container).

You will be given two parameters, `population` and `minimum`: your goal is to give to each one according to his own needs (which we assume to be equal to `minimum` for everyone, no matter what), taking from the richest (bigger numbers) first.

For example, assuming a population `[2,3,5,15,75]` and `5` as a minimum, the expected result should be `[5,5,5,15,70]`. Let's punish those filthy capitalists, as we all know that being rich has to be somehow a fault and a shame!

If you happen to have few people as the richest, just take from the ones with the lowest index (the closest to the left, in few words) in the array first, on a 1:1 based heroic proletarian redistribution, until everyone is satisfied.

To clarify this rule, assuming a population `[2,3,5,45,45]` and `5` as `minimum`, the expected result should be `[5,5,5,42,43]`.

If you want to see it in steps, consider removing `minimum` from every member of the population, then iteratively (or recursively) adding 1 to the poorest while removing 1 from the richest. Pick the element most at left if more elements exist with the same level of minimal poverty, as they are certainly even more aligned with the party will than other poor people; similarly, it is ok to take from the richest one on the left first, so they can learn their lesson and be more kind, possibly giving more *gifts* to the inspectors of the State!

In steps:
```
[ 2, 3, 5,45,45] becomes
[-3,-2, 0,40,40] that then becomes
[-2,-2, 0,39,40] that then becomes
[-1,-2, 0,39,39] that then becomes
[-1,-1, 0,38,39] that then becomes
[ 0,-1, 0,38,38] that then becomes
[ 0, 0, 0,37,38] that then finally becomes (adding the minimum again, as no value is no longer under the poverty threshold
[ 5, 5, 5,42,43]
```

If giving...

def socialist_distribution(population, minimum):
    if sum(population) < len(population) * minimum:
        return []
    while 1:
        poor = rich = 0
        for idx, need in enumerate(population):
            if need < population[poor]: poor = idx
            if need > population[rich]: rich = idx
        if population[poor] >= minimum:
            return population
        population[rich] -= 1
        population[poor] += 1


Solve in Python:
A country has coins with denominations
```python
coins_list = d1 < d2 < · · · < dn.
```
You want to make change for n cents, using the smallest number of coins.

```python
# Example 1: U.S. coins
d1 = 1 d2 = 5 d3 = 10 d4 = 25

## Optimal change for 37 cents – 1 quarter, 1 dime, 2 pennies.

# Example 2: Alien Planet Z coins
Z_coin_a = 1 Z_coin_b = 3 Z_coin_c = 4

## Optimal change for 6 cents - 2 Z_coin_b's
```

Write a function that will take a list of coin denominations and a desired amount and provide the least amount of coins needed.

def loose_change(coins_list, amount_of_change):
    if len(coins_list) == 1: return amount_of_change
    return min(
        loose_change(coins_list[:-1], amount_of_change),
        amount_of_change // coins_list[-1] + loose_change(coins_list[:-1], amount_of_change % coins_list[-1])
    )


Solve in Python:
A despotic king decided that his kingdom needed to be rid of corruption and disparity. He called his prime minister and ordered that all corrupt citizens be put to death. Moreover, he wanted this done quickly.
The wily prime minister realised that investigating every citizen to decide who was corrupt and who was not was rather difficult. So he decided on the following plan: He ordered all the citizens to appear in the court one by one and declare their wealth.
The king does not sit in the court all the time (he has other important business to attend to - for instance, meet dignitaries from neighbouring kingdoms, spend time with his family …) Whenever the king walks into the court, the prime minister pulls out the richest man who has appeared before the court so far and is still alive and beheads him for being corrupt. Since the rich are more likely to be corrupt, he hopes to get rid of most of the corrupt and the king is happy as he sees his policy being implemented enthusiastically.
Suppose the wealth of the citizens trooping into the court is
1376518911241376518911241\; 3\; 7\; 6\; 5\; 18\;  9\; 11\;  2\; 4
and the king walked in three times: the first time after the first four persons have seen the minister, the second time after the first five persons have seen the minister and, finally after the first nine persons have seen the minister.
At the king's first visit the richest person to have met the minister has wealth $7$ and he would be beheaded. At the second visit, the wealth of the richest person who has met the minister and is still alive has wealth $6$ and so he would be beheaded. At the third visit the richest person to have met the minister who is still alive has wealth $18$ and so he would be beheaded.
You may assume that the input is such that whenever the king walks in, it is always possible to behead someone.
Your aim is to write a program that will enable the prime minister to identify the richest man to have met the minister and who is still alive quickly. You may assume that no two citizens...

a, b = map(int, input().split())
k = []
for _ in range(a + b):
    p = int(input())
    if p != -1:
        k.append(p)
    else:
        print(max(k))
        k.remove(max(k))


Solve in Python:
A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) consecutive times.
Given an array of integers rollMax and an integer n, return the number of distinct sequences that can be obtained with exact n rolls.
Two sequences are considered different if at least one element differs from each other. Since the answer may be too large, return it modulo 10^9 + 7.

Example 1:
Input: n = 2, rollMax = [1,1,2,2,2,3]
Output: 34
Explanation: There will be 2 rolls of die, if there are no constraints on the die, there are 6 * 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34.

Example 2:
Input: n = 2, rollMax = [1,1,1,1,1,1]
Output: 30

Example 3:
Input: n = 3, rollMax = [1,1,1,2,2,3]
Output: 181

Constraints:

1 <= n <= 5000
rollMax.length == 6
1 <= rollMax[i] <= 15

class Solution:
    def dieSimulator(self, n: int, rollMax: List[int]) -> int:

        memo = {}
        def dfs(last, s,  k):
            if k == n:
                return 1
            if (last, s, k)  in memo:
                return memo[last, s, k]

            else:

                res = 0
                for i in range(6):
                    if i == last:
                        if s + 1 > rollMax[i]:
                            continue
                        else:
                            res += dfs(i, s+1, k+1)
                    else:
                        res += dfs(i, 1, k+1)
                memo[last, s, k] = res
            return res

        mode = 10**9 + 7
        return dfs(None, 0, 0)%mode