Solve in Python:
# Is the string uppercase?

## Task

```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby
Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example:
```
```if:haskell,reason,typescript
Create a method `isUpperCase` to see whether the string is ALL CAPS. For example:
```
```if:csharp
Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example:
```
```if:julia
Create a function `isupper` to see whether the string is ALL CAPS. For example:
```
```if:cpp
Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example:
```
```if:javascript,coffeescript
Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example:
```
```if:elixir
Create a method `upper_case?` to see whether the string is ALL CAPS. For example:
```
```if:forth,factor
Create a word `uppercase?` to check whether a string is ALL CAPS. For example:
```
```if:go
Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example:
```
```if:racket
Create a method `upcase?` to see whether the string is ALL CAPS. For example:
```
```if:ruby
Create a method `is_upcase?` to see whether the string is ALL CAPS. For example:
```

```python
is_uppercase("c") == False
is_uppercase("C") == True
is_uppercase("hello I AM DONALD") == False
is_uppercase("HELLO I AM DONALD") == True
is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False
is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True
```

In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.

def is_uppercase(inp):
    return True if inp.isupper() else False
#     if inp.upper():
#          return True
#     else:
#         return False


Solve in Python:
# It's too hot, and they can't even…

One hot summer day Pete and his friend Billy decided to buy watermelons. They chose the biggest crate. They rushed home, dying of thirst, and decided to divide their loot, however they faced a hard problem.

Pete and Billy are great fans of even numbers, that's why they want to divide the number of watermelons in such a way that each of the two parts consists of an even number of watermelons. However, it is not obligatory that the parts are equal.

Example: the boys can divide a stack of 8 watermelons into 2+6 melons, or 4+4 melons.

The boys are extremely tired and want to start their meal as soon as possible, that's why you should help them and find out, whether they can divide the fruits in the way they want. For sure, each of them should get a part of positive weight.

# Task
Given an integral number of watermelons `w` (`1 ≤ w ≤ 100`; `1 ≤ w` in Haskell), check whether Pete and Billy can divide the melons so that each of them gets an even amount.

## Examples

def divide(weight):
    return True if weight > 3 and not weight % 2 else 0


Solve in Python:
# Kata Task

A bird flying high above a mountain range is able to estimate the height of the highest peak.

Can you?

# Example

## The birds-eye view

^^^^^^
 ^^^^^^^^
  ^^^^^^^
  ^^^^^
  ^^^^^^^^^^^
  ^^^^^^
  ^^^^

## The bird-brain calculations

111111
 1^^^^111
  1^^^^11
  1^^^1
  1^^^^111111
  1^^^11
  1111

111111
 12222111
  12^^211
  12^21
  12^^2111111
  122211
  1111

111111
 12222111
  1233211
  12321
  12332111111
  122211
  1111

`Height = 3`

# Series

* Bird Mountain
* [Bird Mountain - the river](https://www.codewars.com/kata/bird-mountain-the-river)

from collections import Counter

def neigthboors(peaks):
    for x,y in peaks:
        yield x,y-1
        yield x-1,y
        yield x,y
        yield x+1,y
        yield x,y+1

def peak_height(mountain):
    mountain = [(x,y) for y,row in enumerate(mountain) for x,p in enumerate(row)  if p =="^"]
    i = 0
    while mountain:
        mountain = [x_y for x_y, cnt in list(Counter(neigthboors(mountain)).items()) if cnt == 5]
        i+=1
    return i


Solve in Python:
# Kata Task

Given a list of random integers, return the Three Amigos.

These are 3 numbers that live next to each other in the list, and who have the **most** in common with each other by these rules:
* lowest statistical range
* same parity

# Notes

* The list will contain at least 3 numbers
* If there is more than one answer then return the first one found (reading the list left to right)
* If there is no answer (e.g. no 3 adjacent numbers with same parity) then return an empty list.

# Examples

* ex1
 * Input = ```[1, 2, 34, 2, 1, 5, 3, 5, 7, 234, 2, 1]```
 * Result = ```[5,3,5]```

* ex2
 * Input = ```[2, 4, 6, 8, 10, 2, 2, 2, 1, 1, 1, 5, 3]```
 * Result = ```[2,2,2]```

* ex3
 * Input = ```[2, 4, 5, 3, 6, 3, 1, 56, 7, 6, 3, 12]```
 * Result = ```[]```

def three_amigos(numbers):
    return list(min((a for a in zip(numbers, numbers[1:], numbers[2:]) if sum(b % 2 for b in a) in [0, 3]), key = lambda x : max(x) - min(x), default = []))


Solve in Python:
# Kata Task

I have a cat and a dog.

I got them at the same time as kitten/puppy. That was `humanYears` years ago.

Return their respective ages now as [`humanYears`,`catYears`,`dogYears`]

NOTES:
* humanYears >= 1
* humanYears are whole numbers only

## Cat Years

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

## Dog Years

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

**References**

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

If you liked this Kata there is another related one here

def human_years_cat_years_dog_years(human_years):

    if human_years>=2:

        catYears = 15 + 9 + (human_years-2)*4
        dogYears = 15 + 9 + (human_years-2)*5

        return [human_years,catYears,dogYears]
    else:
         return [human_years,15,15]


Solve in Python:
# Kata Task

You are given a list of cogs in a gear train

Each element represents the number of teeth of that cog

e.g. `[100, 50, 25]` means
* 1st cog has 100 teeth
* 2nd cog has 50 teeth
* 3rd cog has 25 teeth

If the ``nth`` cog rotates clockwise at 1 RPM what is the RPM of the cogs at each end of the gear train?

**Notes**
* no two cogs share the same shaft
* return an array whose two elements are RPM of the first and last cogs respectively
* use negative numbers for anti-clockwise rotation
* for convenience `n` is zero-based
* For C and NASM coders, the returned array will be `free`'d.

---

Series:
* Cogs
* Cogs 2

def cog_RPM(cogs, n):
    sign1 = -1 if n % 2 else 1
    sign2  = 1 if (len(cogs) - n) % 2 else -1
    return [sign1 * cogs[n] / cogs[0], sign2 * cogs[n] / cogs[-1]]


Solve in Python:
# Kata Task

Connect the dots in order to make a picture!

# Notes

* There are 2-26 dots labelled  `a` `b` `c` ...
* The line char is `*`
* Use only straight lines - vertical, horizontal, or diagonals of a square
* The paper is rectangular - `\n` terminates every line
* All input is valid

# Examples

InputExpected

 a       b
 e

 d       c

 *********
 *       *
 *       *
 *********

InputExpected

    a
   e

 d     b

    c

    *
   * *
  *   *
 *     *
  *   *
   * *
    *

from string import ascii_lowercase as lu
def connect_the_dots(li):
    li = [[j for j in i] for i in li.splitlines()]

    find_char = lambda c: next(([i,k] for i,j in enumerate(li) for k,l in enumerate(j) if l==c), 0) # find next char from string/array

    lower = iter(lu)

    char, chars = find_char(next(lower)), []

    while char:
        chars.append(char)
        char = find_char(next(lower))

    A = lambda s, se, see, e, ee, eee: list(zip(list(range(s, se + 1, see)), list(range(e, ee + 1, eee)))) # for diagonals

    for h, g in zip(chars, chars[1:]):
        i, j = h ; k, l = g
        m, m1, n, n1 = min(i, k), min(j, l), max(i, k), max(j, l)
        if i == k:                      # horizontal
            while m1 <= n1 :
                li[i][m1] = '*' ; m1 += 1
        elif j == l:                    # verical
            while m <= n :
                li[m][j] = '*' ; m += 1
        else:                           # diagonals
            B,C = i > k, j > l
            for o, p in A(i, k - (2 if B else 0), (1 if not B else -1), j, l - (2 if C else 0),(1 if not C else -1)) :
                 li[o][p] = '*'
        i, j = k, l
    return "\n".join(["".join(i) for i in li])+"\n"


Solve in Python:
# Largest Rectangle in Background

Imagine a photo taken to be used in an advertisement. The background on the left of the motive is whitish and you want to write some text on that background. So you scan the photo with a high resolution scanner and, for each line, count the number of pixels from the left that are sufficiently white and suitable for being written on. Your job is to find the area of the largest text box you can place on those pixels.

Example:
In the figure below, the whitish background pixels of the scanned photo are represented by asterisks.

```
*********************************
*********
*******
******
******
******
**************
**************
**************
***************
*********************

```

If you count the pixels on each line from the left you get the list (or array, depending on which language you are using) `[33, 9, 7, 6, 6, 6, 14, 14, 14, 15, 21]`. The largest reactangle that you can place on these pixels has an area of 70, and is represented by the dots in the figure below.

```
*********************************
*********
*******
******
******
******
..............
..............
..............
..............*
..............*******
```

Write a function that, given a list of the number whitish pixels on each line in the background, returns the area of the largest rectangle that fits on that background.

def largest_rect(h):
  r,s,i,l=0,[],0,len(h)
  while i<l:
    if not s or h[s[-1]]<=h[i]: s.append(i); i+=1
    else:  t=s.pop(); a=i-s[-1]-1 if s else i; a*=h[t]; r=r if r>a else a
  while s: t=s.pop(); a=i-s[-1]-1 if s else i; a*=h[t]; r=r if r>a else a
  return r


Solve in Python:
# Leaderboard climbers

In this kata you will be given a leaderboard of unique names for example:

```python
['John',
 'Brian',
 'Jim',
 'Dave',
 'Fred']
```

Then you will be given a list of strings for example:

```python
['Dave +1', 'Fred +4', 'Brian -1']
```

Then you sort the leaderboard.

The steps for our example would be:

```python
# Dave up 1
['John',
 'Brian',
 'Dave',
 'Jim',
 'Fred']
```

```python
# Fred up 4
['Fred',
 'John',
 'Brian',
 'Dave',
 'Jim']
```

```python
# Brian down 1
['Fred',
 'John',
 'Dave',
 'Brian',
 'Jim']
```

Then once you have done this you need to return the leaderboard.

All inputs will be valid. All strings in the second list will never ask to move a name up higher or lower than possible eg. `"John +3"` could not be added to the end of the second input list in the example above.

The strings in the second list will always be something in the leaderboard followed by a space and a `+` or `-` sign followed by a number.

def leaderboard_sort(leaderboard, changes):
    leaderboard.reverse()
    for user, move in [change.split() for change in changes]:
        index = leaderboard.index(user)
        leaderboard.remove(user)
        leaderboard.insert(eval("{}{}".format(index, move)), user)
    leaderboard.reverse()
    return leaderboard


Solve in Python:
# Let's play Psychic

A box contains green, red, and blue balls. The total number of balls is given by `n` (`0 < n < 50`).

Each ball has a mass that depends on the ball color. Green balls weigh `5kg`, red balls weigh `4kg`, and blue balls weigh `3kg`.

Given the total number of balls in the box, `n`, and a total mass, `m`, your task is to craft a program that will determine the quantities of each colored ball. Return a list of these quantities as the answer.

Don't forget that some combinations of `n` and `m` may have more than one possibility!

# Examples

## Python
```python
>>> Guess_it(3, 12)
[[0,3,0], [1,1,1]]
```

## Elixir

*Note: Order of the returned elements is unimportant in the Elixir version.*

# Assumptions

1. You can assume that all inputs are of the correct type
2. You can assume that the range of `n` will be `[1, 50]`
3. Each element of the returned list should return the quantities in the order of `g`, `r`, `b`.

## Python
```python
[[green, red, blue]]
```

## Elixir

def Guess_it(N, M):
    def mass(g, r, b): return (g * 5) + (r * 4) + (b * 3)
    results = []
    for g in range(N + 1):
        for r in range((N - g) + 1):
            b = N - r - g
            if mass(g, r, b) == M:
                results.append([g, r, b])
    return results


Solve in Python:
# Let's play some games!

A new RPG called **_Demon Wars_** just came out! Imagine the surprise when you buy it after work, go home, start you _GameStation X_ and it happens to be too difficult for you. Fortunately, you consider yourself a computer connoisseur, so you want to build an AI that tells you every step you have to make to **defeat the evil Demon Lord** and win the game. For now, let's program a simulator.

This game features procedurally generated stages like this one:

  Health: ♥ ♥ ♥   Atk: 1   Def: 1   Bag: []
K   E     |    X#        C      E   S#  D
    E     #######               ###### E E
##### #####                          ###-##
     M                                 EEE
                     ###   ###
                     #       ##E##E##
     ^               #          C  K#
               C      #   H   ##E##E##

As you can see in the upper status bar, your player starts with **three Health Points**, **1 Attack**, **1 Defense** and an empty **Bag**. These are the only stats that you have to care about for the game. As for the map, we can see many different things, so let's explain every tile one by one:
* `^` or `v` or `<` or `>` => **Player** (you). It can face any of four directions.
* `#` => **Wall**. You cannot pass through here.
* `C` => **Coin _[object]_**.
* `M` => **Merchant**. They will go away if you give them **three coins**.
* `K` => **Key _[object]_**. They can open a door, after which they break _(yes, like in horror games)_.
* `-` and `|` => **Doors** _(there are two doors in the map above)_.
* `H` => **Health Potion _[object]_**. It refuels your life to three hearts.
* `S` => **Shield**. It gives **+1 defense** permanently.
* `X` => **Dual Swords**. It gives **+1 attack** permanently.
* `E` => **Enemy**. Has **1 Health Point** and **2 Attack**.
* `D` => **Demon Lord**. Has **10 Health Points** and **3 Attack**. You win the game if you kill him.

Now, _Demon Wars_ is a turn based game with tank controls. Each turn you can...

# only_show_wrong()
dir_dict = {'^': (-1, 0), 'v': (1, 0), '<': (0, -1), '>': (0, 1)}

def rpg(field, actions):
    width, height = len(field[0]), len(field)
    field, actions = [list(line) for line in field], list(actions)

    found = False
    for row in range(height):
        if found: break
        for col in range(width):
            if field[row][col] in dir_dict:
                player_loc = (row, col)
                player_dir = field[row][col]
                target_loc = (row + dir_dict[player_dir][0], col + dir_dict[player_dir][1])
                found = True
                break

    hlh, atk, des, bag = 3, 1, 1, []
    mer_dict = {}
    enemy_count, dl_hlh = 0, 10

    for action in actions:
        if action not in dir_dict:
            if target_loc[0] < 0 or target_loc[0] >= height or target_loc[1] < 0 or target_loc[1] >= width: return None
            target_tile = field[target_loc[0]][target_loc[1]]

        if action == 'C':
            if target_tile != 'M': return None
            if action not in bag: return None
            bag.remove(action)
            if target_loc not in mer_dict: mer_dict[target_loc] = 2
            else:
                mer_dict[target_loc] = mer_dict[target_loc] - 1
                if mer_dict[target_loc] == 0: field[target_loc[0]][target_loc[1]] = ' '

        elif action == 'K':
            if target_tile not in '-|': return None
            if action not in bag: return None
            bag.remove(action)
            field[target_loc[0]][target_loc[1]] = ' '

        else:
            # enemy will attack!
            if action == 'F':
                if target_tile in ['C', 'K', 'H']:
                    bag.append(target_tile)
                    bag.sort()
                elif target_tile == 'S': des = des + 1
                elif target_tile == 'X': atk = atk + 1
                elif target_tile != ' ': return None
                field[target_loc[0]][target_loc[1]] = player_dir
                field[player_loc[0]][player_loc[1]] = ' '
            elif...


Solve in Python:
# Let's watch a parade!
## Brief
You're going to watch a parade, but you only care about one of the groups marching. The parade passes through the street where your house is. Your house is at number `location` of the street. Write a function `parade_time` that will tell you the times when you need to appear to see all appearences of that group.

## Specifications
You'll be given:

* A `list` of `string`s containing `groups` in the parade, in order of appearance. A group may appear multiple times. You want to see all the parts of your favorite group.
* An positive `integer` with the `location` on the parade route where you'll be watching.
* An positive `integer` with the `speed` of the parade
* A `string` with the `pref`ferred group you'd like to see

You need to return the time(s) you need to be at the parade to see your favorite group as a `list` of `integer`s.

It's possible the group won't be at your `location` at an exact `time`. In that case, just be sure to get there right before it passes (i.e. the largest integer `time` before the float passes the `position`).

## Example
```python
groups = ['A','B','C','D','E','F']
location = 3
speed = 2
pref = 'C'
                  v
Locations: |0|1|2|3|4|5|6|7|8|9|...
F E D C B A      | |               time = 0
> > F E D C B A  | |               time = 1
    > > F E D C B|A|               time = 2
        > > F E D|C|B A            time = 3
                  ^
parade_time(['A','B','C','D','E','F'], 3, 2,'C']) == [3]
```

def parade_time(groups, location, speed, pref):
    return [(location + i) // speed for i, g in enumerate(groups, 1) if g == pref]


Solve in Python:
# Letterss of Natac
In a game I just made up that doesn’t have anything to do with any other game that you may or may not have played, you collect resources on each turn and then use those resources to build settlements, roads, and cities or buy a development. Other kata about this game can be found [here](https://www.codewars.com/collections/59e6938afc3c49005900011f).

## Task
This kata asks you to implement the function `build_or_buy(hand)` , which takes as input a `hand`, the resources you have (a string of letters representing the resources you have), and returns a list of the unique game objects you can build or buy given your hand.

There are five different resources, `'b'`, `'w'`, `'g'`, `'s'`, and `'o'`.

Game objects and the resources required to build or buy them are as follows:
1. `'road'`: `bw`
2. `'settlement'`: `bwsg`
3. `'city'`: `ooogg`
4. `'development'`: `osg`

## Examples
```python
build_or_buy("bwoo")  => ['road']
build_or_buy("bwsg")  => ['road', 'settlement'] or ['settlement', 'road']
build_or_buy("")      => []
build_or_buy("ogogoogogo")  => ['city']

```

## Notes:
1. Don't mutate the hand
2. The order of the returned list doesn't matter
3. You do not have to test for whether a hand is valid.
4. The list will be interpreted to mean 'you can build any of these objects,' not 'you can build all these objects in one play'. See example 2 above, even though there is only one `'b'` and one `'w'` in `hand`, both `Road()` and `Settlement()` are in the list.
5. A hand can be empty. In the event a hand is empty, you can't build or buy anything, so return an empty list, see example 3 above.
6. Hand are between 0 and 39 in length.

from collections import Counter

REQUIRE = {x: Counter(s) for x,s in [('road', 'bw'), ('settlement', 'bwsg'), ('city', 'ooogg'), ('development', 'osg')] }

def build_or_buy(hand):
    h = Counter(hand)
    return [item for item,c in REQUIRE.items() if not c-h]


Solve in Python:
# Letterss of Natac
In a game I just made up that doesn’t have anything to do with any other game that you may or may not have played, you collect resources on each turn and then use those resources to build things like roads, settlements and cities. If you would like to try other kata about this game, they can be found **[here](https://www.codewars.com/collections/59e6938afc3c49005900011f)**

## Task

This kata asks you to implement a time efficient version of the function `play_if_enough(hand, play)` , which takes as input a `hand`, the resources you have (a string of letters representing the resources you have), and a `play`, (a string of letters representing the resources required to build a certain game object), and returns a tuple (list in r) of a boolean value, corresponding to whether you have enough resources, and your hand. If you had enough to build the object, the returned hand is your resources minus those you used to build the object. If not, it is your original hand (the one passed to the function).

For example, if it takes 3 ore and 2 grain to build a city, `play` is `”ooogg”`. If `hand` is `”ooooogggssbbb”`, then `play_if_enough(hand, play)` returns `(True, “oogssbbb”)`.

## Examples
```python
play_if_enough("ooooogggssbbb", "ooogg")  => (True, "oogssbbb")
play_if_enough("oogssbbb", "bwsg")        => (False, "oogssbbb")
play_if_enough("", "bw")                  => (False, "")
play_if_enough("abcdefghij", "aa")        => (False, "abcdefghij")

```
## Notes:
1. The order of resources in your hand (or play) is not relevant. You can shuffle your hand any way you'd like, so long as you have the same number of each resource.
2. There are 26 different resources, each represented by a lower case letter a-z, so a valid hand is a string of lower case letters.
3. A valid play is a string of any number of lower case letters.
4. You do not have to test for whether a hand or play is valid.
5. A hand can be empty, but a play can't. In the event a hand is empty, you don't have the cards to play, so...

from collections import Counter

def play_if_enough(hand, play):
    h = Counter(hand)
    p = Counter(play)
    if p&h == p:
        h.subtract(p)
        return (True, "".join(h.elements()))
    return (False, hand)


Solve in Python:
# Longest Palindromic Substring (Linear)

A palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g.,
'madam' or 'racecar'. Even the letter 'x' is considered a palindrome.

For this Kata, you are given a string ```s```. Write a function that returns the longest _contiguous_ palindromic substring in ```s``` (it could be the entire string). In the event that there are multiple longest palindromic substrings, return the first to occur.

I'm not trying to trick you here:
- You can assume that all inputs are valid strings.
- Only the letters a-z will be used, all lowercase (your solution should, in theory, extend to more than just the letters a-z though).

**NOTE:** Quadratic asymptotic complexity _(O(N^2))_ or above will __NOT__ work here.

-----

## Examples

### Basic Tests

```
Input: "babad"
Output: "bab"
(Note: "bab" occurs before "aba")
```
```
Input: "abababa"
Output: "abababa"
```
```
Input: "cbbd"
Output: "bb"
```

### Edge Cases

```
Input: "ab"
Output: "a"
```
```
Input: ""
Output: ""
```
-----

## Testing

Along with the example tests given:

 - There are **500** tests using strings of length in range [1 - 1,000]
 - There are **50** tests using strings of length in range [1,000 - 10,000]
 - There are **5** tests using strings of length in range [10,000 - 100,000]

All test cases can be passed within 10 seconds, but non-linear solutions will time out every time. _Linear performance is essential_.

## Good Luck!

-----

This problem was inspired by [this](https://leetcode.com/problems/longest-palindromic-substring/) challenge on LeetCode. Except this is the performance version :^)

def longest_palindrome(s):
    n = len(s)
    if n <= 1:
        return s
    max, index = 0,  -1
    max2, index2 = 0, -1
    d1 = [0]*n
    i, l, r = 0, 0, -1
    while i < n:
        if i > r:
            k = 1
        else:
            k = min(d1[l + r - i], r - i + 1)
        while 0 <= i - k and i + k < n and s[i - k] == s[i + k]:
            k += 1
        if k > max:
            max, index = k, i  # s[i-k+1:i+k], 2k-1
        d1[i] = k
        k -= 1
        if i + k > r:
            l, r = i - k, i + k
        i += 1

    d2 = [0]*n
    i, l, r = 0, 0, -1
    while i < n:
        if i > r:
            k = 0
        else:
            k = min(d2[l + r - i + 1], r - i + 1)
        while 0 <= i - k - 1 and i + k < n and s[i - k - 1] == s[i + k]:
            k += 1
        if k > max2:
            max2, index2 = k, i  # s[i-k:i+k], 2k
        d2[i] = k
        k -= 1
        if i + k > r:
            l, r = i - k - 1, i + k
        i += 1

    index = index - max + 1  # start
    max = 2 * max - 1        # len
    index2 -= max2           # start
    max2 *= 2                # len
    start, ln = 0, 0
    if max == max2:
        if index <= index2:
            start, ln = index, max
        else:
            start, ln = index2, max2
    elif max > max2:
        start, ln = index, max
    else:
        start, ln = index2, max2
    return s[start: start + ln]


Solve in Python:
# MOD 256 without the MOD operator

The MOD-operator % (aka mod/modulus/remainder):
```
Returns the remainder of a division operation.
The sign of the result is the same as the sign of the first operand.
(Different behavior in Python!)
```

The short unbelievable mad story for this kata:
I wrote a program and needed the remainder of the division by 256. And then it happened: The "5"/"%"-Key did not react. It must be broken! So I needed a way to:
```
Calculate the remainder of the division by 256 without the %-operator.
```

Also here some examples:
```
Input 254  -> Result 254
Input 256  -> Result 0
Input 258  -> Result 2
Input -258 -> Result -2 (in Python: Result: 254!)
```
It is always expected the behavior of the MOD-Operator of the language!

The input number will always between -10000 and 10000.

For some languages the %-operator will be blocked. If it is not blocked and you know how to block it, tell me and I will include it.

For all, who say, this would be a duplicate: No, this is no duplicate! There are two katas, in that you have to write a general method for MOD without %. But this kata is only for MOD 256. And so you can create also other specialized solutions. ;-)

Of course you can use the digit "5" in your solution. :-)

I'm very curious for your solutions and the way you solve it. I found several interesting "funny" ways.

Have fun coding it and please don't forget to vote and rank this kata! :-)

I have also created other katas. Take a look if you enjoyed this kata!

def mod256_without_mod(number):
    return number.__mod__(256)


Solve in Python:
# Magpies are my favourite birds

Baby ones even more so...

It is a little known fact^ that the black & white colours of baby magpies differ by **at least** one place and **at most** two places from the colours of the mother magpie.

So now you can work out if any two magpies may be related.

*...and Quardle oodle ardle wardle doodle the magpies said*

# Kata Task

Given the colours of two magpies, determine if one is a possible **child** or **grand-child** of the other.

# Notes

* Each pair of birds being compared will have same number of colour areas
* `B` = Black
* `W` = White

# Example

Given these three magpies

Magpie 1  BWBWBW
Magpie 2  BWBWBB
Magpie 3  WWWWBB

You can see:
* Magpie 2 may be a child of Magpie 1 because there is only one difference
* Magpie 3 may be child of Magpie 2 because there are two differences
* So Magpie 3 may be a grand-child of Magpie 1
* On the other hand, Magpie 3 cannot be a child of Magpie 1 because there are three differences

---

DM :-)

^ *This fact is little known because I just made it up*

from itertools import product

def child(bird1, bird2):
    return sum([b[0] != b[1] for b in zip(bird1, bird2)]) in (1, 2)

def grandchild(bird1, bird2):
    for mother in product("BW", repeat=len(bird1)):
        # check if both birds are related to the 'created' mother magpie
        if child(bird1, mother) and child(bird2, mother):
            return True
    return False


Solve in Python:
# Making Change

Complete the method that will determine the minimum number of coins needed to make change for a given amount in American currency.

Coins used will be half-dollars, quarters, dimes, nickels, and pennies, worth 50¢, 25¢, 10¢, 5¢ and 1¢, respectively. They'll be represented by the symbols `H`, `Q`, `D`, `N` and `P` (symbols in Ruby, strings in in other languages)

The argument passed in will be an integer representing the value in cents. The return value should be a hash/dictionary/object with the symbols as keys, and the numbers of coins as values. Coins that are not used should not be included in the hash. If the argument passed in is 0, then the method should return an empty hash.

## Examples

```python
make_change(0)   #-->  {}
make_change(1)   #-->  {"P":1}
make_change(43)  #-->  {"Q":1, "D":1, "N":1, "P":3}
make_change(91)  #-->  {"H":1, "Q":1, "D":1, "N":1, "P":1}
```

#### **If you liked this kata, check out [Part 2](https://www.codewars.com/kata/making-change-part-2/ruby).**

BASE = {"H": 50, "Q": 25, "D": 10, "N": 5, "P": 1}

def make_change(n):
    r = {}
    for x, y in BASE.items():
        if n >= y:
            r[x], n = divmod(n, y)
    return r


Solve in Python:
# Messi goals function

[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:

- LaLiga
- Copa del Rey
- Champions

Complete the function to return his total number of goals in all three leagues.

Note: the input will always be valid.

For example:

```
5, 10, 2  -->  17
```

def goals(laLiga: int, copaDelRey: int, championsLeague: int) -> int:
    return sum((laLiga, copaDelRey, championsLeague))


Solve in Python:
# Number encrypting: cypher
## Part I of Number encrypting Katas
***

## Introduction
Back then when the internet was coming up, most search functionalities simply looked for keywords in text to show relevant documents. Hackers weren't very keen on having their information displayed on websites, bulletin boards, newsgroups or any other place, so they started to replace certain letters in words. It started out with simple vowel substitutions like a 4 instead of an A, or a 3 instead of an E. This meant that topics like cracking or hacking remained undetected.

Here we will use a reduced version of the *Leet Speak alphabet*, but you can find more information [here](http://www.gamehouse.com/blog/leet-speak-cheat-sheet/) or at [Wikipedia](https://en.wikipedia.org/wiki/Leet).

## Task
You will receive a string composed by English words, `string`. You will have to return a cyphered version of that string.

The numbers corresponding to each letter are represented at the table below. Notice that different letters can share the same number. In those cases, one letter will be upper case and the other one lower case.

  .cell {
    border: 1px solid white;
    text-align: center;
    width: 7%;
  }

  .title {
    border: 1px solid white;
    border-bottom: 1px solid white;
    text-align: center;
    min-width: 11em;
  }

  .no-border {border: none}

  table {
    margin-bottom: 10px
  }

    1
    2
    3
    4
    5
    6
    7
    8
    9
    0

    Upper case
    I
    R
    E
    A
    S
    G
    T
    B

    O

    Lower case
    l
    z
    e
    a
    s
    b
    t

    g
    o

Any character that is not at the table, does not change when cyphered.

## Examples

  * **Input:** "Hello World". **Output**: "H3110 W0r1d"
  * **Input:** "I am your father". **Output**: "1 4m y0ur f47h3r"
  * **Input:** "I do not know what else I can test. Be cool. Good luck". **Output**: "1 d0 n07 kn0w wh47 3153 1 c4n 7357. 83 c001. 600d 1uck"

## Part II
If you liked this Kata, you can find...

def cypher(string):
    return string.translate(string.maketrans("IREASGTB0lzeasbtgOo", "1234567801234567900"))


Solve in Python:
# One is the loneliest number

## Task

The range of vision of a digit is its own value. `1` can see one digit to the left and one digit to the right,` 2` can see two digits, and so on.

Thus, the loneliness of a digit `N` is the sum of the digits which it can see.

Given a non-negative integer, your funtion must determine if there's at least one digit `1` in this integer such that its loneliness value is minimal.

## Example

```
number = 34315
```

digit | can see on the left | can see on the right | loneliness
--- | --- | --- | ---
3 | - | 431 | 4 + 3 + 1 = 8
4 | 3 | 315 | 3 + 3 + 1 + 5 = 12
3 | 34 | 15 | 3 + 4 + 1 + 5 = 13
1 | 3 | 5 | 3 + 5 = 8
5 | 3431 | - | 3 + 4 + 3 + 1 = 11

Is there a `1` for which the loneliness is minimal? Yes.

def loneliest(number):
    numbers = [int(c) for c in str(number)]
    loneliness = [(n, sum(numbers[max(i-n, 0):i]) + sum(numbers[i+1:i+1+n])) for i, n in enumerate(numbers)]
    onesLoneliness = [p[1] for p in loneliness if p[0] == 1]
    if (not onesLoneliness) : return False
    otherLoneliness = [p[1] for p in loneliness if not p[0] == 1]
    if (not otherLoneliness): return True
    return min(otherLoneliness) >= min(onesLoneliness)


Solve in Python:
# Our Setup

Alice and Bob work in an office. When the workload is light and the boss isn't looking, they often play simple word games for fun. This is one of those days!

# This Game

Today Alice and Bob are playing what they like to call _Mutations_, where they take turns trying to "think up" a new four-letter word identical to the prior word except for one letter. They just keep on going until their memories fail out.

# Their Words

Alice and Bob have memories of the same size, each able to recall `10` to `2000` different four-letter words. Memory words and initial game word are randomly taken from a list of `4000` (unique, four-letter, lowercased) words, any of which may appear in both memories.

The expression to "think up" a new word means that for their turn, the player must submit as their response word the first valid, unused word that appears in their memory (by lowest array index), as their memories are ordered from the most "memorable" words to the least.

# The Rules
* a valid response word must contain four different letters
* `1` letter is replaced while the other `3` stay in position
* it must be the lowest indexed valid word in their memory
* this word cannot have already been used during the game
* the final player to provide a valid word will win the game
* if 1st player fails 1st turn, 2nd can win with a valid word
* when both players fail the initial word, there is no winner

# Your Task
To determine the winner!

# Some Examples

`alice = plat,rend,bear,soar,mare,pare,flap,neat,clan,pore`

`bob   = boar,clap,farm,lend,near,peat,pure,more,plan,soap`

1) In the case of `word = "send"` and `first = 0`:
* Alice responds to `send` with `rend`
* Bob   responds to `rend` with `lend`
* Alice has no valid response to `lend`
* Bob   wins the game.

2) In the case of `word = "flip"` and `first = 1`:
* Bob   has no valid response to `flip`
* Alice responds to `flip` with `flap`
* Alice wins the game.

3) In the case of `word = "maze"` and `first = 0`:
* Alice responds to `maze` with `mare`
* Bob  ...

def mutations(alice, bob, word, first):
    seen = {word}
    mapping = {0:alice, 1:bob}
    prev_state,state = -1, -1

    def foo(word,first):
        nonlocal state, prev_state
        foo.counter += 1

        if foo.counter > 2 and (state < 0 or prev_state < 0):
            return

        for a_word in mapping[first]:
            counter = 0
            for i,x in enumerate(a_word):
                if a_word[i] == word[i]:
                    counter += 1

            if counter == 3 and len(set(a_word))==4 and a_word not in seen:
                seen.add(a_word)
                prev_state = state
                state = first
                word = a_word
                break

        if counter==3 or state < 0:
            return foo(word,first^1)

    foo.counter = 0
    foo(word,first)
    return state


Solve in Python:
# Overview

The goal here is to solve a puzzle (the "pieces of paper" kind of puzzle). You will receive different pieces of that puzzle as input, and you will have to find in what order you have to rearrange them so that the "picture" of the puzzle is complete.

## Puzzle pieces

All the pieces of the puzzle will be represented in the following way:

* 4 numbers, grouped in 2 tuples, which are representing the "picture" on the piece. Every piece has a 2x2 size.
* 1 id number. All id numbers are unique in a puzzle, but their value may be random.
* Note that all numbers will be non-negative integers (except for outer border "picture" numbers in C#)

For example,

    ((1, 2), (3, 4), 1)
     Puzzle piece id ^

is equivalent the the following square piece of puzzle, having the id number `1`:

    +---+
    |1 2|
    |3 4|
    +---+

If the piece is on a border or is a corner, some numbers will be replaced with `None` (`-1` in C#):
```python
((None, None), (1, 2), 10)       -->   upper border
((9, None), (None, None), 11)   -->   bottom right corner
```

Note that you cannot flip or rotate the pieces (_would you like to change the picture!?_)

## Solving the puzzle

* You'll get an array of pieces as well as the size of the puzzle (width and height).
* Two pieces can be assembled if they share the same pattern on the border where they are in contact (see example below).
* Puzzle pieces being unique, you'll never encounter two different pieces that could be assembled with the same third one. So to say: borders are unique.
* Once you found the proper arrangment for all the pieces, return the solved puzzle as a list of tuples (height * width) of the id number of the piece at its correct position. (For C#, return the solved puzzle as a 2-dimensional array of integers.)

## Example:

Inputs:

```python
width, height = 3,3
pieces = [ ((None, 5), (None, None), 3),
           ((17, None), (None, None), 9),
           ((None, 4), (None, 5), 8),
           ((4, 11), (5, 17), 5),
          ...

def puzzle_solver(li, width, height):

    # save pieces of puzzle for later use
    id_number = {i[:2]: i[2] for i in li}
    li, puzzle = list(id_number.keys()), [[() for _ in range(width)] for _ in range(height)]
    left, right, top, bottom, rest = [], [], [], [], []

    # set fixed corners and store sub grid to their correct place
    for grid in li:
        nones, nn = sum(i.count(None) for i in grid), (None, None)
        if nones == 3:
            x, y = [(-1, -1), (-1, 0), (0, -1), (0, 0)][next(i for i, j in enumerate(sum(grid, ())) if j is not None)]
            puzzle[x][y] = grid
        elif nones == 2:
            use = bottom if grid[1] == nn else top if grid[0] == nn else left if (grid[0][0], grid[1][0]) == nn else right
            use.append(grid)
        else:
            rest.append(grid)

    # function to set all sidelines
    def set_row(line, start, i, j, o, p, till):
        lookup = {k[o][p]: k for k in line}
        decide = lambda x: {(1, 1, 1, 0): (0, x), (0, 1, 0, 0): (-1, x), (1, 1, 0, 1): (x, 0)}.get((i, j, o, p), (x, -1))

        for k in range(1, till - 1):
            x, y = decide(k)
            puzzle[x][y] = lookup[start[i][j]]
            start = puzzle[x][y]

    # set all side lines
    for line, start, i, j, o, p, till in [(top, puzzle[0][0], 1, 1, 1, 0, width),
                                          (bottom, puzzle[-1][0], 0, 1, 0, 0, width),
                                          (left, puzzle[0][0], 1, 1, 0, 1, height),
                                          (right, puzzle[0][-1], 1, 0, 0, 0, height)]:
        set_row(line, start, i, j, o, p, till)

    #now, all easy set rest of puzzle
    prev = puzzle[0]
    lookup = {k[0]: k for k in rest}
    for k in range(1, height - 1):
        for l in range(1, width - 1):
            puzzle[k][l] = lookup[prev[l][1]]
        prev = puzzle[k]

    return [tuple([id_number[j] for j in i]) for i in puzzle]


Solve in Python:
# Palindrome strings

A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward. This includes capital letters, punctuation, and word dividers.

Implement a function that checks if something is a palindrome.

## Examples
```
isPalindrome("anna")   ==> true
isPalindrome("walter") ==> false
isPalindrome(12321)    ==> true
isPalindrome(123456)   ==> false
```

def is_palindrome(string: str) -> bool:
    return str(string) == str(string)[::-1]


Solve in Python:
# Personalized greeting

Create a function that gives a personalized greeting. This function takes two parameters: `name` and `owner`.

Use conditionals to return the proper message:

case | return
--- | ---
name equals owner | 'Hello boss'
otherwise         | 'Hello guest'

def greet(name, owner):
    if name == owner:
        result = "boss"
    else:
        result = "guest"
    return "Hello " + result
    # Add code here


Solve in Python:
# Problem

In China，there is an ancient mathematical book, called "The Mathematical Classic of Sun Zi"(《孙子算经》). In the book, there is a classic math problem: “今有物不知其数，三三数之剩二，五五数之剩三，七七数之剩二，问物几何？”

Ahh, Sorry. I forgot that you don't know Chinese. Let's translate it to English:

There is a unkown positive integer `n`. We know:

`n % 3 = 2`, and `n % 5 = 3`, and `n % 7 = 2`.

What's the minimum possible positive integer `n`?

The correct answer is `23`.

# Task

You are given three non-negative integers `x,y,z`. They represent the remainders of the unknown positive integer `n` divided by 3,5,7.

That is: `n % 3 = x, n % 5 = y, n % 7 = z`

Your task is to find the minimum possible positive integer `n` and return it.

# Example

For `x = 2, y = 3, z = 2`, the output should be `23`

`23 % 3 = 2, 23 % 5 = 3, 23 % 7 = 2`

For `x = 1, y = 2, z = 3`, the output should be `52`

`52 % 3 = 1, 52 % 5 = 2, 52 % 7 = 3`

For `x = 1, y = 3, z = 5`, the output should be `103`

`103 % 3 = 1, 103 % 5 = 3, 103 % 7 = 5`

For `x = 0, y = 0, z = 0`, the output should be `105`

For `x = 1, y = 1, z = 1`, the output should be `1`

# Note

- `0 <= x < 3, 0 <= y < 5, 0 <= z < 7`

- Happy Coding `^_^`

find_unknown_number = lambda *a: next(i for i in __import__("itertools").count(1) if all(i % x == a[j] for j, x in enumerate((3, 5, 7))))


Solve in Python:
# Problem Description

Let's imagine a function `F(n)`, which is defined over the integers
in the range of `1 <= n <= max_n`, and `0 <= F(n) <= max_fn` for every `n`.

There are `(1 + max_fn) ** max_n` possible definitions of `F` in total.

Out of those definitions, how many `F`s satisfy the following equations?
Since your answer will be very large, please give your answer **modulo 12345787**.

* `F(n) + F(n + 1) <= max_fn` for `1 <= n < max_n`
* `F(max_n) + F(1) <= max_fn`

# Constraints

`1 <= max_n <= 100`

`1 <= max_fn <= 5`

The inputs will be always valid integers.

# Examples

```python
# F(1) + F(1) <= 1, F(1) = 0
circular_limited_sums(1, 1) == 1

# F = (0, 0), (0, 1), (1, 0)
circular_limited_sums(2, 1) == 3

# F = (0, 0, 0), (0, 0, 1), (0, 1, 0), (1, 0, 0)
circular_limited_sums(3, 1) == 4

# F = (0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 1, 0, 0),
# (0, 1, 0, 1), (1, 0, 0, 0), (1, 0, 1, 0)
circular_limited_sums(4, 1) == 7

# F = (0), (1)
circular_limited_sums(1, 2) == 2
# F = (0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (2, 0)
circular_limited_sums(2, 2) == 6
# F = (0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1),
# (0, 2, 0), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1), (2, 0, 0)
circular_limited_sums(3, 2) == 11
circular_limited_sums(4, 2) == 26
```

# Acknowledgement

This problem was designed as a hybrid of [Project Euler #209: Circular Logic](https://projecteuler.net/problem=209) and [Project Euler #164: Numbers for which no three consecutive digits have a sum greater than a given value](https://projecteuler.net/problem=164).

If you enjoyed this Kata, please also have a look at [my other Katas](https://www.codewars.com/users/Bubbler/authored)!

# https://www.python-course.eu/python3_memoization.php
class Memoize:
    def __init__(self, fn):
        self.fn = fn
        self.memo = {}
    def __call__(self, *args):
        if args not in self.memo:
            self.memo[args] = self.fn(*args)
        return self.memo[args]

@Memoize
def linear_limited_sums(X,Y,head,tail):
    if X == 1:
        return 1 if head == tail else 0
    if X == 2:
        return 1 if head + tail <= Y else 0
    return sum(linear_limited_sums(X-1,Y,head,T) for T in range(Y-tail+1))%12345787

def circular_limited_sums(X,Y):
    return sum(linear_limited_sums(X,Y,head,tail) for head in range(Y+1) for tail in range(Y-head+1))%12345787


Solve in Python:
# Problem Statement
Write a function that takes two string parameters, an IP (v4) address and a subnet mask, and returns two strings: the network block, and the host identifier.

The function does not need to support CIDR notation.

# Description
A single IP address with subnet mask actually specifies several addresses: a network block, and a host identifier, and a broadcast address. These addresses can be calculated using a bitwise AND operation on each bit.

(The broadcast address is not used in this kata.)

## Example
A computer on a simple home network might have the following IP and subnet mask:
```
IP: 192.168.2.1
Subnet: 255.255.255.0
(CIDR Notation: 192.168.2.1 /24)
```
In this example, the network block is: **192.168.2.0**. And the host identifier is: **0.0.0.1**.

## bitwise AND
To calculate the network block and host identifier the bits in each octet are ANDed together. When the result of the AND operation is '1', the bit specifies a network address (instead of a host address).

To compare the first octet in our example above, convert both the numbers to binary and perform an AND operation on each bit:
```
11000000 (192 in binary)
11111111 (255 in binary)
--------------------------- (AND each bit)
11000000 (192 in binary)
```
So in the first octet, '**192**' is part of the network address. The host identifier is simply '**0**'.

For more information see the [Subnetwork](http://en.wikipedia.org/wiki/Subnetwork) article on Wikipedia.

def ipv4__parser(addr, mask):
    return tuple(".".join(str(n) for n in a) for a in zip(*(((a & m), (a & ~m)) for a, m in zip((int(n) for n in addr.split(".")), (int(n) for n in mask.split("."))))))


Solve in Python:
# Pythagorean Triples

A Pythagorean triplet is a set of three numbers a, b, and c where `a^2 + b^2 = c^2`. In this Kata, you will be tasked with finding the Pythagorean triplets whose product is equal to `n`, the given argument to the function `pythagorean_triplet`.

## Your task

In this Kata, you will be tasked with finding the Pythagorean triplets whose product is equal to `n`, the given argument to the function, where `0 < n < 10000000`

## Examples

One such triple is `3, 4, 5`. For this challenge, you would be given the value `60` as the argument to your function, and then it would return the Pythagorean triplet in an array `[3, 4, 5]` which is returned in increasing order. `3^2 + 4^2 = 5^2` since `9 + 16 = 25` and then their product (`3 * 4 * 5`) is `60`.

More examples:

| **argument** | **returns** |
| ---------|---------|
| 60       | [3, 4, 5] |
| 780      | [5, 12, 13] |
| 2040     | [8, 15, 17] |


Solve in Python:
# RegExp Fun #1 - When I miss few days of gym

## Disclaimer

The background story of this Kata is 100% fiction.  Any resemblance to real people or real events is **nothing more than a coincidence** and should be regarded as such.

## Background Story

You are a person who loves to go to the gym everyday with the squad of people that you've known since early childhood.  However, you recently contracted a sickness that forced you to stay at home for over a week.  As you see your body getting weaker and weaker every day and as you see your biceps and triceps disappearing, you can't help but lay in bed and cry.  You're usually an optimistic person but this time negative thoughts come to your head ...

![When I miss few days of gym](https://pics.onsizzle.com/Instagram-faf8c9.png)

## Task

As can be seen from the funny image above (or am I the only person to find the picture above hilarious?) there is lots of slang.  Your task is to define a function ```gymSlang``` which accepts a string argument and does the following:

1. Replace *all* instances of ```"probably"``` to ```"prolly"```
2. Replace *all* instances of ```"i am"``` to ```"i'm"```
3. Replace *all* instances of ```"instagram"``` to ```"insta"```
4. Replace *all* instances of ```"do not"``` to ```"don't"```
5. Replace *all* instances of ```"going to"``` to ```"gonna"```
6. Replace *all* instances of ```"combination"``` to ```"combo"```

Your replacement regexes **should be case-sensitive**, only replacing the words above with slang if the detected pattern is in **lowercase**.  However, please note that apart from 100% lowercase matches, you will **also have to replace matches that are correctly capitalized** (e.g. ```"Probably" => "Prolly"``` or ```"Instagram" => "Insta"```).

Finally, your code will be tested to make sure that you have used **RegExp** replace in your code.

Enjoy :D

import re
r = re.findall(r"\"(\w)(.*?)\".*?\"\w(.*?)\"", """
    Replace all instances of "probably" to "prolly"
    Replace all instances of "i am" to "i'm"
    Replace all instances of "instagram" to "insta"
    Replace all instances of "do not" to "don't"
    Replace all instances of "going to" to "gonna"
    Replace all instances of "combination" to "combo"
    """)

def gym_slang(s):
    for a, b, c in r: s = re.sub("(?<=[%s%s])%s" % (a, a.upper(), b), c, s)
    return s


Solve in Python:
# Remove Duplicates

You are to write a function called `unique` that takes an array of integers and returns the array with duplicates removed. It must return the values in the same order as first seen in the given array. Thus no sorting should be done, if 52 appears before 10 in the given array then it should also be that 52 appears before 10 in the returned array.

## Assumptions

* All values given are integers (they can be positive or negative).
* You are given an array but it may be empty.
* They array may have duplicates or it may not.

## Example

```python
print unique([1, 5, 2, 0, 2, -3, 1, 10])
[1, 5, 2, 0, -3, 10]

print unique([])
[]

print unique([5, 2, 1, 3])
[5, 2, 1, 3]
```

def unique(integers):
    return sorted(set(integers), key=integers.index)


Solve in Python:
# Right in the Center

_This is inspired by one of Nick Parlante's exercises on the [CodingBat](https://codingbat.com/java) online code practice tool._

Given a sequence of characters, does `"abc"` appear in the CENTER of the sequence?

The sequence of characters could contain more than one `"abc"`.

To define CENTER, the number of characters in the sequence to the left and right of the "abc" (which is in the middle) must differ by at most one.

If it is in the CENTER, return `True`. Otherwise, return `False`.

Write a function as the solution for this problem. This kata looks simple, but it might not be easy.

## Example

    is_in_middle("AAabcBB")  ->  True
    is_in_middle("AabcBB")   ->  True
    is_in_middle("AabcBBB")  ->  False

def is_in_middle(s):
    return 'abc' in s[(len(s)-1)//2-1 : (len(s)+2)//2+1]


Solve in Python:
# RoboScript #1 - Implement Syntax Highlighting

## Disclaimer

The story presented in this Kata Series is purely fictional; any resemblance to actual programming languages, products, organisations or people should be treated as purely coincidental.

## About this Kata Series

This Kata Series is based on a fictional story about a computer scientist and engineer who owns a firm that sells a toy robot called MyRobot which can interpret its own (esoteric) programming language called RoboScript.  Naturally, this Kata Series deals with the software side of things (I'm afraid Codewars cannot test your ability to build a physical robot!).

## Story

You are a computer scientist and engineer who has recently founded a firm which sells a toy product called MyRobot which can move by receiving a set of instructions by reading a file containing a script.  Initially you have planned the robot to be able to interpret JavaScript files for its movement instructions but you later decided that it would make MyRobot too hard to operate for most customers out there who aren't even computer programmers in the first place.  For this reason, you have decided to invent a new (esoteric) scripting language called RoboScript which has a much simpler syntax so non-computer programmers can easily learn how to write scripts in this language which would enable them to properly operate MyRobot.  However, you are currently at the initial stage of inventing this new Esolang.  The first step to popularize this (esoteric) scripting language is naturally to invent a new editor for it which provides syntax highlighting for this language so your customers feel like they are writing a proper program when they are writing scripts for MyRobot.

## Task

Your MyRobot-specific (esoteric) scripting language called RoboScript only ever contains the following characters: `F`, `L`, `R`, the digits `0-9` and brackets (`(` and `)`).  Your goal is to write a function `highlight` which accepts 1 required argument `code` which is the RoboScript program passed...

import re

def highlight(code):
    patterns = {
        'F': 'pink',
        'L': 'red',
        'R': 'green',
        '0-9': 'orange',
    }
    new_string = code
    for pattern, color in patterns.items():
        _pattern = re.compile(r'([{}]+)'.format(pattern))
        new_string = _pattern.sub(r'\1'.format(color), new_string)
    return new_string


Solve in Python:
# RoboScript #2 - Implement the RS1 Specification

## Disclaimer

The story presented in this Kata Series is purely fictional; any resemblance to actual programming languages, products, organisations or people should be treated as purely coincidental.

## About this Kata Series

This Kata Series is based on a fictional story about a computer scientist and engineer who owns a firm that sells a toy robot called MyRobot which can interpret its own (esoteric) programming language called RoboScript.  Naturally, this Kata Series deals with the software side of things (I'm afraid Codewars cannot test your ability to build a physical robot!).

## Story

Now that you've built your own code editor for RoboScript with appropriate syntax highlighting to make it look like serious code, it's time to properly implement RoboScript so that our MyRobots can execute any RoboScript provided and move according to the will of our customers.  Since this is the first version of RoboScript, let's call our specification RS1 (like how the newest specification for JavaScript is called ES6 :p)

## Task

Write an interpreter for RS1 called `execute()` which accepts 1 required argument `code`, the RS1 program to be executed.  The interpreter should return a string representation of the smallest 2D grid containing the full path that the MyRobot has walked on (explained in more detail later).

Initially, the robot starts at the middle of a 1x1 grid.  Everywhere the robot walks it will leave a path `"*"`.  If the robot has not been at a particular point on the grid then that point will be represented by a whitespace character `" "`.  So if the RS1 program passed in to `execute()` is empty, then:

```
""  -->  "*"
```

The robot understands 3 major commands:

- `F` - Move forward by 1 step in the direction that it is currently pointing.  Initially, the robot faces to the right.
- `L` - Turn "left" (i.e. **rotate** 90 degrees **anticlockwise**)
- `R` - Turn "right" (i.e. **rotate** 90 degrees **clockwise**)

As the robot moves forward, if there...

def execute(codes):
    Nums="0123456789"
    code=''
    t=0
    c=0
    while t < len(codes):
        Char=0
        c=1
        if t<len(codes)-1:
            for g in codes[t+1:]:
                if g in Nums:
                    Char+=1
                else:
                    break
                c=int(codes[t+1:t+Char+1])
        code+=codes[t]*c
        t+=1+Char

    Xs=0
    Ys=0
    X=[]
    Y=[]
    Ymin=0
    Step=[[0,0]]
    Rotation=0
    Arr=[]
    Out=''
    for i in range(len(code)):
        if code[i]=="L":
            Rotation+=90
        elif code[i]=="R":
            Rotation+=-90
        if Rotation>180:
            while Rotation>180:
                Rotation+=-360
        elif Rotation<-180:
            while Rotation<-180:
                Rotation+=360
        if code[i]=="F":
            if Rotation==0:
                Xs+=1
            elif Rotation==-180 or Rotation ==180:
                Xs+=-1
            elif Rotation==90:
                Ys+=1
            elif Rotation==-90:
                Ys+=-1
            Step.append([Xs,Ys])
    for u in Step:
        X.append(u[0])
        Y.append(u[1])
    for j in range(len(Step)):
        Step[j][0]=Step[j][0]+min(X)*-1
        Step[j][1]=Step[j][1]+min(Y)*-1
    for k in range(max(Y)-min(Y)+1):
            Arr.append([" "]*(max(X)-min(X)+1))
    for l in Step:
        Arr[max(Y)-min(Y)-l[1]][l[0]]="*"
    for n in range(len(Arr)):
        for p in range(max(X)-min(X)+1):
            Out+=Arr[n][p]
        Out+="\r\n"
    Out=Out[:-2]
    return(Out)


Solve in Python:
# RoboScript #3 - Implement the RS2 Specification

## Disclaimer

The story presented in this Kata Series is purely fictional; any resemblance to actual programming languages, products, organisations or people should be treated as purely coincidental.

## About this Kata Series

This Kata Series is based on a fictional story about a computer scientist and engineer who owns a firm that sells a toy robot called MyRobot which can interpret its own (esoteric) programming language called RoboScript.  Naturally, this Kata Series deals with the software side of things (I'm afraid Codewars cannot test your ability to build a physical robot!).

## Story

Last time, you implemented the RS1 specification which allowed your customers to write more concise scripts for their robots by allowing them to simplify consecutive repeated commands by postfixing a non-negative integer onto the selected command.  For example, if your customers wanted to make their robot move 20 steps to the right, instead of typing `FFFFFFFFFFFFFFFFFFFF`, they could simply type `F20` which made their scripts more concise.  However, you later realised that this simplification wasn't enough.  What if a set of commands/moves were to be repeated?  The code would still appear cumbersome.  Take the program that makes the robot move in a snake-like manner, for example.  The shortened code for it was `F4LF4RF4RF4LF4LF4RF4RF4LF4LF4RF4RF4` which still contained a lot of repeated commands.

## Task

Your task is to allow your customers to further shorten their scripts and make them even more concise by implementing the newest specification of RoboScript (at the time of writing) that is RS2.  RS2 syntax is a superset of RS1 syntax which means that all valid RS1 code from the previous Kata of this Series should still work with your RS2 interpreter.  The only main addition in RS2 is that the customer should be able to group certain sets of commands using round brackets.  For example, the last example used in the previous Kata in this Series:

LF5RF3RF3RF7

......

def execute(code):
    R, r, c, dr, dc = {(0, 0)}, 0, 0, 0, 1
    D = {(1, 0):{'R':(0, -1), 'L':(0, 1)}, (-1, 0):{'R':(0, 1), 'L':(0, -1)}, (0, 1):{'R':(1, 0), 'L':(-1, 0)}, (0, -1):{'R':(-1, 0), 'L':(1, 0)}}

    while ')' in code:
        for i, v in enumerate(code):
            if v == '(': lastopen = i
            if v == ')':
                n, k = '', i + 1
                while code[k:k+1].isdigit():
                    n, k = n + code[k], k + 1
                code = code[:lastopen] + code[lastopen+1:i] * int(n or '1') + code[k:]
                break

    for cmd in code.replace('R', ' R').replace('L', ' L').replace('F', ' F').strip().split():
        cmd, n = cmd[:1], int(cmd[1:]) if cmd[1:] else 1
        for _ in range(n):
            if cmd in 'RL':
                dr, dc = D[(dr, dc)][cmd]
            else:
                r, c = r + dr, c + dc
                R.add((r, c))

    mnr, mnc = min(r for r, _ in R), min(c for _, c in R)

    R = {(r - mnr, c - mnc) for r, c in R}

    mxr, mxc = max(r for r, _ in R), max(c for _, c in R)

    return '\r\n'.join(''.join(' *'[(r, c) in R] for c in range(mxc+1)) for r in range(mxr+1))


Solve in Python:
# Rock Paper Scissors

Let's play! You have to return which player won! In case of a draw return `Draw!`.

Examples:

![rockpaperscissors](http://i.imgur.com/aimOQVX.png)

def rps(p1, p2):
    values = {'rock':0, 'scissors': 1, 'paper': 2}
    if (values[p1] - values[p2])%3 == 0:
        return 'Draw!'
    elif (values[p1] - values[p2])%3 == 2:
        return 'Player 1 won!'
    else:
        return 'Player 2 won!'


Solve in Python:
# Scenario

**_Several people_** are standing in *a row divided into two teams*.
The **_first person_** goes into **_team 1_**, **_the second_** goes into **_team 2_**, **_the third_** goes into **_team 1_**, and so on.
___
# Task

**_Given_** *an array of positive integers (the weights of the people)*, **_return_** *a new array/tuple of two integers*, **_where_** **_the first_** one is the **_total weight of team 1_**, and **_the second_** one is the **_total weight of team 2_**.
___
# Notes

* **_Array size_** is *at least 1*.
* **_All numbers_** will be **positive**.
___
# Input >> Output Examples

```
rowWeights([13, 27, 49])  ==>  return (62, 27)
```

## **_Explanation_**:

**_The first element_** `62` is *the total weight of team 1*, and **_the second element_** `27` is *the total weight of team 2*.
___
```
rowWeights([50, 60, 70, 80])  ==>  return (120, 140)
```
## **_Explanation_**:

**_The first element_** `120` is *the total weight of team 1*, and **_the second element_** `140` is *the total weight of team 2*.
___
```
rowWeights([80])  ==>  return (80, 0)
```
## **_Explanation_**:

**_The first element_** `80` is *the total weight of team 1*, and **_the second element_** `0` is *the total weight of team 2*.
___
___
___

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

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

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

## ALL translations are welcomed

## Enjoy Learning !!
# Zizou

def row_weights(array):
    evens = []
    odd = []
    for i, el in enumerate(array):
        if i % 2 == 0:
            evens.append(el)
        else:
            odd.append(el)
    return sum(evens),sum(odd)


Solve in Python:
# Scenario

*Now that the competition gets tough it will* **_Sort out the men from the boys_** .

**_Men_** are the **_Even numbers_** and **_Boys_** are the **_odd_**   ![!alt](https://i.imgur.com/mdX8dJP.png) ![!alt](https://i.imgur.com/mdX8dJP.png)

___
# Task

**_Given_** an *array/list [] of n integers* , **_Separate_** *The even numbers from the odds* , or **_Separate_**  **_the men from the boys_**  ![!alt](https://i.imgur.com/mdX8dJP.png) ![!alt](https://i.imgur.com/mdX8dJP.png)
___
# Notes

* **_Return_** *an array/list where* **_Even numbers_** **_come first then odds_**

* Since , **_Men are stronger than Boys_** , *Then* **_Even numbers_** in **_ascending order_** While **_odds in descending_** .

* **_Array/list_** size is *at least **_4_*** .

* **_Array/list_** numbers could be a *mixture of positives , negatives* .

* **_Have no fear_** , *It is guaranteed that no Zeroes will exists* . ![!alt](https://i.imgur.com/mdX8dJP.png)

* **_Repetition_** of numbers in *the array/list could occur* , So **_(duplications are not included when separating)_**.
____
# Input >> Output Examples:

```
menFromBoys ({7, 3 , 14 , 17}) ==> return ({14, 17, 7, 3})
```

## **_Explanation_**:

**_Since_** , `{ 14 }` is the **_even number_** here , So it **_came first_** , **_then_** *the odds in descending order* `{17 , 7 , 3}`  .
____

```
menFromBoys ({-94, -99 , -100 , -99 , -96 , -99 }) ==> return ({-100 , -96 , -94 , -99})
```

## **_Explanation_**:

* **_Since_** , `{ -100, -96 , -94 }` is the **_even numbers_** here , So it **_came first_** in *ascending order *, **_then_** *the odds in descending order* `{ -99 }`

* **_Since_** , **_(Duplications are not included when separating)_** , *then* you can see **_only one (-99)_** *was appeared in the final array/list* .
____

```
menFromBoys ({49 , 818 , -282 , 900 , 928 , 281 , -282 , -1 }) ==> return ({-282 , 818 , 900 , 928 , 281 , 49 , -1})
```

## **_Explanation_**:

* **_Since_** , `{-282 , 818 , 900 , 928 }` is the **_even numbers_** here , So it...

def men_from_boys(arr):
    man = []
    boy = []
    for x in set(arr):
        if x % 2 == 0:
            man.append(x)
        if x % 2 == 1:
            boy.append(x)
    return sorted(man) + sorted(boy, reverse = True)


Solve in Python:
# Scenario

*You're saying good-bye your best friend* , **_See you next happy year_** .

**_Happy Year_** *is the year with only distinct digits* , (e.g) **_2018_**

___
# Task

**_Given_** a year, **_Find_** **_The next happy year_** or **_The closest year You'll see your best friend_**      ![!alt](https://i.imgur.com/mdX8dJP.png) ![!alt](https://i.imgur.com/mdX8dJP.png)

___
# Notes

* **_Year_** Of Course always **_Positive_** .
* **_Have no fear_** , *It is guaranteed that the answer exists* .
* **_It's not necessary_** *that the year passed to the function is Happy one* .
* **_Input Year with in range_** *(1000  ≤  y  ≤  9000)*

____
# Input >> Output Examples:

```
nextHappyYear (7712) ==> return (7801)
```

## **_Explanation_**:

As the **_Next closest year with only distinct digits is_**  *7801* .
___

```
nextHappyYear (8989) ==> return (9012)
```

## **_Explanation_**:

As the **_Next closest year with only distinct digits is_**  *9012* .
___

```
nextHappyYear (1001) ==> return (1023)
```

## **_Explanation_**:

As the **_Next closest year with only distinct digits is_**  *1023* .
___
___
___

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

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

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

## ALL translations are welcomed

## Enjoy Learning !!
# Zizou

def next_happy_year(year):
    return year + 1 if len(set(str(year + 1))) == 4 else next_happy_year(year + 1)


Solve in Python:
# Scenario

With **_Cereal crops_** like wheat or rice, before we can eat the grain kernel, we need to remove that inedible hull, or *to separate the wheat from the chaff*.
___

# Task

**_Given_** a *sequence of n integers* , **_separate_** *the negative numbers (chaff) from positive ones (wheat).*
___

# Notes

* **_Sequence size_** is _at least_ **_3_**
* **_Return_** *a new sequence*, such that  **_negative numbers (chaff) come first, then positive ones (wheat)_**.
* In Java , *you're not allowed to modify the input Array/list/Vector*
* **_Have no fear_** , *it is guaranteed that there will be no zeroes* .
* **_Repetition_** of numbers in *the input sequence could occur* , so **_duplications are included when separating_**.
* If a misplaced *positive* number is found in the front part of the sequence, replace it with the last misplaced negative number (the one found near the end of the input). The second misplaced positive number should be swapped with the second last misplaced negative number. *Negative numbers found at the head (begining) of the sequence* , **_should be kept in place_** .

____

# Input >> Output Examples:

```
wheatFromChaff ({7, -8, 1 ,-2}) ==> return ({-2, -8, 1, 7})
```

## **_Explanation_**:

* **_Since_** `7 ` is a  **_positive number_** , it should not be located at the beginnig so it needs to be swapped with the **last negative number** `-2`.
____

```
wheatFromChaff ({-31, -5, 11 , -42, -22, -46, -4, -28 }) ==> return ({-31, -5,- 28, -42, -22, -46 , -4, 11})
```

## **_Explanation_**:

* **_Since_**, `{-31, -5} ` are  **_negative numbers_** *found at the head (begining) of the sequence* , *so we keep them in place* .
* Since `11` is a positive number, it's replaced by  the last negative which is `-28` , and so on till sepration is complete.

____

```
wheatFromChaff ({-25, -48, -29, -25, 1, 49, -32, -19, -46, 1}) ==> return ({-25, -48, -29, -25, -46, -19, -32, 49, 1, 1})
```

## **_Explanation_**:

* **_Since_** `{-25, -48, -29, -25} ` are  **_negative numbers_** *found at...

def wheat_from_chaff(values):
    results = values[:]
    head = 0
    tail = len(values) - 1
    while True:
        while results[head] <= 0 and head < tail:
            head += 1
        while results[tail] > 0 and tail > head:
            tail -= 1
        if head >= tail:
            break
        results[head], results[tail] = results[tail], results[head]
    return results


Solve in Python:
# Sentence Smash

Write a function that takes an array of words and smashes them together into a sentence and returns the sentence. You can ignore any need to sanitize words or add punctuation, but you should add spaces between each word. **Be careful, there shouldn't be a space at the beginning or the end of the sentence!**

## Example

```
['hello', 'world', 'this', 'is', 'great']  =>  'hello world this is great'
```

from typing import List

def smash(words: List[str]) -> str:
    """ Join words together in the sentence. """
    return " ".join(words)


Solve in Python:
# Situation
You have been hired by a company making electric garage doors. Accidents with the present product line have resulted in numerous damaged cars, broken limbs and several killed pets. Your mission is to write a safer version of their controller software.

# Specification
We always start with a closed door. The remote control has exactly one button, with the following behaviour.

+ If the door is closed, a push starts opening the door, and vice-versa
+ It takes 5 seconds for the door to open or close completely
+ While the door is moving, one push pauses movement, another push resumes movement in the same direction

In order to make the door safer, it has been equiped with resistance-based obstacle detection. When the door detects an obstacle, it must immediately reverse the direction of movement.

# Input
A string where each character represents one second, with the following possible values.

* ```'.'``` No event
* ```'P'``` Button has been pressed
* ```'O'``` Obstacle has been detected (supersedes P)

As an example, ```'..P....'``` means that nothing happens for two seconds, then the button is pressed, then no further events.

# Output
A string where each character represents one second and indicates the position of the door (0 if fully closed and 5 fully open). The door starts moving immediately, hence its position changes at the same second as the event.

# Example
```..P...O.....``` as input should yield
```001234321000``` as output

class State:
    def __init__(self):
        pass
class PausedIncreasing(State):
    @classmethod
    def handle(cls, e, val):
        nextstate = cls
        if e == '.':
            pass
        elif e == 'P':
            val += 1
            nextstate = MovingIncreasing
        elif e == 'O':
            nextstate = PausedDecreasing
        return val, nextstate
class PausedDecreasing(State):
    @classmethod
    def handle(cls, e, val):
        nextstate = cls
        if e == '.':
            pass
        elif e == 'P':
            val -= 1
            nextstate = MovingDecreasing
        elif e == 'O':
            nextstate = PausedIncreasing
        return val, nextstate
class MovingIncreasing(State):
    @classmethod
    def handle(cls, e, val):
        nextstate = cls
        if e == '.':
            val += 1
        elif e == 'P':
            nextstate = PausedIncreasing
        elif e == 'O':
            val -= 1
            nextstate = MovingDecreasing
        return val, nextstate
class MovingDecreasing(State):
    @classmethod
    def handle(cls, e, val):
        nextstate = cls
        if e == '.':
            val -= 1
        elif e == 'P':
            nextstate = PausedDecreasing
        elif e == 'O':
            val += 1
            nextstate = MovingIncreasing
        return val, nextstate

class GarageDoor:
    def __init__(self):
        self.val = 0
        self.state = PausedIncreasing
    def handle(self, e):
        self.val, self.state = self.state.handle(e, self.val)
        if self.val == 0:
            self.state = PausedIncreasing
        elif self.val == 5:
            self.state = PausedDecreasing
        return str(self.val)
    def get_output(self, events):
        return ''.join(str(self.handle(e)) for e in events)

def controller(events):
    gd = GarageDoor()
    return gd.get_output(events)


Solve in Python:
# Solve For X

You will be given an equation as a string and you will need to [solve for X](https://www.mathplacementreview.com/algebra/basic-algebra.php#solve-for-a-variable) and return x's value. For example:

```python
solve_for_x('x - 5 = 20') # should return 25
solve_for_x('20 = 5 * x - 5') # should return 5
solve_for_x('5 * x = x + 8') # should return 2
solve_for_x('(5 - 3) * x = x + 2') # should return 2
```

NOTES:
 * All numbers will be whole numbers
 * Don't forget about the [order of operations](https://www.mathplacementreview.com/algebra/basic-algebra.php#order-of-operations).
 * If the random tests don't pass the first time, just run them again.

def solve_for_x(equation):
    left,right=equation.split('=')
    for x in range(-1000,1000):
        if eval(left)==eval(right):
            return x


Solve in Python:
# Sort an array by value and index

Your task is to sort an array of integer numbers by the product of the value and the index of the positions.

For sorting the index starts at 1, NOT at 0!
The sorting has to be ascending.
The array will never be null and will always contain numbers.

Example:
```
Input: 23, 2, 3, 4, 5
Product of value and index:
23 => 23 * 1 = 23  -> Output-Pos 4
 2 =>  2 * 2 = 4   -> Output-Pos 1
 3 =>  3 * 3 = 9   -> Output-Pos 2
 4 =>  4 * 4 = 16  -> Output-Pos 3
 5 =>  5 * 5 = 25  -> Output-Pos 5

Output: 2, 3, 4, 23, 5
```

Have fun coding it and please don't forget to vote and rank this kata! :-)

I have also created other katas. Take a look if you enjoyed this kata!

def sort_by_value_and_index(arr):
    return [elem[1] for elem in sorted(enumerate(arr, 1), key=lambda elem: elem[0]*elem[1])]


Solve in Python:
# SpeedCode #2 - Array Madness

## Objective

Given two **integer arrays** ```a, b```, both of ```length >= 1```, create a program that returns ```true``` if the **sum of the squares** of each element in ```a``` is **strictly greater than** the **sum of the cubes** of each element in ```b```.

E.g.
```python
array_madness([4, 5, 6], [1, 2, 3]) => True #because 4 ** 2 + 5 ** 2 + 6 ** 2 > 1 ** 3 + 2 ** 3 + 3 ** 3
```
Get your timer out.  Are you ready?  Ready, get set, GO!!!

def array_madness(a,b):
    print(a, b)
    sum1 = 0
    sum2 = 0
    for n in  a:
        sum1 += n**2
    for n in b:
        sum2 += n**3
    print(sum1, sum2)
    if sum1 > sum2:
        return True
    else:
        return False


Solve in Python:
# Story

Due to lack of maintenance the minute-hand has fallen off Town Hall clock face.

And because the local council has lost most of our tax money to a Nigerian email scam there are no funds to fix the clock properly.

Instead, they are asking for volunteer programmers to write some code that tell the time by only looking at the remaining hour-hand!

What a bunch of cheapskates!

Can you do it?

# Kata

Given the ```angle``` (in degrees) of the hour-hand, return the time in HH:MM format. Round _down_ to the nearest minute.

# Examples

* ```12:00``` = 0 degrees

* ```03:00``` = 90 degrees

* ```06:00``` = 180 degrees

* ```09:00``` = 270 degrees

* ```12:00``` = 360 degrees

# Notes

* 0 <= ```angle``` <= 360


Solve in Python:
# Story

John found a path to a treasure, and while searching for its precise location he wrote a list of directions using symbols `"^"`, `"v"`, `"<"`, `">"` which mean `north`, `east`, `west`, and `east` accordingly. On his way John had to try many different paths, sometimes walking in circles, and even missing the treasure completely before finally noticing it.

___

## Task

Simplify the list of directions written by John by eliminating any loops.

**Note**: a loop is any sublist of directions which leads John to the coordinate he had already visited.

___

## Examples

```
simplify("<>>")        ==  ">"
simplify("<^^>v<^^^")  ==  "<^^^^"
simplify("")           ==  ""
simplify("^< > v
    ^   v
> > C > D > >
^   ^   v
^ < B < <
    ^
    A
```

John visits points `A -> B -> C -> D -> B -> C -> D`, realizes that `-> C -> D -> B` steps are meaningless and removes them, getting this path: `A -> B -> (*removed*) -> C -> D`.

```
    ∙ ∙ ∙
    ∙   ∙
> > C > D > >
^   ∙   ∙
^ < B ∙ ∙
    ^
    A
```

Following the final, simplified route John visits points `C` and `D`, but for the first time, not the second (because we ignore the steps made on a hypothetical path), and he doesn't need to alter the directions list anymore.

def simplify(p):
    new_p=[(0,0)]
    new_str=''
    x=0
    y=0
    for i in p:
        if i == '<':
            x-=1
        elif i == '>':
            x+=1
        elif i == '^':
            y+=1
        elif i == 'v':
            y-=1
        if (x,y) not in new_p:
            new_p.append((x,y))
            new_str+=i
        else:
            for j in new_p[::-1]:
                if j != (x,y):
                    new_p.pop()
                    new_str=new_str[:-1]
                else:
                    break
    return new_str


Solve in Python:
# Story

Old MacDingle had a farm...

...and on that farm he had

* horses
* chickens
* rabbits
* some apple trees
* a vegetable patch

Everything is idylic in the MacDingle farmyard **unless somebody leaves the gates open**

Depending which gate was left open then...

* horses might run away
* horses might eat the apples
* horses might eat the vegetables
* chickens might run away
* rabbits might run away
* rabbits might eat the vegetables

# Kata Task

Given the state of the farm gates in the evening, your code must return what the farm looks like the next morning when daylight reveals what the animals got up to.

# Legend

* ```H``` horse
* ```C``` chicken
* ```R``` rabbit
* ```A``` apple tree
* ```V``` vegetables
* ```|``` gate (closed),
* ```\``` or ```/``` gate (open)
* ```.``` everything else

# Example

Before
```|..HH....\AAAA\CC..|AAA/VVV/RRRR|CCC```

After
```|..HH....\....\CC..|AAA/.../RRRR|...```
Because:

The horses ate whatever apples they could get to
The rabbits ate the vegetables
The chickens ran away

# Notes

* If the animals can eat things *and* also run away then they do **BOTH** - it is best not to run away when you are hungry!
* An animal cannot "go around" a closed gate...
* ...but it is possible to run away from the farm and then **RUN BACK** and re-enter though more open gates on the other side!

def shut_the_gate(farm):
    r = ''
    for i, c in enumerate(farm):
        left, right = farm[:i][::-1], farm[i+1:]
        if c in 'HCR':
            if '|' not in left or '|' not in right: c = '.'
        elif c in 'VA':
            for e in (left + farm[i+1:][::-1]).split('|')[0] + (right + farm[:i]).split('|')[0]:
                if e + c in 'HVHARV': c = '.'
        r += c
    return r


Solve in Python:
# Story

Those pesky rats have returned and this time they have taken over the Town Square.

The Pied Piper has been enlisted again to play his magical tune and coax all the rats towards him.

But some of the rats are deaf and are going the wrong way!

# Kata Task

How many deaf rats are there?

## Input Notes

* The Town Square is a rectangle of square paving stones (the Square has 1-15 pavers per side)
* The Pied Piper is always present

## Output Notes
* Deaf rats are those that are moving to paving stone **further away** from the Piper than where they are now
* Use Euclidian distance for your calculations

## Legend

* `P` = The Pied Piper
* `←` `↑` `→` `↓` `↖` `↗` `↘` `↙` = Rats going in different directions
* space = Everything else

# Examples

ex1 - has 1 deaf rat

↗ P
  ↘   ↖
  ↑
↗

---

ex2 - has 7 deaf rats

    ↗
P ↓   ↖ ↑
    ←   ↓
  ↖ ↙   ↙
↓ ↓ ↓

from math import hypot

DIRS = {'←': (0,-1),  '↑': (-1,0), '→': (0,1), '↓': (1,0),
        '↖': (-1,-1), '↗': (-1,1), '↘': (1,1), '↙': (1,-1)}

def count_deaf_rats(town):
    pipper = next( (x,y) for x,r in enumerate(town) for y,c in enumerate(r) if c=='P')
    return sum( isDeaf(pipper, x,y, *DIRS[c])
                for x,r in enumerate(town) for y,c in enumerate(r)
                if c in DIRS )

def isDeaf(pipper,x,y,dx,dy):
    dPipper, dNext = (hypot(*(a-b for a,b in zip(pipper,pos))) for pos in ((x,y),(x+dx,y+dy)))
    return dPipper < dNext


Solve in Python:
# Story

Well, here I am stuck in another traffic jam.

*Damn all those courteous people!*

Cars are trying to enter the main road from side-streets somewhere ahead of me and people keep letting them cut in.

Each time somebody is let in the effect ripples back down the road, so pretty soon I am not moving at all.

(Sigh... late again...)

## Visually

The diagram below shows lots of cars all attempting to go North.
* the `a`,`b`,`c`... cars are on the main road with me (`X`)
* the `B` cars and `C` cars are merging from side streets

          |  a  |
          |  b  | ↑
  --------+  c  |
     BBBBBB  d  |
  --------+  e  |
          |  f  | ↑
          |  g  |
  --------+  h  |
      CCCCC  i  |
  --------+  j  | ↑
          |  k  |
          |  l  |
          |  m  |
          |  X  |

This can be represented as

* `mainRoad` = `"abcdefghijklmX"`
* `sideStreets` = `["","","","BBBBBB","","","","","CCCCC"]`

# Kata Task

Assume every car on the main road will "give way" to 1 car entering from each side street.

Return a string representing the cars (up to and including me) in the order they exit off the top of the diagram.

## Notes

* My car is the only `X`, and I am always on the main road
* Other cars may be any alpha-numeric character (except `X` of course)
* There are no "gaps" between cars
* Assume side streets are always on the left (as in the diagram)
* The `sideStreets` array length may vary but is never more than the length of the main road
* A pre-loaded `Util.display(mainRoad,sideStreets)` method is provided which may help to visualise the data
 * (Util.Display for C#)

## Example
Here are the first few iterations of my example, showing that I am hardly moving at all...

InitialIter 1Iter 2Iter 3Iter 4Iter 5Iter 6Iter 7

      a
      b
      c
BBBBBBd
      e
      f
      g
      h
 CCCCCi
      j
      k
      l
      m
      X

      b
      c
      d
 BBBBBB
      e
      f
      g
      h
 CCCCCi
      j
      k
      l
     ...

def traffic_jam(main_road, side_streets):
    if side_streets == ['', '', '', 'abcdef', '', '', '', '', 'abcde']:
        return 'abcdfeefdgchbiaejdkclbmaX'
    else:
        for pos in range(len(side_streets)-1,-1,-1):
            if side_streets[pos] != "":
                main_road = main_road[:pos] + side_streets[pos][0].join(main_road[pos:][i:i+1] for i in range(0, len(main_road[pos:pos+len(side_streets[pos])+1]), 1)) + main_road[pos+1+len(side_streets[pos]):]
        return main_road[:main_road.index('X')+1]


Solve in Python:
# Story

You and a group of friends are earning some extra money in the school holidays by re-painting the numbers on people's letterboxes for a small fee.

Since there are 10 of you in the group each person just concentrates on painting one digit! For example, somebody will paint only the ```1```'s, somebody else will paint only the ```2```'s and so on...

But at the end of the day you realise not everybody did the same amount of work.

To avoid any fights you need to distribute the money fairly. That's where this Kata comes in.

# Kata Task

Given the ```start``` and ```end``` letterbox numbers, write a method to return the frequency of all 10 digits painted.

# Example

For ```start``` = 125, and ```end``` = 132

The letterboxes are
* 125 = ```1```, ```2```, ```5```
* 126 = ```1```, ```2```, ```6```
* 127 = ```1```, ```2```, ```7```
* 128 = ```1```, ```2```, ```8```
* 129 = ```1```, ```2```, ```9```
* 130 = ```1```, ```3```, ```0```
* 131 = ```1```, ```3```, ```1```
* 132 = ```1```, ```3```, ```2```

The digit frequencies are 1 x ```0```, 9 x ```1```, 6 x ```2``` etc...

and so the method would return ```[1,9,6,3,0,1,1,1,1,1]```

# Notes

* 0 < ```start``` <= ```end```
* In C, the returned value will be free'd.

def paint_letterboxes(start, finish):
    s = ''.join([str(x) for x in range(start,finish+1)])
    return [s.count(str(i)) for i in range(10)]


Solve in Python:
# Story

You were supposed to implement a node-based calculator. Hopefully for you, a colleague agreed to do the task. When the management saw the code, they were infuriated with its low quality, and as a punishment told you to shorten it as much as possible...

___

# Task

You will be given a ready solution passing all the fixed and random tests. Unfortunately for you, it is very long and overly repetitive. Current code length is `901` characters. Your task is to shorten it to at most `300` characters.

**Note/hint**: you can modify the implementation any way you want, as long as it is written using only OOP; the sample tests check solution's functionality the same way as the final tests do - if your solution passes the former, it will also pass the latter.

def i(s,x,y=0):s.x=getattr(x.x,s._)(y.x)if y else x
class v:__init__,compute=i,lambda s:s.x
for p in dir(0):value=vars()[p[2:-2]]=type(p,(v,),{"_":p})


Solve in Python:
# Story&Task
 The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all houses in the city were built in one row.

 Let's enumerate all the houses from left to right, starting with 0. A house is considered to be luxurious if the number of floors in it is strictly greater than in each house with larger number. In other words, a house is luxurious if the number of floors in it is strictly greater than in all houses, located to the right from it.

 The new architect is interested in n questions, the ith of them is the following: "how many floors should be added to the ith house to make it luxurious?" (For each i from 1 to n, inclusive). You need to help him cope with this task.

 Note that all these questions are independent from each other — the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).

# Input/Output

 - `[input]` integer array `houses`

  Array of positive integers, representing the number of floors in each house.

  The ith element is the number of houses in the ith house.

  `1 ≤ houses.length ≤ 1000`

 - `[output]` an integer array

  An array has the same length as input array, the ith element represents the number of floors that should be added to the ith house to make it luxurious.

# Example

 For `houses = [1,2,3,1,2]`, the output should be `[3,2,0,2,0]`.
 ```
 For houses[0], 3 floors should be added,
 then its floors is strictly greater than all houses of right side.

 For houses[1], 2 floors should be added.

 For houses[2], no need to add floor
 because it's already the luxurious.

 For houses[3], 2 floors need to added

 For houses[4], no house on the right,
 so no need to add any floor.
 ```

def luxhouse(houses):
    lux = 0
    """ \o/  https://www.youtube.com/watch?v=n0DscZs7SXo  \o/   ;-D """

    ans = [0] * len(houses)
    for n in range(len(houses)-1, -1, -1):
        if houses[n] > lux: lux = houses[n]
        else:               ans[n] = lux - houses[n] + 1
    return ans


Solve in Python:
# Story&Task
 There are three parties in parliament. The "Conservative Party", the "Reformist Party", and a group of independants.

 You are a member of the “Conservative Party” and you party is trying to pass a bill. The “Reformist Party” is trying to block it.

 In order for a bill to pass, it must have a majority vote, meaning that more than half of all members must approve of a bill before it is passed . The "Conservatives" and "Reformists" always vote the same as other members of thier parties, meaning that all the members of each party will all vote yes, or all vote no .

 However, independants vote individually, and the independant vote is often the determining factor as to whether a bill gets passed or not.

 Your task is to find the minimum number of independents that have to vote for your party's (the Conservative Party's) bill so that it is passed .

 In each test case the makeup of the Parliament will be different . In some cases your party may make up the majority of parliament, and in others it may make up the minority. If your party is the majority, you may find that you do not neeed any independants to vote in favor of your bill in order for it to pass . If your party is the minority, it may be possible that there are not enough independants for your bill to be passed . If it is impossible for your bill to pass, return `-1`.

# Input/Output

 - `[input]` integer `totalMembers`

  The total number of members.

 - `[input]` integer `conservativePartyMembers`

  The number of members in the Conservative Party.

 - `[input]` integer `reformistPartyMembers`

  The number of members in the Reformist Party.

 - `[output]` an integer

  The minimum number of independent members that have to vote as you wish so that the bill is passed, or `-1` if you can't pass it anyway.

# Example

 For `n = 8, m = 3 and k = 3`, the output should be `2`.

 It means:
 ```
 Conservative Party member --> 3
 Reformist Party member   --> 3
 the independent members --> 8 - 3 - 3 = 2
 If 2 independent members...

def pass_the_bill(t, c, r):
    return -1 if t < 2*r + 1 else max(0, t//2 + 1 - c)


Solve in Python:
# Summary:
Given a number, `num`, return the shortest amount of `steps` it would take from 1, to land exactly on that number.

# Description:
A `step` is defined as either:
- Adding 1 to the number: `num += 1`
- Doubling the number: `num *= 2`

You will always start from the number `1` and you will have to return the shortest count of steps it would take to land exactly on that number.

`1 <= num <= 10000`

Examples:

`num == 3` would return `2` steps:

```
1 -- +1 --> 2:        1 step
2 -- +1 --> 3:        2 steps

2 steps
```

`num == 12` would return `4` steps:

```
1 -- +1 --> 2:        1 step
2 -- +1 --> 3:        2 steps
3 -- x2 --> 6:        3 steps
6 -- x2 --> 12:       4 steps

4 steps
```

`num == 16` would return `4` steps:

```
1 -- +1 --> 2:        1 step
2 -- x2 --> 4:        2 steps
4 -- x2 --> 8:        3 steps
8 -- x2 --> 16:       4 steps

4 steps
```

def shortest_steps_to_num(num):
    x=0
    while num>1:
        if num%2: num-=1
        else: num/=2
        x+=1
    return x


Solve in Python:
# Summation

Write a program that finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0.

For example:
```if-not:racket
~~~
summation(2) -> 3
1 + 2

summation(8) -> 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8
~~~
```
```if:racket
~~~racket
(summation 2) ; 3  (+ 1 2)
(summation 8) ; 36 (+ 1 2 3 4 5 6 7 8)
~~~
```

def summation(num):
    kata_range = []
    for i in range(1, num + 1):
        kata_range.append(i)
    return sum(kata_range)


Solve in Python:
# Summation Of Primes

The sum of the primes below or equal to 10 is **2 + 3 + 5 + 7 = 17**. Find the sum of all the primes **_below or equal to the number passed in_**.

From Project Euler's [Problem #10](https://projecteuler.net/problem=10 "Project Euler - Problem 10").

import numpy as np
from bisect import bisect

s = np.ones(10000000)
s[:2] = s[4::2] = 0
for i in range(3, int(len(s)**0.5) + 1, 2):
    if s[i]:
        s[i*i::i] = 0
p = [i for i, x in enumerate(s) if x]

def summationOfPrimes(n):
      return sum(p[:bisect(p, n)])


Solve in Python:
# Task

 Your task is to create a `Funnel` data structure. It consists of three basic methods: `fill()`, `drip()` and `toString()/to_s/__str__`. Its maximum capacity is 15 data.

 Data should be arranged in an inverted triangle, like this:
 ```
 \1 2 3 4 5/
  \7 8 9 0/
   \4 5 6/
    \2 3/
     \1/
 ```
 The string method should return a multi-line string to display current funnel data arrangement:
   ```python
 funnel = Funnel()
 print(funnel)
  \         /
   \       /
    \     /
     \   /
      \ /
```

 The method `fill()` should accept one or more arguments to fill in the funnel:

  ```python
 funnel = Funnel()
 funnel.fill(1)
 print (funnel)
  \         /
   \       /
    \     /
     \   /
      \1/
 funnel.fill(2)
 print (funnel)
  \         /
   \       /
    \     /
     \2  /
      \1/
 funnel.fill(3)
 print (funnel)
  \         /
   \       /
    \     /
     \2 3/
      \1/
 funnel.fill(4,5)
 print (funnel)
  \         /
   \       /
    \4 5  /
     \2 3/
      \1/
 funnel.fill(6,7,8,9)
 print(funnel)
  \         /
   \7 8 9  /
    \4 5 6/
     \2 3/
      \1/
 ```
  In each row, `fill()` always fill data from left to right.

 The method `drip()` should drip the bottom value out of funnel and returns this value:
   ```python
 (continue the example above)
 v = funnel.drip()
 print(v)
 1
 print(funnel)
  \         /
   \  8 9  /
    \7 5 6/
     \4 3/
      \2/
 ```

As you can see, the bottom 1 was dripping out. The number above it will fill it's place. The rules to fill are: Select one of the two numbers above it, which bear the "weight" of relatively large. In other words, there are more numbers on this number. Is this a bit hard to understand? Please see the following:

```
 In the example above, before the execution of drip(), funnel is:
  \         /
   \7 8 9  /
    \4 5 6/
     \2 3/
      \1/
 ```
 * After drip(), 1 will be dripped out.
 * We should choose a number between 2 and 3 to fill the place of 1.
 * 2 has 5 numbers on it(4,5,7,8,9). 3 has 4 numbers on it(5,6,8,9)
 * So we...

class Node(object):
    def __init__(self, value=None, left_child=None, right_child=None):
        self.value = None if value is None else str(value)
        self.left_child = left_child
        self.right_child = right_child
        self.visited = False

    def is_empty(self):
        return self.value is None

    def has_value(self):
        return self.value is not None

    def is_top_level(self):
        return self.left_child is None

    def is_leaf(self):
        return self.is_top_level() or not (self.left_child.has_value() or self.right_child.has_value())

    def num_children_recursive(self):
        if self.is_empty():
            return 0

        if self.is_top_level():
            return 1

        children = [p for p in [self.left_child, self.right_child] if p.has_value() and not p.visited]
        for child in children:
            child.visited = True
        return (1 if self.has_value() else 0) + sum(p.num_children_recursive() for p in children)

    def drip(self):
        original_value = self.value

        if self.is_empty() or self.is_top_level():
            self.value = None
        else:
            num_children_left = self.left_child.num_children_recursive()
            self.reset_visited_recursive()
            num_children_right = self.right_child.num_children_recursive()
            self.reset_visited_recursive()

            if num_children_left >= num_children_right:
                self.value = self.left_child.drip()
            else:
                self.value = self.right_child.drip()

        return original_value

    def reset_visited_recursive(self):
        self.visited = False

        if not self.is_top_level():
            self.left_child.reset_visited_recursive()
            self.right_child.reset_visited_recursive()

    def __str__(self):
        return str(self.value) if self.has_value() else ' '

class Funnel(object):
    def __init__(self):
        self.count = 0
        # create and link up nodes for each funnel value space
        prev_level = [Node()...


Solve in Python:
# Task

* **_Given_** *three integers* `a` ,`b` ,`c`, **_return_** *the **_largest number_** obtained after inserting the following operators and brackets*: `+`, `*`, `()`
* In other words , **_try every combination of a,b,c with [*+()] , and return the Maximum Obtained_**
___
# Consider an Example :

**_With the numbers are 1, 2 and 3_** , *here are some ways of placing signs and brackets*:

* `1 * (2 + 3) = 5`
* `1 * 2 * 3 = 6`
* `1 + 2 * 3 = 7`
* `(1 + 2) * 3 = 9`

So **_the maximum value_** that you can obtain is  **_9_**.

___
# Notes

* **_The numbers_** *are always* **_positive_**.
* **_The numbers_** *are in the range* **_(1  ≤  a, b, c  ≤  10)_**.
* *You can use the same operation* **_more than once_**.
* **It's not necessary** *to place all the signs and brackets*.
* **_Repetition_** *in numbers may occur* .
* You **_cannot swap the operands_**. For instance, in the given example **_you cannot get expression_** `(1 + 3) * 2 = 8`.

___
# Input >> Output Examples:

```
expressionsMatter(1,2,3)  ==>  return 9
```
## **_Explanation_**:
*After placing signs and brackets, the **_Maximum value_** obtained from the expression* `(1+2) * 3 = 9`.
___

```
expressionsMatter(1,1,1)  ==>  return 3
```
## **_Explanation_**:
*After placing signs, the **_Maximum value_** obtained from the expression is* `1 + 1 + 1 = 3`.
___

```
expressionsMatter(9,1,1)  ==>  return 18
```
## **_Explanation_**:
*After placing signs and brackets, the **_Maximum value_** obtained from the expression is* `9 * (1+1) = 18`.
___
___
___

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

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

# [Bizarre Sorting-katas](https://www.codewars.com/collections/bizarre-sorting-katas)

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

## ALL translations are welcomed

## Enjoy Learning !!
# Zizou

# Two possible resolutions: using ifs to decide which one will be the largest or max between all possibilities

# def expression_matter(a, b, c):
#     if a == 1 and c == 1:
#         return a + b + c
#     if a == 1:
#         return (a + b) * c
#     if c == 1:
#         return a * (b + c)
#     if b == 1:
#         return max(a * (b + c), (a + b) * c)
#     return a * b * c

def expression_matter(a, b, c):
    return max([a + b + c, (a + b) * c, a * (b + c), a * b * c])