Solve in Python:
Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated.

For example, Zookeeper can use two such operations: AABABBA $\to$ AABBA $\to$ AAA.

Zookeeper wonders what the shortest string he can make is. Can you help him find the length of the shortest string?

-----Input-----

Each test contains multiple test cases. The first line contains a single integer $t$ $(1 \leq t \leq 20000)$  — the number of test cases. The description of the test cases follows.

Each of the next $t$ lines contains a single test case each, consisting of a non-empty string $s$: the string that Zookeeper needs to bomb. It is guaranteed that all symbols of $s$ are either 'A' or 'B'.

It is guaranteed that the sum of $|s|$ (length of $s$) among all test cases does not exceed $2 \cdot 10^5$.

-----Output-----

For each test case, print a single integer: the length of the shortest string that Zookeeper can make.

-----Example-----
Input
3
AAA
BABA
AABBBABBBB

Output
3
2
0

-----Note-----

For the first test case, you can't make any moves, so the answer is $3$.

For the second test case, one optimal sequence of moves is BABA $\to$ BA. So, the answer is $2$.

For the third test case, one optimal sequence of moves is AABBBABBBB $\to$ AABBBABB $\to$ AABBBB $\to$ ABBB $\to$ AB $\to$ (empty string). So, the answer is $0$.

for t in range(int(input())):
    s=input()
    stack=[]
    for i in s:
        if i=='A':
            stack.append(i)
        else:
            if stack:
                stack.pop()
            else:
                stack.append(i)
    print(len(stack))


Solve in Python:
[BasE91](http://base91.sourceforge.net/) is a method for encoding binary as ASCII characters. It is more efficient than Base64 and needs 91 characters to represent the encoded data.

The following ASCII charakters are used:

    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
    '!#$%&()*+,./:;<=>?@[]^_`{|}~"'

Create two functions that encode strings to basE91 string and decodes the other way round.

    b91encode('test') = 'fPNKd'
    b91decode('fPNKd') = 'test'

    b91decode('>OwJh>Io0Tv!8PE') = 'Hello World!'
    b91encode('Hello World!') = '>OwJh>Io0Tv!8PE'

Input strings are valid.


Solve in Python:
[Chopsticks (singular: chopstick) are short, frequently tapered sticks used in pairs of equal length, which are used as the traditional eating utensils of China, Japan, Korea and Vietnam. Originated in ancient China, they can also be found in some areas of Tibet and Nepal that are close to Han Chinese populations, as well as areas of Thailand, Laos and Burma which have significant Chinese populations. Chopsticks are most commonly made of wood, bamboo or plastic, but in China, most are made out of bamboo. Chopsticks are held in the dominant hand, between the thumb and fingers, and used to pick up pieces of food.]
Retrieved from wikipedia
Actually, the two sticks in a pair of chopsticks need not be of the same length. A pair of sticks can be used to eat as long as the difference in their length is at most D. The Chef has N sticks in which the ith stick is L[i] units long. A stick can't be part of more than one pair of chopsticks. Help the Chef in pairing up the sticks to form the maximum number of usable pairs of chopsticks.

-----Input-----
The first line contains two space-separated integers N and D. The next N lines contain one integer each, the ith line giving the value of L[i].

-----Output-----
Output a single line containing the maximum number of pairs of chopsticks the Chef can form.

-----Constraints-----
- 1 ≤ N ≤ 100,000 (10 5 )
- 0 ≤ D ≤ 1,000,000,000 (10 9 )
- 1 ≤ L[i] ≤ 1,000,000,000 (10 9 ) for all integers i from 1 to N

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

5 2
1
3
3
9
4

Output:
2

-----Explanation-----

The 5 sticks have lengths 1, 3, 3, 9 and 4 respectively. The maximum allowed difference in the lengths of two sticks forming a pair is at most 2.
It is clear that the 4th stick (length 9) cannot be used with any other stick.
The remaining 4 sticks can can be paired as (1st and 3rd) and (2nd and 5th) to form 2 pairs of usable chopsticks.

# cook your dish here
a,b=list(map(int, input().split()))
l=[]
for _ in range(a):
 x=int(input())
 l.append(x)

l.sort()

m=0
i=0
while(i<a-1):
 x=l[i+1]-l[i]
 if(x<=b):
  m=m+1
  i=i+2
 else:
  i=i+1
print(m)


Solve in Python:
[Currying and partial application](http://www.2ality.com/2011/09/currying-vs-part-eval.html) are two ways of transforming a function into another function with a generally smaller arity. While they are often confused with each other, they work differently. The goal is to learn to differentiate them.

## Currying

> Is the technique of transforming a function that takes multiple arguments in such a way that it can be called as a chain of functions each with a single argument.

Currying takes a function:

```
f: X × Y → R
```

and turns it into a function:

```
f': X → (Y → R)
```

Instead of calling `f` with two arguments, we invoke `f'` with the first argument. The result is a function that we then call with the second argument to produce the result. Thus, if the uncurried `f` is invoked as:

```
f(3, 5)
```

then the curried `f'` is invoked as:

`f'(3)(5)`

### Example

Given this function:

```python
def add(x, y, z):
  return x + y + z
```

We can call in a normal way:

```python
add(1, 2, 3) # => 6
```

But we can create a curried version of `add(a, b, c)`function:

```python
curriedAdd = lambda a: (lambda b: (lambda c: add(a,b,c)))
curriedAdd(1)(2)(3) # => 6
```

## Partial application

> Is the process of fixing a number of arguments to a function, producing another function of smaller arity.

Partial application takes a function:

```
f: X × Y → R
```

and a fixed value `x` for the first argument to produce a new function

```
f': Y → R
```

`f'` does the same as `f`, but only has to fill in the second parameter which is why its arity is one less than the arity of `f`. One says that the first argument is bound to `x`.

### Example

```python
partialAdd = lambda a: (lambda *args: add(a,*args))
partialAdd(1)(2, 3) # => 6
```

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

Your work is to implement a generic `curryPartial()` function allows either currying or partial application.

For example:

```python
curriedAdd = curryPartial(add)
curriedAdd(1)(2)(3) # => 6

partialAdd = curryPartial(add, 1)
partialAdd(2, 3) # => 6
```

We want the...

def curry_partial(f,*initial_args):
    def f1(*args):
        def f2(*args2):

            if not callable(f):                             return f     #we are done already
            elif f.__code__.co_argcount == 0:               return f(*(args+args2))# nested call
            elif f.__code__.co_argcount > len(args+args2):  return f1(*(args+args2))#not enough args
            else:                                           return f(*(args+args2)[0:f.__code__.co_argcount])#victory

        return f2
    return f1(*initial_args)()


Solve in Python:
[Generala](https://en.wikipedia.org/wiki/Generala) is a dice game popular in South America. It's very similar to [Yahtzee](https://en.wikipedia.org/wiki/Yahtzee) but with a different scoring approach. It is played with 5 dice, and the possible results are:

| Result        | Points | Rules                                                                                | Samples                            |
|---------------|--------|------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------|
| GENERALA      | 50     | When all rolled dice are of the same value.                                                                                | 66666, 55555, 44444, 11111, 22222, 33333.  |
| POKER         | 40     | Four rolled dice are of the same value.                                                                                | 44441, 33233, 22262.               |
| FULLHOUSE     | 30     | Three rolled dice are of the same value, the remaining two are of a different value, but equal among themselves.                               | 12121, 44455, 66116.               |
| STRAIGHT      | 20     | Rolled dice are in sequential order. Dice with value `1` is a wildcard that can be used at the beginning of the straight, or at the end of it. | 12345, 23456, 34561, 13654, 62534. |
| Anything else | 0      | Anything else will return `0` points.                                                                                | 44421, 61623, 12346.               |

Please note that dice are not in order; for example `12543` qualifies as a `STRAIGHT`. Also, No matter what string value you get for the dice, you can always reorder them any order you need to make them qualify as a `STRAIGHT`. I.E. `12453`, `16543`, `15364`, `62345` all qualify as valid `STRAIGHT`s.

Complete...

from collections import Counter

def points(s):
    m = tuple(sorted(dict(Counter(list(s))).values()))
    d = {(5,):50, (1,4):40, (2,3):30}
    try:
        return d[m]
    except KeyError:
        return 20 if "".join(sorted(list(s))) in ["12345","13456","23456"] else 0


Solve in Python:
[Haikus](https://en.wikipedia.org/wiki/Haiku_in_English) are short poems in a three-line format, with 17 syllables arranged in a 5–7–5 pattern. Your task is to check if the supplied text is a haiku or not.

### About syllables

[Syllables](https://en.wikipedia.org/wiki/Syllable) are the phonological building blocks of words. *In this kata*, a syllable is a part of a word including a vowel ("a-e-i-o-u-y") or a group of vowels (e.g. "ou", "ee", "ay"). A few examples: "tea", "can", "to·day", "week·end", "el·e·phant".

**However**, silent "E"s **do not** create syllables. *In this kata*, an "E" is considered silent if it's alone at the end of the word, preceded by one (or more) consonant(s) and there is at least one other syllable in the word. Examples: "age", "ar·range", "con·crete"; but not in "she", "blue", "de·gree".

Some more examples:
* one syllable words: "cat", "cool", "sprout", "like", "eye", "squeeze"
* two syllables words: "ac·count", "hon·est", "beau·ty", "a·live", "be·cause", "re·store"

## Examples
```
An old silent pond...
A frog jumps into the pond,
splash! Silence again.
```

...should return `True`, as this is a valid 5–7–5 haiku:
```
An old si·lent pond...            # 5 syllables
A frog jumps in·to the pond,      # 7
splash! Si·lence a·gain.          # 5
```

Another example:

```
Autumn moonlight -
a worm digs silently
into the chestnut.
```

...should return `False`, because the number of syllables per line is not correct:
```
Au·tumn moon·light -          # 4 syllables
a worm digs si·lent·ly        # 6
in·to the chest·nut.          # 5
```

---

## My other katas

If you enjoyed this kata then please try [my other katas](https://www.codewars.com/collections/katas-created-by-anter69)! :-)

def is_haiku(s,v='aeiouy'):
    C=[]
    for x in[a.strip('.;:!?,').split()for a in s.lower().split('\n')]:
        t=''
        for y in x:
            if y.endswith('e')and any(c in y[:-1]for c in v):y=y[:-1]
            for c in y:t+=c if c in v else' 'if t and t[-1]!=' 'else''
            t+=' '
        C+=[len(t.split())]
    return C==[5,7,5]


Solve in Python:
[Harshad numbers](http://en.wikipedia.org/wiki/Harshad_number) (also called Niven numbers) are positive numbers that can be divided (without remainder) by the sum of their digits.

For example, the following numbers are Harshad numbers:

* 10, because 1 + 0 = 1 and 10 is divisible by 1
* 27, because 2 + 7 = 9 and 27 is divisible by 9
* 588, because 5 + 8 + 8 = 21 and 588 is divisible by 21

While these numbers are not:

* 19, because 1 + 9 = 10 and 19 is not divisible by 10
* 589, because 5 + 8 + 9 = 22 and 589 is not divisible by 22
* 1001, because 1 + 1 = 2 and 1001 is not divisible by 2

Harshad numbers can be found in any number base, but we are going to focus on base 10 exclusively.

## Your task

Your task is to complete the skeleton Harshad object ("static class") which has 3 functions:

* ```isValid()``` that checks if `n` is a Harshad number or not
* ```getNext()``` that returns the next Harshad number > `n`
* ```getSerie()``` that returns a series of `n` Harshad numbers, optional `start` value not included

You do not need to care about the passed parameters in the test cases, they will always be valid integers (except for the start argument in `getSerie()` which is optional and should default to `0`).

**Note:** only the first 2000 Harshad numbers will be checked in the tests.

## Examples

```python
Harshad.is_valid(1)          ==>  True
Harshad.get_next(0)          ==>  1
Harshad.get_series(3)        ==>  [ 1, 2, 3 ]
Harshad.get_series(3, 1000)  ==>  [ 1002, 1008, 1010 ]
```

class Harshad:
    @staticmethod
    def is_valid(number):
        if number == 0:
            return False
        sumdigits = sum(int(d) for d in str(number))
        return number % sumdigits == 0

    @staticmethod
    def get_next(number):
        while True:
            number += 1
            if Harshad.is_valid(number):
                return number

    @staticmethod
    def get_series(count, start = 0):
        answer = []
        for _ in range(count):
            start = Harshad.get_next(start)
            answer.append(start)
        return answer


Solve in Python:
[Langton's ant](https://en.wikipedia.org/wiki/Langton%27s_ant) is a two-dimensional Turing machine invented in the late 1980s. The ant starts out on a grid of black and white cells and follows a simple set of rules that has complex emergent behavior.

## Task

Complete the function and return the `n`th iteration of Langton's ant with the given input.

### Parameters:

* `grid` - a two dimensional array of `1`s and `0`s (representing white and black cells respectively)
* `column` - horizontal position of ant
* `row` - ant's vertical position
* `n` - number of iterations
* `dir` - ant's current direction (0 - north, 1 - east, 2 - south, 3 - west), **should default to 0**

**Note:** parameters `column` and `row` will always be inside the `grid`, and number of generations `n` will never be negative.

## Output

The state of the `grid` after `n` iterations.

## Rules

The ant can travel in any of the four cardinal directions at each step it takes. The ant moves according to the rules below:

* At a white square (represented with `1`), turn 90° right, flip the color of the square, and move forward one unit.
* At a black square (`0`), turn 90° left, flip the color of the square, and move forward one unit.

The grid has no limits and therefore if the ant moves outside the borders, the grid should be expanded with `0`s, respectively maintaining the rectangle shape.

## Example

```python
ant([[1]], 0, 0, 1, 0)   # should return: [[0, 0]]
```

Initially facing north (`0`), at the first iteration the ant turns right (because it stands on a white square, `1`), flips the square and moves forward.

def ant(gr, cl, ro, n, di = 0):
    class ant_class():
        def __init__(self, col, row, direction):
            self.c = col
            self.r = row
            self.direction = ['N', 'E', 'S', 'W']
        def __repr__(self):
            return ('col: {}, row: {}, direction: {}'.format(self.c, self.r, self.direction[0]))
        def turn_right(self):
            self.direction.append(self.direction.pop(0))
        def turn_left(self):
            self.direction.insert(0, self.direction.pop(-1))
        def move(self, grid):
            if self.direction[0] == 'N':
                 if ant.r == 0:
                    grid.expand_north()
                 else:
                    ant.r -= 1
            elif self.direction[0] == 'S':
                if ant.r == len(grid.grid) - 1:
                    grid.expand_south()
                ant.r += 1
            elif self.direction[0] == 'W':
                if ant.c == 0:
                    grid.expand_west()
                else:
                    ant.c -= 1
            elif self.direction[0] == 'E':
                if ant.c == len(grid.grid[0]) - 1:
                    grid.expand_east()
                ant.c += 1

    class grid():
        def __init__(self, arr):
            self.grid = arr
        def expand_south(self):
            self.grid.append([0 for i in range(len(self.grid[0]))])
        def expand_north(self):
            self.grid.insert(0, [0 for i in range(len(self.grid[0]))])
        def expand_east(self):
            self.grid = [i + [0] for i in self.grid]
        def expand_west(self):
            self.grid = [[0] + i for i in self.grid]
        def invert(self, ant):
            self.grid[ant.r][ant.c] = int(not(self.grid[ant.r][ant.c]))

    ant = ant_class(cl, ro, di)
    field = grid(gr)
    for i in range(di):
        ant.turn_right()

    for i in range(n):
        if field.grid[ant.r][ant.c] == 1:
            ant.turn_right()
            field.invert(ant)
            ant.move(field)
        elif...


Solve in Python:
[Run-length encoding](http://en.wikipedia.org/wiki/Run-length_encoding) (RLE) is a very simple form of lossless data compression in which runs of data are stored as a single data value and count.

A simple form of RLE would encode the string `"AAABBBCCCD"` as `"3A3B3C1D"` meaning, first there are `3 A`, then `3 B`, then `3 C` and last there is `1 D`.

Your task is to write a RLE encoder and decoder using this technique. The texts to encode will always consist of only uppercase characters, no numbers.

from re import sub

def encode(s):
    return sub(r'(.)\1*', lambda m: str(len(m.group(0))) + m.group(1), s)

def decode(s):
    return sub(r'(\d+)(\D)', lambda m: m.group(2) * int(m.group(1)), s)


Solve in Python:
[The Vigenère cipher](https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher) is a classic cipher that was thought to be "unbreakable" for three centuries. We now know that this is not so and it can actually be broken pretty easily.

**How the Vigenère cipher works**:

The basic concept is that you have a `message` and a `key`, and each character in the `message` is encrypted using a character in the `key`, by applying a Caesar shift. The key is recycled as many times as needed.

You might want to try [this kata](https://www.codewars.com/kata/vigenere-cipher-helper) first, which focuses on the encryption and decryption processes.

## Well how do we break it?

The first thing we have to do is determine the **length of the key** that was used to encrypt the message.

Write a function that takes some cipher text and a maximum possible key length and returns the length of the key that was used in the encryption process.

**Note:** We don't care about what characters are in the key -- only how many of them there are.

---

Any feedback (and suggestions) would be much appreciated

*This kata is based on one of the programming assignments in [Prof. Jonathan Katz's course on cryptography](https://www.coursera.org/course/cryptography) given on Coursera*

from functools import reduce
import itertools

def most_common(lst):
    return max(set(lst), key=lst.count)

def factors(n):
    return list(set(reduce(list.__add__,
                ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))

def gcd_list(alist):
    def gcd(a, b):
        while b > 0:
            a, b = b, a % b
        return a

    result = alist[0]
    for i in alist[1:]:
        result = gcd(result, i)

    return result

def common_subs(alist):
    to_return = []
    for i in alist:
        for j in alist:
            if i != j:
                to_return.append(abs(i-j))
    return to_return

#print(common_subs([100,3,4]))

def get_key_length(cipher_text,max_key_length):
    dis = []
    for pos,char in enumerate(cipher_text):
        if pos == len(cipher_text)-1:
            pass
        else:
            dis.append([cipher_text[pos]+cipher_text[pos+1],pos])

    alls = []
    for di in dis:
        if [x[0] for x in dis].count(di[0]) != 1:
            a = [x[1] for x in dis if x[0] == di[0]]
            #print(a)
            #print(common_subs(a))
            #print(gcd_list(common_subs(a)))
            alls.append(gcd_list(common_subs(a)))
    print('a')
    return most_common([x for x in alls if x != 1])


Solve in Python:
[XKCD 1609]( http://xkcd.com/1609/) provides us with the following fun fact:

![If anyone tries this on you, the best reply is a deadpan "Oh yeah, that's a common potato chip flavor in Canada."](http://imgs.xkcd.com/comics/food_combinations.png)

### Task:

Given an array containing a list of good foods, return a string containing the assertion that any two of the individually good foods are really good when combined.

eg: `"You know what's actually really good? Pancakes and relish."`

### Examples:
```python
Good_foods = ["Ice cream", "Ham", "Relish", "Pancakes", "Ketchup", "Cheese", "Eggs", "Cupcakes", "Sour cream", "Hot chocolate", "Avocado", "Skittles"]

actually_really_good( Good_foods ) #  "You know what's actually really good? Pancakes and relish."

actually_really_good( ['Peanut butter'] ) #  "You know what's actually really good? Peanut butter and more peanut butter."

actually_really_good( [] ) #  "You know what's actually really good? Nothing!"
```

### Notes:
There are many different valid combinations of 2 foods it doesn't matter which one you choose.
But there should be 2 different foods listed **unless** there was only one food given in the input array.
Capitalization should be correct, the first given food should be capitalized, but the second should not.
The input array should not be modified by the method.

The test cases for this kata are fairly complicated, see if you can trick them. (Then let me know about it in the discourse.)

The original kata language is *Ruby*

### Bonus:
If you thought this kata was easy, try this one: [Testing 'Food combinations'](http://www.codewars.com/kata/testing-food-combinations) in which you get to write a method similar to the one the tests here use to check that a result is valid and returns any errors it has.

def actually_really_good(foods):
    def formatter(pairFood):
        return (f(s) for f,s in zip((str.capitalize, str.lower), pairFood))
    START = "You know what's actually really good? "
    return START + ("Nothing!" if not foods else
                    "{1} and {0}{2}.".format("more "*(len(foods)==1), *formatter(foods*2 if len(foods)==1 else foods[:2])))


Solve in Python:
[comment]: # (Hello Contributors, the following guidelines in order of importance should help you write new translations and squash any pesky unintended bugs.)
[//]: # (The epsilon of all floating point test case comparisons is 0.01.)
[//]: # (Each test case shall pass if the statement "a^2 + b^2 = c^2" is true of the returned object.)
[//]: # (The test suite should contain 3 fixed test and exactly 512 random tests.)
[//]: # ( The following fixed test shall be used in the test suite as well as the example test suite:)
[//]: # (  {a: 3, b: 4, c: 5} from input {a: 3, b: 4})
[//]: # (  {a: 5, c: 13, b: 12} from input {a: 5, c: 13})
[//]: # (  {b: 2, c: 3, a: 2.236} from input {b: 2, c: 3})
[//]: # ( Random tests shall assign float values of a random range between 0.1-10.1 to properties a and b, and 14.5-114.5 to property c, after which, one of the properties is removed at random if target language allows for property insertions and deletions, or has its value replaced with either NaN if possible, or 0 if not.)
[//]: # (The test suite should not be sensitive to property insertion or placement order of the returned object.)
[//]: # (Validation attempts should not produce any errors outside the solution scope regardless of solution content.)

My tired eyes surveyed the horizon to spot a right triangle, made of an unknown material that sparkles in the endless void I have trekked thus far.

I hurried towards it. However far it seemed, it can't compare to the uncounted days I have been trapped here in this endless void. To break the monotony, it shall do nicely.

Reaching the triangle, I inspected it. It is even more spectacular up close than a far, like a piece of the heavens, just as grand as the best Hubble photo I've ever seen. Adorned onto its striking surface were two numbers, each hugging a side of the triangle in white chalk.

```python
{'a': 3, 'b': 4}
```

Almost unconsciously, I grabbed at the misshapen chalk piece in my pocket, a small stone shaped calcium oddity I found among the void. I am hit with the...

def how_to_find_them(right_triangle):
    if 'a' not in right_triangle:
        right_triangle['a'] = round((right_triangle['c']**2 - right_triangle['b']**2)**0.5, 3)
    elif 'b' not in right_triangle:
        right_triangle['b'] = round((right_triangle['c']**2 - right_triangle['a']**2)**0.5, 3)
    else:
        right_triangle['c'] = round((right_triangle['a']**2 + right_triangle['b']**2)**0.5, 3)
    return right_triangle


Solve in Python:
_A mad sociopath scientist just came out with a brilliant invention! He extracted his own memories to forget all the people he hates! Now there's a lot of information in there, so he needs your talent as a developer to automatize that task for him._

> You are given the memories as a string containing people's surname and name (comma separated). The scientist marked one occurrence of each of the people he hates by putting a '!' right before their name.

**Your task is to destroy all the occurrences of the marked people.
One more thing ! Hate is contagious, so you also need to erase any memory of the person that comes after any marked name!**

---
Examples
---
---
Input:
```
"Albert Einstein, !Sarah Connor, Marilyn Monroe, Abraham Lincoln, Sarah Connor, Sean Connery, Marilyn Monroe, Bjarne Stroustrup, Manson Marilyn, Monroe Mary"
```
Output:
```
"Albert Einstein, Abraham Lincoln, Sean Connery, Bjarne Stroustrup, Manson Marilyn, Monroe Mary"
```
=> We must remove every memories of Sarah Connor because she's marked, but as a side-effect we must also remove all the memories about Marilyn Monroe that comes right after her! Note that we can't destroy the memories of Manson Marilyn or Monroe Mary, so be careful!

def select(memory):

    s = memory.split(", ")
    result = memory.split(", ")

    set1= set()

    for i in range(len(s)):

        if s[i].find('!') != -1:
            set1.add(str(s[i])[(s[i].find('!')+1):len(s[i])])
            if i != len(s)-1:
                set1.add(str(s[i+1])[(s[i+1].find('!')+1):len(s[i+1])])

    for i in s:
        for j in set1:
            if i.find(j) != -1:
                result.remove(i)

    return ', '.join(result)


Solve in Python:
_Based on [Project Euler problem 35](https://projecteuler.net/problem=35)_

A circular prime is a prime in which every circular permutation of that number is also prime. Circular permutations are created by rotating the digits of the number, for example: `197, 971, 719`. One-digit primes are circular primes by definition.

Complete the function that dertermines if a number is a circular prime.

There are 100 random tests for numbers up to 10000.

from collections import deque

def is_prime(n):
   return n > 1 and all(n % i != 0 for i in range(2, int(n**0.5) + 1))

def circular_prime(n):
    items = deque(str(n))
    for _ in range(len(items)):
        items.rotate(1)
        if not is_prime(int("".join(items))):
            return False
    return True


Solve in Python:
_Friday 13th or Black Friday is considered as unlucky day. Calculate how many unlucky days are in the given year._

Find the number of Friday 13th in the given year.

__Input:__ Year as an integer.

__Output:__ Number of Black Fridays in the year as an integer.

__Examples:__

        unluckyDays(2015) == 3
        unluckyDays(1986) == 1

***Note:*** In Ruby years will start from 1593.

from datetime import datetime

def unlucky_days(year):
    """returns the numbers of Fridays 13th found in a given year.

       example:
       >> print('%s unlucky days found in year 2020.' % unlucky_days(2020))
    """
    spooky_days = 0
    if (isinstance(year, int) and (0 < year < 10000)):
        months = ('01', '02', '03', '04', '05', '06',
                  '07','08', '09', '10', '11', '12')
        for m in months:
            date_to_check = str(year) + '-' + m + '-13'
            day = datetime.strptime(date_to_check, '%Y-%m-%d').weekday()
            if day == 4:
                spooky_days += 1
    return spooky_days


Solve in Python:
_That's terrible! Some evil korrigans have abducted you during your sleep and threw you into a maze of thorns in the scrubland D:
But have no worry, as long as you're asleep your mind is floating freely in the sky above your body._
> **Seeing the whole maze from above in your sleep, can you remember the list of movements you'll have to do to get out when you awake?**

---

**Input**
---
---

You are given the whole maze `maze` as a 2D grid, more specifically in your language:
```if:ruby,javascript,python
an array of strings
```
```if:java
a `char[][]`
```
```if:ruby,javascript,python,java
`maze[0][0]` is the top left-hand corner
```
```if:c
a `Maze*` (a struct with three fields: `unsigned height`, `unsigned width`, `char **grid`)
Each line is '\0' terminated, but the array of lines is not.
`maze->grid[0][0]` is the top left-hand corner.
```
```if:java,javascript,ruby
`maze[maze.length - 1][maze[0].length - 1]` is the bottom right-hand corner
```
```if:python
`maze[len(maze) - 1][len(maze[0]) - 1]` is the bottom right-hand corner
```
```if:c
`maze->grid[maze->height - 1][maze->width - 1]` is the bottom right-hand corner.
```
Inside this 2D grid:
 - `' '` is some walkable space
 - `'#'` is a thorn bush (you can't pass through)
 - `'^'`, `'<'`, `'v'` or `'>'` is your sleeping body facing respectively the top, left, bottom or right side of the map.

---

**Output**
---
---
Write the function `escape` that returns the list/array of moves you need to do relatively to the direction you're facing in order to escape the maze (you won't be able to see the map when you wake up). as an array of the following instructions:
 - `'F'` move one step forward
 - `'L'` turn left
 - `'R'` turn right
 - `'B'` turn back
 > Note: `'L'`,`'R'`, and `'B'` **ONLY** perform a rotation and will not move your body

```if:javascript,ruby,python,java
If the maze has no exit, return an empty array.
```
```if:c
If the maze has no exit, return `NULL`.
```
* This is a real maze, there is no "escape" point. Just reach the...

class Piece:

    def __init__(self, map):
        self.map = map
        self.size = (len(map) - 1, len(map[0]) - 1)
        for num, line in enumerate(map):
            for tag in ('^', '<', 'v', '>'):
                if tag in line:
                    self.x, self.y, self.direct = num, line.index(tag), tag
        self.walked = set()     # 记录所有行进过得点
        self.walked.add((self.x, self.y))
        self.forks = []     # 记录所有岔路口以及在岔路口时的步数
        self.steps = 0  # 记录行动过得步数，方便回溯
        self.check_fork(self.x, self.y, 1)  # 起点时有两个方向就算岔路口
        self.dir = {
            'up': ('^', (-1, 0)),
            'down': ('v', (1, 0)),
            'left': ('<', (0, -1)),
            'right': ('>', (0, 1)),
        }
        self.turn = {
            '>': {'L': self.dir['up'], 'R': self.dir['down'], 'B': self.dir['left'], 'F': self.dir['right']},
            '<': {'L': self.dir['down'], 'R': self.dir['up'], 'B': self.dir['right'], 'F': self.dir['left']},
            '^': {'L': self.dir['left'], 'R': self.dir['right'], 'B': self.dir['down'], 'F': self.dir['up']},
            'v': {'L': self.dir['right'], 'R': self.dir['left'], 'B': self.dir['up'], 'F': self.dir['down']},
        }

    def check_fork(self, x, y, direct=2):
        count = 0
        for x_, y_ in ((x+1, y), (x-1, y), (x, y+1), (x, y-1)):
            if x_ >= 0 and x_ <= self.size[0] and y_ >= 0 and y_ <= self.size[1]:
                if self.map[x_][y_] != '#':
                    count += 1
        fork = ((x, y), self.steps, self.direct)
        for _ in range(count-direct):   # 四个方向有三个能通才是岔路口
            self.forks.append(fork)

    def draw_map(self, x, y):
        self.map[x] = self.map[x][:y] + self.direct + self.map[x][y + 1:]

    def go_forward(self):
        self.direct, (x, y) = self.turn[self.direct]['F']
        x, y = self.x + x, self.y + y
        if self.map[x][y] != '#' and (x, y) not in self.walked:     # 只有前方是空地，并且没有走过才会向前走
            self.x, self.y = x, y
            self.walked.add((x, y))  # 将走过的路劲都记录下来，不走重复的路
           ...


Solve in Python:
_This kata is based on [Project Euler Problem 546](https://projecteuler.net/problem=546)_

# Objective

Given the recursive sequence

fk(n) =

∑

i
=
0

n

fk(floor(i / k)) where fk(0) = 1

Define a function `f` that takes arguments `k` and `n` and returns the nth term in the sequence fk

## Examples

`f(2, 3)` = f2(3) = 6

`f(2, 200)` = f2(200) = 7389572

`f(7, 500)` = f7(500) = 74845

`f(1000, 0)` = f1000(0) = 1

**Note:**
No error checking is needed, `k` ranges from 2 to 100 and `n` ranges between 0 and 500000 (mostly small and medium values with a few large ones)

As always any feedback would be much appreciated

def f(k, n):
    r=[1]
    diff=0
    c=1
    while(n>=len(r)):
        r.append(r[-1]+r[diff])
        c+=1
        if c==k:
            c=0
            diff+=1
    return r[n]


cache = [0, 2, 4]
comp = [0, 2, 6]

repeat = len(cache)-1
b = cache[-1]
while comp[-1] < 2 ** 41:
    if len(cache) >= b:
        repeat += 1
        b = cache[repeat]
    cache.append(cache[-1] + repeat)
    comp.append(comp[-1] + (cache[-1] - cache[-2]) * (len(cache) - 1))

from bisect import bisect
def find(n):
    repeat = bisect(comp, n)
    return cache[repeat-1] + (n - comp[repeat-1]) // repeat


Solve in Python:
__Definition:__ According to Wikipedia, a [complete binary tree](https://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees) is a binary tree _"where every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible."_

The Wikipedia page referenced above also mentions that _"Binary trees can also be stored in breadth-first order as an implicit data structure in arrays, and if the tree is a complete binary tree, this method wastes no space."_

Your task is to write a method (or function) that takes an array (or list, depending on language) of integers and, assuming that the array is ordered according to an _in-order_ traversal of a complete binary tree, returns an array that contains the values of the tree in breadth-first order.

__Example 1:__
Let the input array be `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]`. This array contains the values of the following complete binary tree.

```
          _ 7_
        /      \
       4        9
     /   \     / \
   2      6   8   10
  / \     /
 1   3   5
```
In this example, the input array happens to be sorted, but that is _not_ a requirement.

__Output 1:__ The output of the function shall be an array containing the values of the nodes of the binary tree read top-to-bottom, left-to-right. In this example, the returned array should be:

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

__Example 2:__
Let the input array be `[1, 2, 2, 6, 7, 5]`. This array contains the values of the following complete binary tree.

```
        6
      /   \
    2       5
   / \     /
  1   2   7

```
Note that an in-order traversal of this tree produces the input array.

__Output 2:__ The output of the function shall be an array containing the values of the nodes of the binary tree read top-to-bottom, left-to-right. In this example, the returned array should be:

```[6, 2, 5, 1, 2, 7]```

def complete_binary_tree(a):
    def in_order(n=0):
        if n < len(a):
            yield from in_order(2 * n + 1)
            yield n
            yield from in_order(2 * n + 2)

    result = [None] * len(a)
    for i, x in zip(in_order(), a):
        result[i] = x
    return result


Solve in Python:
__Function composition__ is a mathematical operation that mainly presents itself in lambda calculus and computability. It is explained well [here](http://www.mathsisfun.com/sets/functions-composition.html), but this is my explanation, in simple mathematical notation:

```
f3 = compose( f1 f2 )
   Is equivalent to...
f3(a) = f1( f2( a ) )
```

Your task is to create a `compose` function to carry out this task, which will be passed two functions or lambdas. Ruby functions will be passed, and should return, either a proc or a lambda. Remember that the resulting composed function may be passed multiple arguments!

```python
compose(f , g)(x)
=> f( g( x ) )
```

This kata is not available in haskell; that would be too easy!

def compose(f,g):
    def composing(*args, **kwargs):
        return f(g(*args, **kwargs))
    return composing


Solve in Python:
_yet another easy kata!_

_Bored of usual python katas? me too;_

## Overview

     As you have guessed from the title of the kata you are going to implement a class that supports ***function overloading***. You might be thinking python doesn't support that thing... Of course python doesn't support that! So you have to implement that missing functionality.

     To achieve that You have to implement the `Meta` class which will be the metaclass of `Overload` class (see sample tests) and class that use `Meta` should work as usual at other things.

## The Goal

```python

class Overload(metaclass=Meta):

    CLS_VAR = 42

    def __init__(self):
        self.a = 1
        self.no = 'This is "No parameter" function.'
        self.single = 'This is "Single parameter" function'
        self.two = 'This is "Two parameter" function'
        self.three = 'This is "Three parameter" function'

    def foo(self):
        return self.no

    def foo(self, x):
        return self.single + ':' + str(x)

    def foo(self, x, y):
        return self.two + ':' + str(x) + ',' + str(y)

    def foo(self, x, y, z):
        return self.three + ':' + str(x) + ',' + str(y) + ',' + str(z)

    def extra(self):
        return 'This is extra method.'

  obj = Overload()

  Overload.foo=lambda self,a,b,c,d: 'from outside!'

  obj.foo()            # 'This is "No parameter" function.'
  obj.foo(1, 2)        # 'This is "Two parameter" function:1,2'
  obj.foo(1, 2, 3)     # 'This is "Three parameter" function:1,2,3'
  obj.foo(1, 2, 3, 4)  # 'from outside!'
```

## Specifications

   * The Overload base class will always be the same as above. It will be regenerated different times in the tests, for testing purpose.
   * All the other methods will be added and tested **after instanciation** the class like shown in the example above (***Focus on this point; you will need this***).
   * Only instance methods will be tested, no static or class level methods.
   * There is no testing for either `*varargs`...

from collections import defaultdict
def setter(prep, k, v, sup):
    if callable(v):
        def wrap(*args):
            a = prep.d[k][len(args)]
            if isinstance(a, int): raise AttributeError()
            return a(*args)
        prep.d[k][v.__code__.co_argcount] = v
        v = wrap
    sup(k, v)

class Prep(dict):
    def __init__(self): self.d = defaultdict(lambda: defaultdict(int))
    def __setitem__(self,k,v): setter(self, k, v, super().__setitem__)

class Meta(type):
    @classmethod
    def __prepare__(cls, *args, **kwargs): return Prep()

    def __new__(metacls, name, bases, prep, **kwargs):
        prep['_Meta__DCT'] = prep
        return super().__new__(metacls, name, bases, prep, **kwargs)

    def __setattr__(self, k, v): setter(self.__DCT, k, v, super().__setattr__)


Solve in Python:
`Description:`

Given an input array (`arr`) of positive integers, the objective is to return an output array where each index represents the amount of times an element appeared (frequency) in the input array.

More specifically, the element at each index of the output array will be an array (bucket) containing integers that appeared index-amount-of-times.

Otherwise, slot nulls (JavaScript, Java), None's (Python) nils (Ruby), or NULL's (C/C++) where appropriate. A valid array will always be provided.

If an array of [1,2,3,4,4,5,5,5] is passed in, the expected output should be: [null, [1,2,3], [4], [5], null, null, null, null, null].

`Explanation:`

```python
# bucketize(arr) ======> outputArray
bucketize(1,2,3,4,4,5,5,5) ======> [None, [1, 2, 3], [4], [5], None, None, None, None, None]
```

An element cannot appear 0 times, so a null is placed at outputArray[0]. The elements 1, 2, and 3 appear once. This is why they are located at outputArray[1]. Notice the elements are grouped together in an array and sorted in ascending order. The element 4 appears twice. This is why it is located at outputArray[2]. The element 5 appears three times. This is why it is located at outputArray[3].

Although an integer could have possibly appeared four, five, six, seven, or eight times, this is not the case for this particular example. This is the reason why the elements at outputArray[4], outputArray[5], outputArray[6], outputArray[7], and outputArray[8] are all null values.

`Examples:`

```python
bucketize(2,2,4,4,6,6,9,9,9,9) ==> [None, None, [2,4,6], None, [9], None, None, None, None, None, None]
bucketize(3,3,3,3,2) ============> [None, [2], None, None, [3], None]
bucketize(5,5,5,5,5) ============> [None, None, None, None, None, [5]]
bucketize(77,3,40,40,40) ========> [None, [3,77], None, [40], None, None]
bucketize(16,7,5,3,6,23) ========> [None, [3,5,6,7,16,23], None, None, None, None, None]
```

def bucketize(*args):
    d = {i:[] for i in range(len(args)+1)}
    for x in sorted(set(args)):
        d[args.count(x)].append(x)
    return [i if i else None for i in d.values()]


Solve in Python:
`This kata is the first of the ADFGX Ciphers, the harder version can be found `here.

The ADFGX Cipher is a pretty well-known Cryptographic tool, and is essentially a modified Polybius Square.

Rather than having numbers as coordinates on the table, it has the letters:

 `A, D, F, G, X`

Also, because this is the first step, and to help simplify things, you won't have to worry about a key, or the corresponding columnar transposition. In this kata ;)

All you have to do is encrypt and decrypt a string into `ADFGX` format.

`adfgx_encrypt() and adfgx_decrypt()` will be passed a string, `plaintext` and `ciphertext` respectively, and an adfgx`square`, for which will guide the operations.

Now for some examples to clear confusion:

```python
adfgx_encrypt("helloworld", "bchigklnmoqprstuvwxyzadef")

    A D F G X

A   b c h i g
D   k l n m o
F   q p r s t  -> square (PLEASE NOTE, j SHOULD BE TREATED AS i)
G   u v w x y
X   z a d e f

"helloworld"   -> plaintext

EVALUATES TO:

      F
          -> "AF"
A     h
--------------
          G
               -> "XG"
X         e

AND SO FORTH...

#Results in:

adfgx_encrypt("helloworld", "bchigklnmoqprstuvwxyzadef")
==
"AFXGDDDDDXGFDXFFDDXF"
```
Now decryption:
```python
adfgx_decrypt("FGXGADGDXGFXAXXGFGFGAADGXG", "aczlmuqngoipvstkrwfxhdbey)

    A D F G X

A   a c z l m
D   u q n g o
F   i p v s t  -> square (PLEASE NOTE, j SHOULD BE TREATED AS i)
G   k r w f x
X   h d b e y

"FGXGADGDXGFXAXXGFGFGAADGXG"   -> ciphertext

"FG" == "s"
"XG" == "e"

AND SO ON:

adfgx_decrypt("FGXGADGDXGFXAXXGFGFGAADGXG", "aczlmuqngoipvstkrwfxhdbey)
==
"secretmessage"
```
PLEASE NOTE: ALL INPUT WILL BE VALID, NO NEED TO ERROR CHECK :D

What are you waiting for?!
Go create `adfgx_encrypt() and adfgx_decrypt()`!

Good Luck!

from itertools import product
import re

KEY = [ a+b for a, b in product("ADFGX", repeat=2) ]

def adfgx_encrypt(plaintext, square):
    d      = dict(zip(square, KEY))
    oddity = d['i'] if 'i' in d else d['j']
    return ''.join(d.get(c, oddity) for c in plaintext)

def adfgx_decrypt(ciphertext, square):
    d      = dict(zip(KEY, square))
    IJkey  = [ k for k, v  in d.items() if v in 'ij'].pop()

    return ''.join( d.get(c, d[IJkey]) for c in re.findall(r'.{2}', ciphertext))


Solve in Python:
```
*************************
*  Create a frame!      *
*           __     __   *
*          /  \~~~/  \  *
*    ,----(     ..    ) *
*   /      \__     __/  *
*  /|         (\  |(    *
* ^  \  /___\  /\ |     *
*    |__|   |__|-..     *
*************************
```

Given an array of strings and a character to be used as border, output the frame with the content inside.

Notes:

* Always keep a space between the input string and the left and right borders.
* The biggest string inside the array should always fit in the frame.
* The input array is never empty.

## Example

`frame(['Create', 'a', 'frame'], '+')`

Output:
```
++++++++++
+ Create +
+ a      +
+ frame  +
++++++++++
```

from itertools import chain

def frame(words, char):
    size = max(map(len, words))
    frame = [char*(size+4)]
    middle = (f"{char} {word: <{size}} {char}" for word in words)
    return '\n'.join(chain(frame, middle, frame))


Solve in Python:
```
------------------------------------------------------------------
 we are programmed just to do anything you want us to
          w e  a r e  t h e  r o b o t s

-----------------------------------------------------------[ d[(0)(0)]b]
```
Task.....
You will receieve an array of strings
such as
```
a = ["We're functioning automatik d[(0)(0)]b","And we are dancing mechanik d[(0)(0)]b"]
```
Count the robots represented by d[(0)(0)]b

Unless of course the factory replaced a part on the robot.....
```
d[(0)(0)]b could look a little different depending on the supplier maybe like this

d[(0)(0)]B or d[(0)(0}]B
```
It's pretty random actually but with a global supply chain it's hard to control which part you get. Most of the parts are made global except the ones made in the factory which do not change.

```
d[(0)(0)]B

In all robots the eyes do not change.

d[(0)(0)]B

...0..0...
   ^  ^
   |  |

The rest of the body can change at random.

legs any in => abcdefghijklmnopqrstuvwxyz
...0..0...
^        ^
|        |

body any in => |};&#[]/><()*

...0..0...
 ^^ ^^ ^^
 || || ||

```
There may be cases where a part is totally missing and of course a robot cannot function at all without a part or where the factory put a valid part in the wrong place and it's again not a valid robot.

return an array of strings with a count of each of the following tasks.

Case insensitve count of robots in string with "automatik" or "mechanik". Strings do not contain both "automatik and "mechanik".

Return an array with the count like below

```
a[0] = automatik count
a[1] = mechanik count

["1 robots functioning automatik", "1 robots dancing mechanik"]

```
to pay tribute...respect :)

https://en.wikipedia.org/wiki/The_Robots

Songwriters: HUETTER, RALF / SCHNEIDER-ESLEBEN, FLORIAN / BARTOS, KARL

import re

LEGS = r'[a-z]'
BODY = r'[|};&#\[\]/><()*]'

counRobots = lambda a,type: str(sum( len(re.findall(LEGS + BODY + "{2}0" + BODY + "{2}0" + BODY + "{2}" + LEGS,s.lower())) for s in a if type in s.lower() ))
count_robots = lambda a : [ counRobots(a,"automatik") + " robots functioning automatik",  counRobots(a,"mechanik") + " robots dancing mechanik"]


Solve in Python:
```if-not:javascript,python
Write function `parseFloat` which takes an input and returns a number or `Nothing` if conversion is not possible.
```

```if:python
Write function `parse_float` which takes a string/list and returns a number or 'none' if conversion is not possible.
```

```if:javascript
Write function `parseF` which takes an input and returns a number or null if conversion is not possible. The input can be one of many different types so be aware.
```

def parse_float(string):

    try:
        return float(string)

    except:
        return None

   # return float(string) or None


Solve in Python:
```if-not:julia,racket
Write a function that returns the total surface area and volume of a box as an array: `[area, volume]`
```
```if:julia
Write a function that returns the total surface area and volume of a box as a tuple: `(area, volume)`
```
```if:racket
Write a function that returns the total surface area and volume of a box as a list: `'(area, volume)`
```

def get_size(w,h,d):
    surface = 2*((w*h)+(h*d)+(d*w))
    area = (w*h*d)

    return [surface,area]


Solve in Python:
```if-not:racket
Write a function called `repeat_str` which repeats the given string `src` exactly `count` times.
```
```if:racket
Write a function called `repeat-string` which repeats the given string `str` exactly `count` times.
```


Solve in Python:
```if-not:ruby
Create a function, that accepts an arbitrary number of arrays and returns a single array generated by alternately appending elements from the passed in arguments. If one of them is shorter than the others, the result should be padded with empty elements.
```
```if:ruby
Create a function, that accepts an arbitrary number of arrays and returns a single array generated by alternately appending elements from the passed in arguments. If one of them is shorter than the others, the result should be padded with `nil`s.
```

Examples:

```python
interleave([1, 2, 3], ["c", "d", "e"]) == [1, "c", 2, "d", 3, "e"]
interleave([1, 2, 3], [4, 5]) == [1, 4, 2, 5, 3, None]
interleave([1, 2, 3], [4, 5, 6], [7, 8, 9]) == [1, 4, 7, 2, 5, 8, 3, 6, 9]
interleave([]) == []
```

def interleave(*args):
    arr = []
    for i in range(max(len(a) for a in args)):
        for j in range(len(args)):
            try:    arr.append(args[j][i])
            except: arr.append(None)
    return arr


Solve in Python:
```if-not:rust
Your task is to write a function `toLeetSpeak` that converts a regular english sentence to Leetspeak.
```
```if:rust
Your task is to write a function `to_leet_speak` that converts a regular english sentence to Leetspeak.
```

More about LeetSpeak You can read at wiki -> https://en.wikipedia.org/wiki/Leet

Consider only uppercase letters (no lowercase letters, no numbers) and spaces.

For example:

```if-not:rust
~~~
toLeetSpeak("LEET") returns "1337"
~~~
```
```if:rust
~~~
to_leet_speak("LEET") returns "1337"
~~~
```

In this kata we use a simple LeetSpeak dialect. Use this alphabet:

```
{
  A : '@',
  B : '8',
  C : '(',
  D : 'D',
  E : '3',
  F : 'F',
  G : '6',
  H : '#',
  I : '!',
  J : 'J',
  K : 'K',
  L : '1',
  M : 'M',
  N : 'N',
  O : '0',
  P : 'P',
  Q : 'Q',
  R : 'R',
  S : '$',
  T : '7',
  U : 'U',
  V : 'V',
  W : 'W',
  X : 'X',
  Y : 'Y',
  Z : '2'
}
```


Solve in Python:
```if-not:sql
Create a function (or write a script in Shell) that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers.
```

```if:sql
## SQL Notes:
You will be given a table, `numbers`, with one column `number`.

Return a table with a column `is_even` containing "Even" or "Odd" depending on `number` column values.

### numbers table schema
* number INT

### output table schema
* is_even STRING
```

def even_or_odd(number):
    #and that's okay!
    if number % 2 == 0:
        #TELL MEEEEE
        return "Even"
    else:
        return "Odd"


Solve in Python:
```if-not:sql
Implement a function that receives two IPv4 addresses, and returns the number of addresses between them (including the first one, excluding the last one).
```

```if:sql
Given a database of first and last IPv4 addresses, calculate the number of addresses between them (including the first one, excluding the last one).

## Input

~~~
---------------------------------
|     Table    | Column | Type  |
|--------------+--------+-------|
| ip_addresses | id     | int   |
|              | first  | text  |
|              | last   | text  |
---------------------------------
~~~

## Output

~~~
----------------------
|   Column    | Type |
|-------------+------|
| id          | int  |
| ips_between | int  |
----------------------
~~~
```

All inputs will be valid IPv4 addresses in the form of strings. The last address will always be greater than the first one.

___

## Examples

```python
ips_between("10.0.0.0", "10.0.0.50")  ==   50
ips_between("10.0.0.0", "10.0.1.0")   ==  256
ips_between("20.0.0.10", "20.0.1.0")  ==  246
```

def ips_between(start, end):
    # TODO
    x=[]
    x=start.split(".")
    y=[]
    u=[]
    y=end.split(".")
    for i in range(4):
        u.append(int(y[i])-int(x[i]))
    t=u[-1]
    for i in range(1,4):t+=u[-1-i]*(256**i)
    return t


Solve in Python:
```if-not:swift
Create a method that takes an array/list as an input, and outputs the index at which the sole odd number is located.

This method should work with arrays with negative numbers. If there are no odd numbers in the array, then the method should output `-1`.
```
```if:swift
reate a function `oddOne` that takes an `[Int]` as input and outputs the index at which the sole odd number is located.

This method should work with arrays with negative numbers. If there are no odd numbers in the array, then the method should output `nil`.
```
Examples:
```python
odd_one([2,4,6,7,10]) # => 3
odd_one([2,16,98,10,13,78]) # => 4
odd_one([4,-8,98,-12,-7,90,100]) # => 4
odd_one([2,4,6,8]) # => -1
```

def odd_one(lst):
    return next((i for i, n in enumerate(lst) if n % 2 == 1), -1)


Solve in Python:
```if-not:swift
Write simple .camelCase method (`camel_case` function in PHP, `CamelCase` in C# or `camelCase` in Java) for strings. All words must have their first letter capitalized without spaces.
```
```if:swift
Write a simple `camelCase` function for strings. All words must have their first letter capitalized and all spaces removed.
```
For instance:

```python
camelcase("hello case") => HelloCase
camelcase("camel case word") => CamelCaseWord
```
```c#
using Kata;

"hello case".CamelCase(); // => "HelloCase"
"camel case word".CamelCase(); // => "CamelCaseWord"
```

Don't forget to rate this kata! Thanks :)

def camel_case(s):
    return s.title().replace(' ','')


Solve in Python:
```if:csharp
## Terminal Game - Create Hero Class

In this first kata in the series, you need to define a Hero class to be used in a terminal game. The hero should have the following attributes:

attribute | type | value
---|---|---
Name | string | user argument or "Hero"
Position | string | "00"
Health | float | 100
Damage | float | 5
Experience | int | 0
```

```if-not:csharp
## Terminal Game - Create Hero Prototype

In this first kata in the series, you need to define a Hero prototype to be used in a terminal game. The hero should have the following attributes:

attribute | value
---|---
name | user argument or 'Hero'
position | '00'
health | 100
damage | 5
experience | 0
```

class Hero():
    def __init__(self, name = "Hero"):
        self.name = name
        self.experience = 0
        self.health = 100
        self.position = '00'
        self.damage = 5
myHero = Hero()
#Solved on 26th Nov, 2019 at 04:49 PM.


Solve in Python:
```if:java
___Note for Java users:___ Due to type checking in Java, inputs and outputs are formated quite differently in this language. See the footnotes of the description.

```

You have the following lattice points with their corresponding coordinates and each one with an specific colour.

 ```
Point   [x ,  y]     Colour
----------------------------
  A     [ 3,  4]     Blue
  B     [-7, -1]     Red
  C     [ 7, -6]     Yellow
  D     [ 2,  5]     Yellow
  E     [ 1, -5]     Red
  F     [-1,  4]     Red
  G     [ 1,  7]     Red
  H     [-3,  5]     Red
  I     [-3, -5]     Blue
  J     [ 4,  1]     Blue
```
We want to count the triangles that have the three vertices with the same colour. The following picture shows the distribution of the points in the plane with the required triangles.

![source: imgur.com](http://i.imgur.com/sP0l1i1.png)

The input that we will have for the field of lattice points described above is:

```
[[[3, -4], "blue"],  [[-7, -1], "red"], [[7, -6], "yellow"], [[2, 5], "yellow"],
 [[1, -5], "red"],   [[-1, 4], "red"],  [[1, 7], "red"],     [[-3, 5], "red"],
 [[-3, -5], "blue"], [[4, 1], "blue"] ]
```
We see the following result from it:

```
Colour   Amount of Triangles       Triangles
Yellow         0                    -------
Blue           1                      AIJ
Red            10                   BEF,BEG,BEH,BFG,BFH,BGH,EFG,EFH,EHG,FGH
```
As we have 5 different points in red and each combination of 3 points that are not aligned.

We need a code that may give us the following information in order:

```
1) Total given points
2) Total number of colours
3) Total number of possible triangles
4) and 5) The colour (or colours, sorted alphabetically) with the highest amount of triangles
```

In Python our function will work like:

```
[10, 3, 11, ["red",10]]) == count_col_triang([[[3, -4], "blue"],  [[-7, -1], "red"], [[7, -6], "yellow"], [[2, 5], "yellow"],
                                              [[1, -5], "red"],   [[-1, 4], "red"],  [[1, 7], "red"],     [[-3, 5],...

from itertools import combinations

def grad(a, b):
    """Builds a gradient description"""
    rise, tread = b[1] - a[1], b[0] - a[0]
    if rise == 0 or tread == 0:
        if rise == tread:
            return "p" # Single point
        elif rise == 0:
            return "y" # Y Axis constant
            # return "y={}".format(a[0])
        return "x" # X Axis constant
    else:
        # Warning: Float used in comparison later, could be a problem
        # but not likely given integer inputs
        return rise / tread

def collinear(a, b, c):
    """Determines if three points are colinear"""
    return grad(a, b) == grad(b, c)

def count_col_triang(input_):
    # Group the inputs based on colour, to unique points within each colour
    colors = set(map(lambda t: t[1], input_))
    points = {col: set() for col in colors}
    for coord, color in input_:
        points[color].add(tuple(coord))

    # Discard any colours with less than 3 unique points
    # Geometry fact: Need at least 3 points to form a triangle!
    points = {k: list(sorted(v)) for k, v in points.items() if len(v) > 2}

    total = 0
    counts = {}
    for color, point_list in points.items():
        count = 0
        # Generate all possible trios of potential triangle vertices
        for a, b, c in combinations(point_list, 3):
            # Make sure the points are not collinear
            if not collinear(a, b, c):
                # Yay! we found a triangle
                count += 1
        counts[color] = count
        total += count

    # Identify colours with greatest number of triangles
    most_count = max(counts.values())
    most = [c for c, n in counts.items() if n == most_count]
    most = [] if most_count == 0 else (list(sorted(most)) + [most_count])

    # Collate stats and return
    return [len(input_), len(colors), total, most]


Solve in Python:
```if:javascript
`Array.prototype.length` will give you the number of top-level elements in an array.
```
```if:ruby
`Array#length` will give you the number of top-level elements in an array.
```
```if:csharp
The `Length` property of an array will give you the number of top-level elements in an array.
```
```if:php
`count()` will give you the number of top-level elements in an array if exactly one argument `$a` is passed in which is the array.
```
```if:python
`len(a)` will give you the number of top-level elements in the list/array named `a`.
```

Your task is to create a function ```deepCount``` that returns the number of ALL elements within an array, including any within inner-level arrays.

For example:

```if:javascript
    deepCount([1, 2, 3]);
    //>>>>> 3
    deepCount(["x", "y", ["z"]]);
    //>>>>> 4
    deepCount([1, 2, [3, 4, [5]]]);
    //>>>>> 7
```
```if:ruby
    deepCount([1, 2, 3]);
    //>>>>> 3
    deepCount(["x", "y", ["z"]]);
    //>>>>> 4
    deepCount([1, 2, [3, 4, [5]]]);
    //>>>>> 7
```
```if:csharp
    deepCount([1, 2, 3]);
    //>>>>> 3
    deepCount(["x", "y", ["z"]]);
    //>>>>> 4
    deepCount([1, 2, [3, 4, [5]]]);
    //>>>>> 7
```
```if:php
    deep_c([1, 2, 3]);
    //>>>>> 3
    deep_c(["x", "y", ["z"]]);
    //>>>>> 4
    deep_c([1, 2, [3, 4, [5]]]);
    //>>>>> 7
```
```if:python
    deepCount([1, 2, 3]);
    //>>>>> 3
    deepCount(["x", "y", ["z"]]);
    //>>>>> 4
    deepCount([1, 2, [3, 4, [5]]]);
    //>>>>> 7
```

The input will always be an array.

```if:php
In PHP you may *not* assume that the array passed in will be non-associative.

Please note that `count()`, `eval()` and `COUNT_RECURSIVE` are disallowed - you should be able to implement the logic for `deep_c()` yourself ;)
```

deep_count=d=lambda a:sum(type(e)is not list or d(e)+1for e in a)


Solve in Python:
```if:python
Create a function `args_count`, that returns the count of passed arguments
```
```if:kotlin
Create a function `argsCount`, that returns the count of passed arguments
```
```if:ruby
Create a method `args_count`, that returns the count of passed arguments
```
```if:julia
Create a method `argscount`, that returns the count of passed arguments
```
```python
args_count(1, 2, 3) -> 3
args_count(1, 2, 3, 10) -> 4
```

def args_count(*arg, **kwarg):
    return len(arg) + len(kwarg)


Solve in Python:
```if:python
Note: Python may currently have some performance issues. If you find them, please let me know and provide suggestions to improve the Python version! It's my weakest language... any help is much appreciated :)
```

Artlessly stolen and adapted from Hackerrank.

Kara Danvers is new to CodeWars, and eager to climb up in the ranks. We want to determine Kara's rank as she progresses up the leaderboard.

This kata uses Dense Ranking, so any identical scores count as the same rank (e.g, a scoreboard of `[100, 97, 97, 90, 82, 80, 72, 72, 60]` corresponds with rankings of `[1, 2, 2, 3, 4, 5, 6, 6, 7]`

You are given an array, `scores`, of leaderboard scores, descending, and another array, `kara`, representing Kara's Codewars score over time, ascending. Your function should return an array with each item corresponding to the rank of Kara's current score on the leaderboard.

**Note:** This kata's performance requirements are significantly steeper than the Hackerrank version. Some arrays will contain millions of elements; optimize your code so you don't time out. If you're timing out before 200 tests are completed, you've likely got the wrong code complexity. If you're timing out around 274 tests (there are 278), you likely need to make some tweaks to how you're handling the arrays.

Examples:

(For the uninitiated, Kara Danvers is Supergirl. This is important, because Kara thinks and moves so fast that she can complete a kata within microseconds. Naturally, latency being what it is, she's already opened many kata across many, many tabs, and solves them one by one on a special keyboard so she doesn't have to wait hundreds of milliseconds in between solving them. As a result, the only person's rank changing on the leaderboard is Kara's, so we don't have to worry about shifting values of other codewarriors. Thanks, Supergirl.)

Good luck! Please upvote if you enjoyed it :)

from bisect import bisect_left

def leaderboard_climb(arr, kara):
    result = []
    arr.append(float('inf'))
    arr = sorted([-a for a in set(arr)])
    for k in kara:
        i = bisect_left(arr, -k)
        result.append(i)
    return result


Solve in Python:
```if:python,php
In this kata you will have to write a function that takes `litres` and `price_per_litre` as arguments. Purchases of 2 or more litres get a discount of 5 cents per litre, purchases of 4 or more litres get a discount of 10 cents per litre, and so on every two litres, up to a maximum discount of 25 cents per litre. But total discount per litre cannot be more than 25 cents. Return the toal cost rounded to 2 decimal places. Also you can guess that there will not be negative or non-numeric inputs.

Good Luck!
```

```if:csharp,java,javascript
In this kata you will have to write a function that takes `litres` and `pricePerLitre` as arguments. Purchases of 2 or more litres get a discount of 5 cents per litre, purchases of 4 or more litres get a discount of 10 cents per litre, and so on every two litres, up to a maximum discount of 25 cents per litre. But total discount per litre cannot be more than 25 cents. Return the toal cost rounded to 2 decimal places. Also you can guess that there will not be negative or non-numeric inputs.

Good Luck!
```

def fuel_price(litres, price_per_liter):
    if litres < 2:
        price_per_liter = price_per_liter
        return round(litres*price_per_liter,2)
    if litres < 4:
        price_per_liter = price_per_liter-0.05
        return round(litres*price_per_liter,2)
    if litres < 6:
        price_per_liter = price_per_liter-0.1
        return round(litres*price_per_liter,2)
    if litres < 8:
        price_per_liter = price_per_liter-0.15
        return round(litres*price_per_liter,2)
    if litres < 10:
        price_per_liter = price_per_liter-0.2
        return round(litres*price_per_liter,2)
    else:
        price_per_liter = price_per_liter-0.25
        return round(litres*price_per_liter,2)


Solve in Python:
`late_clock` function receive an array with 4 digits and should return the latest time that can be built with those digits.
The time should be in `HH:MM` format.

Examples:
```
[1, 9, 8, 3] => 19:38
[9, 1, 2, 5] => 21:59
```

You can suppose the input is correct and you can build from it a correct 24-hour time.

from itertools import permutations

def late_clock(digits):
  for p in permutations(sorted(digits, reverse=True)):
    if p[0] > 2 or (p[0] == 2 and p[1] > 3) or p[2] > 5: continue
    return '{}{}:{}{}'.format(*p)


Solve in Python:
`{a, e, i, o, u, A, E, I, O, U}`

Natural Language Understanding is the subdomain of Natural Language Processing where people used to design AI based applications have ability to understand the human languages. HashInclude Speech Processing team has a project named Virtual Assistant. For this project they appointed you as a data engineer (who has good knowledge of creating clean datasets by writing efficient code). As a data engineer your first task is to make vowel recognition dataset. In this task you have to find the presence of vowels in all possible substrings of the given string. For each given string you have to return the total number of vowels.

## Example

Given a string `"baceb"` you can split it into substrings: `b, ba, bac, bace, baceb, a, ac, ace, aceb, c, ce, ceb, e, eb, b`. The number of vowels in each of these substrings is `0, 1, 1, 2, 2, 1, 1, 2, 2, 0, 1, 1, 1, 1, 0`; if you sum up these number, you get `16` - the expected output.

**Note**: your solution should have linear time complexity.

vowels = "aeiou"

def vowel_recognition(stg):
    l = len(stg)
    return sum((i + 1) * (l - i) for i, c in enumerate(stg.lower()) if c in vowels)


Solve in Python:
and Bengali as well.
There are N$N$ cats (numbered 1$1$ through N$N$) and M$M$ rats (numbered 1$1$ through M$M$) on a line. Each cat and each rat wants to move from some point to some (possibly the same) point on this line. Naturally, the cats also want to eat the rats when they get a chance. Both the cats and the rats can only move with constant speed 1$1$.
For each valid i$i$, the i$i$-th cat is initially sleeping at a point a_i$a_i$. At a time s_i$s_i$, this cat wakes up and starts moving to a final point b_i$b_i$ with constant velocity and without any detours (so it arrives at this point at the time e_i = s_i + |a_i-b_i|$e_i = s_i + |a_i-b_i|$). After it arrives at the point b_i$b_i$, it falls asleep again.
For each valid i$i$, the i$i$-th rat is initially hiding at a point c_i$c_i$. At a time r_i$r_i$, this rat stops hiding and starts moving to a final point d_i$d_i$ in the same way as the cats ― with constant velocity and without any detours, arriving at the time q_i = r_i + |c_i-d_i|$q_i = r_i + |c_i-d_i|$ (if it does not get eaten). After it arrives at the point d_i$d_i$, it hides again.
If a cat and a rat meet each other (they are located at the same point at the same time), the cat eats the rat, the rat disappears and cannot be eaten by any other cat. A sleeping cat cannot eat a rat and a hidden rat cannot be eaten ― formally, cat i$i$ can eat rat j$j$ only if they meet at a time t$t$ satisfying s_i \le t \le e_i$s_i \le t \le e_i$ and r_j \le t \le q_j$r_j \le t \le q_j$.
Your task is to find out which rats get eaten by which cats. It is guaranteed that no two cats will meet a rat at the same time.

-----Input-----
- The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows.
- The first line of each test case contains two space-separated integers N$N$ and M$M$.
- N$N$ lines follow. For each i$i$ (1 \le i \le N$1 \le i \le N$), the i$i$-th of these lines contains three space-separated integers a_i$a_i$, b_i$b_i$ and...

# cook your dish here
class Animal:
    def __init__(self):
        start, end, starting_time = map(int, input().split())

        self.ending_time = starting_time + abs(start - end)
        self.velocity = 1 if end >= start else -1

        self.eaten_by = -1, 10 ** 10

        self.start = start
        self.end = end
        self.starting_time = starting_time

    def will_collide(self, z):
        if self.starting_time > z.ending_time or self.ending_time < z.starting_time:
            return False

        if self.velocity == z.velocity:
            if self.starting_time > z.starting_time:
                self, z = z, self
            if z.start == self.start + self.velocity * (z.starting_time - self.starting_time):
                return z.starting_time
            else:
                return False

        if self.velocity == -1:
            self, z = z, self

        t = ( z.start - self.start + z.starting_time + self.starting_time ) / 2

        return t if self.starting_time <= t <= self.ending_time and z.starting_time <= t <= z.ending_time else False

def main():
    for _ in range(int(input())):
        no_cats, no_rats = map(int, input().split())

        Cats = [Animal() for i in range(no_cats)]

        for i in range(no_rats):
            rat = Animal()
            for j in range(no_cats):
                time = rat.will_collide(Cats[j])
                if time:
                    # print(time)
                    if time < rat.eaten_by[1]:
                        rat.eaten_by = j + 1, time

            print(rat.eaten_by[0])

main()


Solve in Python:
in Chefland, there is a very famous street where $N$ types of street food (numbered $1$ through $N$) are offered. For each valid $i$, there are $S_i$ stores that offer food of the $i$-th type, the price of one piece of food of this type is $V_i$ (the same in each of these stores) and each day, $P_i$ people come to buy it; each of these people wants to buy one piece of food of the $i$-th type.
Chef is planning to open a new store at this street, where he would offer food of one of these $N$ types. Chef assumes that the people who want to buy the type of food he'd offer will split equally among all stores that offer it, and if this is impossible, i.e. the number of these people $p$ is not divisible by the number of these stores $s$, then only $\left\lfloor\frac{p}{s}\right\rfloor$ people will buy food from Chef.
Chef wants to maximise his daily profit. Help Chef choose which type of food to offer and find the maximum daily profit he can make.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- $N$ lines follow. For each $i$ ($1 \le i \le N$), the $i$-th of these lines contains three space-separated integers $S_i$, $P_i$ and $V_i$.

-----Output-----
For each test case, print a single line containing one integer ― the maximum profit.

-----Constraints-----
- $1 \le T \le 100$
- $1 \le N \le 100$
- $1 \le S_i, V_i, P_i \le 10,000$ for each valid $i$

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

-----Example Input-----
2
3
4 6 8
2 6 6
1 4 3
1
7 7 4

-----Example Output-----
12
0

-----Explanation-----
Example case 1: Chef should offer food of the second type. On each day, two people would buy from him, so his daily profit would be $12$.
Example case 2: Chef has no option other than to offer the only type of food, but he does not expect anyone to buy from him anyway, so his daily profit is $0$.

t=int(input())
while(t):
 n=int(input())
 l=[]
 for i in range(n):
  l.append(list(map(int,input().split())));
 m=[]
 for i in l:
  m.append((i[1]//(i[0]+1))*i[2])
 res=max(m)
 print(res)
 t=t-1


Solve in Python:
k kids seem to have visited your home for the festival. It seems like the kids
had all been fighting with each other, so you decided to keep them as far as
possible from each other. You had placed n chairs on the positive number line,
each at position x i , 1 ≤ i ≤ n. You can make the kids sit in any of the chairs.
Now you want to know the largest possible minimum distance between each kid.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains two lines. First line contains two space separated integers n and k. Second line contains n space separated values, x1, x2, x3, … ,xn.

-----Output:-----
For each test case print the largest possible minimum distance.

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

2 2

1 2

-----Sample Output:-----
1

-----Constraints-----
- $2 \leq n \leq 100000$
- $0 \leq xi \leq 10^9$
- $k \leq n $

#dt = {} for i in x: dt[i] = dt.get(i,0)+1
import sys;input = sys.stdin.readline
inp,ip = lambda :int(input()),lambda :[int(w) for w in input().split()]

def check(mid):
    pos = x[0]
    ct = 1
    for i in range(1,n):
        if x[i]-pos >= mid:
            pos = x[i]
            ct += 1
            if ct == k:
                return True
    return False

for _ in range(inp()):
    n,k = ip()
    x = ip()
    x.sort()
    ans = -1
    l,r = 1,x[-1]
    while l < r:
        mid = (l+r)//2
        if check(mid):
            ans = max(ans,mid)
            l = mid +1
        else:
            r = mid
    print(ans)


Solve in Python:
n passengers board an airplane with exactly n seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of passengers will:

Take their own seat if it is still available,
Pick other seats randomly when they find their seat occupied

What is the probability that the n-th person can get his own seat?

Example 1:
Input: n = 1
Output: 1.00000
Explanation: The first person can only get the first seat.
Example 2:
Input: n = 2
Output: 0.50000
Explanation: The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).

Constraints:

1 <= n <= 10^5

class Solution:
    def nthPersonGetsNthSeat(self, n: int) -> float:
        if n == 1: return 1
        if n == 2: return 0.5
        result = 1.0
        curr = 1.0
        for i in range(2, n + 1):
            result = (1 / i) * curr
            curr += result
        return result


Solve in Python:
per nextum in unam tum XI conscribementis fac sic

    vestibulo perlegementum da varo.

    morde varo.

    seqis cumula varum.

cis

per nextum in unam tum XI conscribementis fac sic

    seqis decumulamenta da varo.

    varum privamentum fodementum da aresulto.

    varum tum III elevamentum tum V multiplicamentum da bresulto.

    aresultum tum bresultum addementum da resulto.

    si CD tum resultum non praestantiam fac sic

        dictum sic f(%d) = %.2f cis tum varum tum resultum egresso describe.

        novumversum egresso scribe.

    cis

    si CD tum resultum praestantiam fac sic

        dictum sic f(%d) = MAGNA NIMIS! cis tum varum egresso describe.

        novumversum egresso scribe.

    cis

cis

-----Input-----

The input consists of several integers, one per line. Each integer is between -50 and 50, inclusive.

-----Output-----

As described in the problem statement.

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

Output
f(10) = MAGNA NIMIS!
f(-9) = -3642.00
f(-8) = -2557.17
f(-7) = -1712.35
f(-6) = -1077.55
f(-5) = -622.76
f(-4) = -318.00
f(-3) = -133.27
f(-2) = -38.59
f(1) = 6.00
f(0) = 0.00

#!/usr/bin/env python

import os
import sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from builtins import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

def main():
    stack = [int(input().strip()) for _ in range(11)]
    for _ in range(11):
        v = stack.pop()
        a = (abs(v)) ** 0.5
        b = v ** 3 * 5
        result = a + b
        if result > 400:
            print("f({}) = MAGNA NIMIS!".format(v))
        else:
            print("f({}) = {:.2f}".format(v, result))

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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


Solve in Python:
pre.handle{
      height: 2em;
      width: 4em;
      margin: auto;
      margin-bottom: 0 !important;
      background: none !important;

      border-radius: 0.5em 0.5em 0 0;
      border-top: 5px solid saddlebrown;
      border-left: 5px solid saddlebrown;
      border-right: 5px solid saddlebrown;
  }

  table.example-piece{
      width: fit-content;
      height: fit-content;

      margin: auto;
  }

  pre.piece{
      font-size: 1.75em;
      line-height: 1.4;
      letter-spacing: 0.1em;

      background: none !important;
  }

  pre.bag{
      border-radius: 0.5em;
      border:5px solid saddlebrown;
      width: fit-content;
      background: burlywood;

      font-size: 1.75em;
      line-height: 1.4;
      letter-spacing: 0.1em;
      color: white;
      text-align: center;

      margin: auto;
      padding: 0.2em;

  }

  pre b{
      padding: 0.1em;
  }

  .a{ background: darkolivegreen; }
  .b{ background: seagreen;}
  .c{ background: limegreen; }
  .d{ background: darkgreen; }

# On a business trip, again...

I love traveling, just like everyone else. If only they were not business trips... They force me to go to places I don't want to go and listen to people that I don't care about. But, by far, the thing I hate the most is **packing my bag**.

The thing is, I can only carry one bag in the plane and I **NEED** to bring some important items. Every item is numbered and has a specific shape. Here is an example of a well-sorted bag:

11112233
14444233
14442223

Will I be able to fit all the items I need in the bag?

# Your task

Write a funtion `fit_bag(height: int, width: int, items: List[List[List[int]]]) -> List[List[int]]` that takes a bag height and width and a list of items and returns a bag with all the items in a correct place.

The pieces will be given as a square bidimensional array that represents items as follows:

1111
1
1

 →

[
  [1, 1, 1, 1],
  [1, 0, 0, 0],
  [1, 0, 0, 0]
]

4444
444

 →

[
  [4, 4, 4, 4],
  [4, 4,...

from copy import deepcopy

pieces = {}
solution = []

def fits_at(grid, p, y, x):
    nonlocal pieces
    for pos in pieces[p]:
        py = y+pos[0]
        if py < 0 or py >= len(grid):
            return False
        px = x+pos[1]
        if px < 0 or px >= len(grid[0]):
            return False
        if grid[py][px] != 0:
            return False
    return True

def rec_solve(grid, items):
    nonlocal pieces, solution
    if items == [] or solution != []:
        return

    # fit 1st piece
    val = items[0]
    for y in range(len(grid)):
        for x in range(len(grid[0])):
            if fits_at(grid, val, y, x):
                # piece fits
                # place piece
                for pos in pieces[val]:
                    grid[y+pos[0]][x+pos[1]] = val
                # recursive solve
                next_list = items[1:]
                rec_solve(grid, next_list)
                if next_list == []:
                    solution = deepcopy(grid)
                    return
                # remove piece
                for pos in pieces[val]:
                    grid[y+pos[0]][x+pos[1]] = 0

def fit_bag(height: int, width: int, items: List[List[List[int]]]) -> List[List[int]]:
    # make list of relative positions from an empty grid position
    nonlocal pieces, solution
    solution = []
    item_ids = []
    for item in items:
        i = 0
        while item[0][i] == 0:
            i += 1
        anchor = [0,i]
        val = item[0][i]

        # generate list of coordinates relative to anchor
        rel_c = []
        for h in range(len(item)):
            for w in range(len(item[0])):
                if item[h][w] != 0:
                    newpos = [h,w-i]
                    rel_c.append(newpos)
        pieces[val] = rel_c
        item_ids.append(val)

    grid = [[0 for x in range(width)] for y in range(height)]
    rec_solve(grid, item_ids)
    return solution


Solve in Python:
table {
        width: 236px;
    }

    table, tr, td {
        border: 0px;
    }

In a grid of 4 by 4 squares you want to place a skyscraper in each square with only some clues:

The height of the skyscrapers is between 1 and 4
No two skyscrapers in a row or column may have the same number of floors
A clue is the number of skyscrapers that you can see in a row or column from the outside
Higher skyscrapers block the view of lower skyscrapers located behind them

Can you write a program that can solve this puzzle?

Example:

To understand how the puzzle works, this is an example of a row with 2 clues. Seen from the left side there are 4 buildings visible while seen from the right side only 1:

 4

 1

There is only one way in which the skyscrapers can be placed. From left-to-right all four buildings must be visible and no building may hide behind another building:

 4
 1
 2
 3
 4
 1

Example of a 4 by 4 puzzle with the solution:

 1
 2

 2

 1

 3

 1
 2

 2
 1
 4
 3

 3
 4
 1
 2
 2

 1
 4
 2
 3
 1

 1
 3
 2
 4

 3

Task:

Finish:

#Solving the grid can be broken down into the following main steps:
#1) Using the outside view to remove certain options or place known numbers
#2) Look for block that only has one remaining option (step repeated each time grid is adjusted)
#3) Look for lines with two blocks with restriction of two same options remove these options for other blocks in line
#3) Look for lines with 2 blocks remaining. Create 2 options from these and compare to the view from both sides

#Practical routes taken:
#1)gridComplete is an array used to indicate if number was placed or not. This helps confirm if number is "placed" or just last remaining option. As when it is placed the same number needs to be removed from line and adjacent line
#2)Clues where placed into array with pairs horizonal and vertical. So that the can be looped and assigned easily

import numpy as np

def solve_puzzle (clues):

    nonlocal grid
    grid = np.array([("1234","1234","1234","1234"),("1234","1234","1234","1234"),("1234","1234","1234","1234"),("1234","1234","1234","1234")])

    nonlocal gridComplete
    gridComplete = np.array([(0,0,0,0),(0,0,0,0),(0,0,0,0),(0,0,0,0)])

    nonlocal cluesN
    cluesN = list(map(str,clues))
    clues = list(map(str,clues))

    nonlocal hor
    nonlocal vert
    hor = [(clues[0]+clues[11]),(clues[1]+clues[10]),(clues[2]+clues[9]),(clues[3]+clues[8])]
    vert =[(clues[15]+clues[4]),(clues[14]+clues[5]),(clues[13]+clues[6]),(clues[12]+clues[7])]

#1) Removing known options and placing according to view and standard practise
#----------------------------------------------------------------------------
    #1: M1:
    #    -1 place 4
    #    -4 place 1234
    #    -2V remove [1] 3
    #    -2V remove [0] 4
    #    -3V remove [0] 3

    #M1 - 4 place 1234
    for z in range(len(cluesN)):
        if cluesN[z] == "4" and z<=3:
            placeNum(1,0,z, check = False)
            placeNum(2,1,z, check = False)
            placeNum(3,2,z, check = False)
            placeNum(4,3,z, check =...


Solve in Python:
write me a function `stringy` that takes a `size` and returns a `string` of alternating `'1s'` and `'0s'`.

the string should start with a `1`.

a string with `size` 6 should return :`'101010'`.

with `size` 4 should return : `'1010'`.

with `size` 12 should return : `'101010101010'`.

The size will always be positive and will only use whole numbers.

stringy = lambda size: ('10' * size)[:size]


Solve in Python:
~~~if-not:java
You have to code a function **getAllPrimeFactors** wich take an integer as parameter and return an array containing its prime decomposition by ascending factors, if a factors appears multiple time in the decomposition it should appear as many time in the array.

exemple: `getAllPrimeFactors(100)` returns `[2,2,5,5]` in this order.

This decomposition may not be the most practical.

You should also write **getUniquePrimeFactorsWithCount**, a function which will return an array containing two arrays: one with prime numbers appearing in the decomposition and the other containing their respective power.

exemple: `getUniquePrimeFactorsWithCount(100)` returns `[[2,5],[2,2]]`

You should also write **getUniquePrimeFactorsWithProducts** an array containing the prime factors to their respective powers.

exemple: `getUniquePrimeFactorsWithProducts(100)` returns `[4,25]`
~~~
~~~if:java
You have to code a function **getAllPrimeFactors** wich take an integer as parameter and return an array containing its prime decomposition by ascending factors, if a factors appears multiple time in the decomposition it should appear as many time in the array.

exemple: `getAllPrimeFactors(100)` returns `[2,2,5,5]` in this order.

This decomposition may not be the most practical.

You should also write **getUniquePrimeFactorsWithCount**, a function which will return an array containing two arrays: one with prime numbers appearing in the decomposition and the other containing their respective power.

exemple: `getUniquePrimeFactorsWithCount(100)` returns `[[2,5],[2,2]]`

You should also write **getPrimeFactorPotencies** an array containing the prime factors to their respective powers.

exemple: `getPrimeFactorPotencies(100)` returns `[4,25]`
~~~

Errors, if:

* `n` is not a number
* `n` not an integer
* `n` is negative or 0

The three functions should respectively return `[]`,  `[[],[]]` and `[]`.

Edge cases:

* if `n=0`, the function should respectively return `[]`, `[[],[]]` and  `[]`.
* if `n=1`, the...

# RWH primes
LIMIT = 10**6
sieve = [True] * (LIMIT//2)
for i in range(3, int(LIMIT**0.5)+1, 2):
    if sieve[i//2]: sieve[i*i//2::i] = [False] * ((LIMIT-i*i-1)//2//i+1)
PRIMES = [2] + [2*i+1 for i in range(1, LIMIT//2) if sieve[i]]

from collections import Counter

def getAllPrimeFactors(n):
    # errors and zero
    if not type(n) == int or n < 1:
        return []

    # edge cases
    if n in (1, 2):
        return [n]

    # factorisation
    factors = []

    for p in PRIMES:
        if p*p > n:
            break
        while n % p == 0:
            n //= p
            factors.append(p)

    return factors + [n] * (n > 1)

def getUniquePrimeFactorsWithCount(n):
    factors = Counter(getAllPrimeFactors(n))
    return [ list(factors.keys()), list(factors.values()) ]

def getUniquePrimeFactorsWithProducts(n):
    factors = Counter(getAllPrimeFactors(n))
    return [ p**e for p, e in factors.items() ]


Solve in Python:
~~~if-not:ruby,python
Return `1` when *any* odd bit of `x` equals 1; `0` otherwise.
~~~
~~~if:ruby,python
Return `true` when *any* odd bit of `x` equals 1; `false` otherwise.
~~~

Assume that:
* `x` is an unsigned, 32-bit integer;
* the bits are zero-indexed (the least significant bit is position 0)

## Examples

```
  2  -->  1 (true) because at least one odd bit is 1 (2 = 0b10)
  5  -->  0 (false) because none of the odd bits are 1 (5 = 0b101)
170  -->  1 (true) because all of the odd bits are 1 (170 = 0b10101010)
```

def any_odd(x):
    bin = "{0:b}".format(x)
    bin = bin[::-1]
    odd = 0
    print(bin)
    for letter in bin:
        if odd%2 == 1 and letter == '1':
            return 1
        odd+= 1
    return 0


Solve in Python:
~~~if:csharp,javascript,cfml,php
Given a 2D array of size `m * n`. Your task is to find the sum of minimum value in each row.
~~~
~~~if:cpp
Given a 2D vector of size `m * n`. Your task is to find the sum of minimum value in each row.
~~~
~~~if:python,ruby
Given a 2D list of size `m * n`. Your task is to find the sum of minimum value in each row.
~~~

For Example:
```python
[
  [1, 2, 3, 4, 5],       # minimum value of row is 1
  [5, 6, 7, 8, 9],       # minimum value of row is 5
  [20, 21, 34, 56, 100]  # minimum value of row is 20
]
```
So, the function should return `26` because sum of minimums is as `1 + 5 + 20 = 26`

~~~if:javascript,php
Note: You will be always given non-empty array containing Positive values.
~~~
~~~if:python
Note: You will be always given non-empty list containing Positive values.
~~~
~~~if:cpp
Note: You will be always given non-empty vector containing Positive values.
~~~
~~~if:c#
Note: You will be always given non-empty vector containing Positive values.
~~~
~~~if:cfml
Note: You will be always given non-empty array containing Positive values.
~~~

ENJOY CODING :)

def sum_of_minimums(a):
    return sum(map(min, a))


Solve in Python:
— Hey folks, how do you like this problem?

— That'll do it.

BThero is a powerful magician. He has got $n$ piles of candies, the $i$-th pile initially contains $a_i$ candies. BThero can cast a copy-paste spell as follows:   He chooses two piles $(i, j)$ such that $1 \le i, j \le n$ and $i \ne j$.  All candies from pile $i$ are copied into pile $j$. Formally, the operation $a_j := a_j + a_i$ is performed.

BThero can cast this spell any number of times he wants to — but unfortunately, if some pile contains strictly more than $k$ candies, he loses his magic power. What is the maximum number of times BThero can cast the spell without losing his power?

-----Input-----

The first line contains one integer $T$ ($1 \le T \le 500$) — the number of test cases.

Each test case consists of two lines:   the first line contains two integers $n$ and $k$ ($2 \le n \le 1000$, $2 \le k \le 10^4$);  the second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($1 \le a_i \le k$).

It is guaranteed that the sum of $n$ over all test cases does not exceed $1000$, and the sum of $k$ over all test cases does not exceed $10^4$.

-----Output-----

For each test case, print one integer — the maximum number of times BThero can cast the spell without losing his magic power.

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

Output
1
5
4

-----Note-----

In the first test case we get either $a = [1, 2]$ or $a = [2, 1]$ after casting the spell for the first time, and it is impossible to cast it again.

from sys import stdin
###############################################################
def iinput(): return int(stdin.readline())
def minput(): return list(map(int, stdin.readline().split()))
def linput(): return list(map(int, stdin.readline().split()))
###############################################################

t = iinput()
while t:
    t -= 1
    n, k = minput()
    a = linput()
    a.sort()
    ans = 0
    for i in range(1, n):
        ans += max(0, k - a[i]) // a[0]
    print(ans)


Solve in Python:
“"Forward!", he cried from the rear
And the front rank died
The general sat and the lines on the map
Moved from side to side”Us and Them -- Pink Floyd
A few army battalions from warring nations have met on an even battlefield. Each nation has one battalion present and all battalions have an equal number of soldiers. Every soldier is armed with one rifle and unlimited ammunition. Every soldier also has perfect shooting accuracy. And all armies follow the rules of engagement below.
Rules of Engagement
1. Each army battalion forms its own straight line queue
2. Each line is formed such that the head of each queue faces the head of the opposing army queue to its left (or when there are only two remaining armies, both queues face toward each other)
3. All queue heads maintain equal distance from their respective targets
4. There is a 1 second delay for each queue head to fire his weapon (time taken to lift weapon, aim, then fire)
5. If a queue head gets hit by any bullets during that 1 second delay (including at the exact moment the head is expected to shoot), he falls before he can fire his rifle. Otherwise, he shoots his rifle and immediately walks back to the end of his queue.
Note that the head will receive all bullets that reach his position during that round.
6. The next soldier in queue then takes his place as head at the start of the next round. If there is only one soldier remaining in a queue, he will stand in place and shoot his rifle every round until he falls or emerges victorious
7. An army is eliminated when all its soldiers have fallen. When an elimination occurs, the eliminator changes their target to the next army queue in sequence at the start of the next round.

8.A. If an elimination occurs during the round, then all remaining armies reposition themselves at the start of the next round and repeat the cycle from step 2. All bullets still in flight at the end of the round will miss all their targets when the repositioning occurs.

8.B If no elimination occurs in the round, start again from step...

from collections import deque

class Bullet:

    def __init__(self, speed):
        self.speed = speed  # speed bullet travels
        self.location = 0  # distance travelled towards target

    def update(self):
        self.location += self.speed  # move bullet towards target

class Soldier:

    def __init__(self, number, firing_speed):
        self.number = number  # initial position of soldier in army
        self.firing_speed = firing_speed  # speed of bullets soldier fires

class Army:

    def __init__(self, number, firing_speeds):
        self.number = number  # number associated with army
        # convert input tuple of firing speeds of soldiers to deque of Soldier objects
        self.soldiers = deque()
        for n, firing_speed in enumerate(firing_speeds):
            self.soldiers.append(Soldier(n, firing_speed))

def queue_battle(distance, *args):
    """ Simulates battle. """

    armies = [Army(n, army) for n, army in enumerate(args)]  # list of Army objects

    while len(armies) > 1:  # while armies still fighting

        # reset bullets
        bullets = {army: [] for army in range(len(armies))}  # target: list of bullets moving towards target

        an_army_eliminated = False
        while not an_army_eliminated:  # fight until 1 or more armies eliminated

            # update bullet positions
            for army in range(len(armies)):
                for bullet in bullets[army]:
                    bullet.update()

            # for every army remove soldiers / fire as appropriate
            for army in range(len(armies)):

                for bullet in bullets[army]:
                    if bullet.location >= distance:  # remove leading soldier if hit by bullet before can fire
                        armies[army].soldiers.popleft()
                        if not armies[army].soldiers:  # mark an army has been eliminated
                            an_army_eliminated = True
                        break

                else:  # lead soldier not hit: fire and move to back
    ...


Solve in Python:
“I am not in danger, Skyler. I am the danger. A guy opens his door and gets shot, and you think that of me? No! I am the one who knocks!”
Skyler fears Walter and ponders escaping to Colorado. Walter wants to clean his lab as soon as possible and then go back home to his wife.
In order clean his lab, he has to achieve cleaning level of lab as $Y$. The current cleaning level of the lab is $X$.
He must choose one positive odd integer $a$ and one positive even integer $b$. Note that, he cannot change $a$ or $b$ once he starts cleaning.
He can perform any one of the following operations for one round of cleaning:
- Replace $X$ with $X+a$.
- Replace $X$ with $X-b$.
Find minimum number of rounds (possibly zero) to make lab clean.

-----Input:-----
- First line will contain $T$, number of test cases. $T$ testcases follow :
- Each test case contains two space separated integers $X, Y$.

-----Output:-----
For each test case, output an integer denoting minimum number of rounds to clean the lab.

-----Constraints-----
- $1 \leq T \leq 10^5$
- $ |X|,|Y| \leq 10^9$

-----Sample Input:-----
3
0 5
4 -5
0 10000001

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

-----EXPLANATION:-----
-
For the first testcase, you can convert $X$ to $Y$  by choosing $a=5$ and $b=2$.

It will cost minimum of $1$ cleaning round. You can select any other combination of $a, b$ satisfying above condition but will take minimum of $1$ cleaning round in any case.
-
For the second testcase, you can convert $X$ to $Y$ by choosing $a=1$ and $b=10$. In first round they will replace $X$ to $X+a$ and then in second round replace to $X-b$. You can perform only one operation in one round.

# cook your dish here
try:
 for t in range(int(input())):
  x,u = map(int,input().split())
  if(x==u):
   print(0)
  elif(u>x):
   if(abs(u-x)%2==0):
    if(abs(u-x)%4==0):
     print(3)
    else:
     print(2)
   else:
    print(1)
  else:
   if(abs(x-u)%2!=0):
    print(2)
   else:
    print(1)

except EOFError as e:
 pass