Solve in Python:
## Description
You are a *Fruit Ninja*, your skill is cutting fruit. All the fruit will be cut in half by your knife. For example:

```
[  "apple",     "pear",     "banana"  ]  --> ["app", "le", "pe", "ar", "ban", "ana"]
```
As you see, all fruits are cut in half. You should pay attention to `"apple"`: if you cannot cut a fruit into equal parts, then the first part will has a extra character.

You should only cut the fruit, other things **should not be cut**, such as the `"bomb"`:
```
[  "apple",     "pear",     "banana",   "bomb"]  -->
["app", "le", "pe", "ar", "ban", "ana", "bomb"]
```

The valid fruit names are preloded for you as:
```python
FRUIT_NAMES
```

## Task

```if:javascript
Complete function `cutFruits` that accepts argument `fruits`.
Returns the result in accordance with the rules above.
```
```if:ruby,python
Complete function `cut_fruits` that accepts argument `fruits`.
Returns the result in accordance with the rules above.
```
```if:haskell
Complete function cutFruits that accepts a String array/list.
Returns the result in accordance with the rules above.
```

OK, that's all. I guess this is a 7kyu kata. If you agree, please rank it as 7kyu and vote `very`;-) If you think this kata is too easy or too hard, please shame me by rank it as you want and vote `somewhat` or `none` :[

---

##### *[Click here](https://www.codewars.com/kata/search/?q=i+guess+this+is+a+kyu+kata)  for more more "I guess this is ...kyu" katas!*

FRUIT_NAMES = {'blueberry', 'pear', 'durian', 'ginkgo', 'peach', 'apple', 'cantaloupe', 'fig', 'mangosteen', 'watermelon', 'pineapple', 'cherry', 'pomegranate', 'carambola', 'hawthorn', 'persimmon', 'apricot', 'plum', 'litchi', 'mango', 'jujube', 'lemon', 'orange', 'tomato', 'banana', 'coconut', 'grape', 'pitaya'}
from itertools import *
from math import *
def cut_fruits(fruits):
    def half(f):
        return [f[0:ceil(len(f)/2)], f[ceil(len(f)/2):]] if f in FRUIT_NAMES else [f]

    return list( chain(*[half(f) for f in fruits]) )


Solve in Python:
## Description
Your job is to create a simple password validation function, as seen on many websites.

The rules for a valid password are as follows:
- There needs to be at least 1 uppercase letter.
- There needs to be at least 1 lowercase letter.
- There needs to be at least 1 number.
- The password needs to be at least 8 characters long.

You are permitted to use any methods to validate the password.

## Examples:

### Extra info
- You will only be passed strings.
- The string can contain any standard keyboard character.
- Accepted strings can be any length, as long as they are 8 characters or more.

def password(s):
    return  any(c.isupper() for c in s) and \
            any(c.islower() for c in s) and \
            any(c.isdigit() for c in s) and \
            len(s)>7


Solve in Python:
## Description:

 Remove all exclamation marks from the end of words. Words are separated by spaces in the sentence.

### Examples

```
remove("Hi!") === "Hi"
remove("Hi!!!") === "Hi"
remove("!Hi") === "!Hi"
remove("!Hi!") === "!Hi"
remove("Hi! Hi!") === "Hi Hi"
remove("!!!Hi !!hi!!! !hi") === "!!!Hi !!hi !hi"
```

import re
def remove(s):
    return re.sub(r"(?<=\w)!+(?=\W)*", "", s)


Solve in Python:
## Emotional Sort ( ︶︿︶)

You'll have a function called "**sortEmotions**" that will return an array of **emotions** sorted. It has two parameters, the first parameter called "**arr**" will expect an array of **emotions** where an **emotion** will be one of the following:

- **:D** -> Super Happy
- **:)** -> Happy
- **:|** -> Normal
- **:(** -> Sad
- **T\_T** -> Super Sad

Example of the array:``[ 'T_T', ':D', ':|', ':)', ':(' ]``

And the second parameter is called "**order**", if this parameter is **true** then the order of the emotions will be descending (from **Super Happy** to **Super Sad**) if it's **false** then it will be ascending (from **Super Sad** to **Super Happy**)

Example if **order** is true with the above array: ``[ ':D', ':)', ':|', ':(', 'T_T' ]``

- Super Happy -> Happy -> Normal -> Sad -> Super Sad

If **order** is false: ``[ 'T_T', ':(', ':|', ':)', ':D' ]``

- Super Sad -> Sad -> Normal -> Happy -> Super Happy

Example:
```
arr = [':D', ':|', ':)', ':(', ':D']
sortEmotions(arr, true) // [ ':D', ':D', ':)', ':|', ':(' ]
sortEmotions(arr, false) // [ ':(', ':|', ':)', ':D', ':D' ]

```

**More in test cases!**

Notes:
- The array could be empty, in that case return the same empty array ¯\\\_( ツ )\_/¯
- All **emotions** will be valid

## Enjoy! (づ｡◕‿‿◕｡)づ

emotions = {"T_T": 1, ":(": 2, ":|": 3, ":)": 4, ":D": 5}

def sort_emotions(lst, desc):
    return sorted(lst, key=emotions.get, reverse=desc)


Solve in Python:
## Enough is enough!

Alice and Bob were on a holiday. Both of them took many pictures of the places they've been, and now they want to show Charlie their entire collection. However, Charlie doesn't like these sessions, since the motive usually repeats. He isn't fond of seeing the Eiffel tower 40 times. He tells them that he will only sit during the session if they show the same motive at most N times. Luckily, Alice and Bob are able to encode the motive as a number. Can you help them to remove numbers such that their list contains each number only up to N times, without changing the order?

## Task

Given a list lst and a number N, create a new list that contains each number of lst at most N times without reordering. For example if N = 2, and the input is [1,2,3,1,2,1,2,3], you take [1,2,3,1,2], drop the next [1,2] since this would lead to 1 and 2 being in the result 3 times, and then take 3, which leads to [1,2,3,1,2,3].

~~~if:nasm
## NASM notes

Write the output numbers into the `out` parameter, and return its length.

The input array will contain only integers between 1 and 50 inclusive. Use it to your advantage.
~~~

~~~if:c
For C:
* Assign the return array length to the pointer parameter `*szout`.
* Do not mutate the input array.
~~~

## Example
```python
  delete_nth ([1,1,1,1],2) # return [1,1]

  delete_nth ([20,37,20,21],1) # return [20,37,21]
```

def delete_nth(order,max_e):
    return [order[i] for i in range(len(order)) if order[0:i+1].count(order[i]) <= max_e]


Solve in Python:
## Euler's Method

We want to calculate the shape of an unknown curve which starts at a given point
with a given slope. This curve satisfies an ordinary differential equation (ODE):

```math
\frac{dy}{dx} = f(x, y);\\
y(x_0) = y_0
```

The starting point `$ A_0 (x_0, y_0) $` is known as well as the slope to the curve
at `$ A_0 $` and then the tangent line at `$ A_0 $` .

Take a small step along that tangent line up to a point `$ A_1 $`. Along this small step,
the slope does not change too much, so `$ A_1 $` will be close to the curve.
If we suppose that `$ A_1 $` is close enough to the curve, the same reasoning
as for the point `$ A_1 $` above can be used for other points.
After several steps, a polygonal curve `$ A_0, A_1, ..., A_n $` is computed.
The error between the two curves will be small if the step is small.

We define points `$ A_0, A_1, A_2, ..., A_n $`
whose x-coordinates are `$ x_0, x_1, ..., x_n $`
and y-coordinates are such that `$ y_{k+1} = y_k + f(x_k, y_k) \times h $`
where `$ h $` is the common step. If `$ T $` is the length `$ x_n - x_0 $` we have `$ h = T/n $`.

## Task

For this kata we will focus on the following differential equation:

```math
\frac{dy}{dx} = 2 - e^{-4x} - 2y; \\
A_0 = (0,1)
```
with `$ x ∈ [0, 1] $`. We will then take a uniform partition of the region of `$ x $` between `$ 0 $` and `$ 1 $` and split it into `$ n $` + 1 sections. `$ n $` will be the input to the function `ex_euler(n)` and since `$ T $` is always 1, `$ h = 1/n $`.

We know that an exact solution is
```math
y = 1 + 0.5e^{-4x} - 0.5e^{-2x}.
```
For each `$ x_k $` we are able to calculate the `$ y_k $` as well as the values `$ z_k $` of the exact solution.

Our task is, for a given number `$ n $` of steps, to return the mean (*truncated* to 6 decimal places)
of the relative errors between the `$ y_k $` (our aproximation) and the `$ z_k $` (the exact solution).
For that we can use:

error in `$ A_k = abs(y_k - z_k) / z_k $` and then the mean is sum(errors in `$ A_k $`)/ (`$ n $` + 1)

##...

import math

def exact_sol(t):
    return  1 + 0.5*math.exp(-4*t) - 0.5*math.exp(-2*t)

def slope(y, t):
    return 2 - math.exp(-4*t) - 2*y

def ex_euler(n):
    y = 1
    t = 0
    error = abs(y - exact_sol(t))/exact_sol(t)
    for _ in range(n):
        y += slope(y,t)*(1/n)
        t += 1/n
        error += abs(y - exact_sol(t))/exact_sol(t)

    return (int((error/(n+1))*1e6))/1e6


Solve in Python:
## Find Mean

Find the mean (average) of a list of numbers in an array.

## Information

To find the mean (average) of a set of numbers add all of the numbers together and divide by the number of values in the list.

For an example list of `1, 3, 5, 7`

1. Add all of the numbers

```
1+3+5+7 = 16
```

2. Divide by the number of values in the list. In this example there are 4 numbers in the list.

```
16/4 = 4
```

3. The mean (or average) of this list is 4

def find_average(nums):
    sum = 0
    if (len(nums) == 0):
        return 0
    for i in range(len(nums)):
        sum = sum + nums[i]
    return sum/len(nums)


Solve in Python:
## Fixed xor

Write a function that takes two hex strings as input and XORs them against each other. If the strings are different lengths the output should be the length of the shortest string.

Hint: The strings would first need to be converted to binary to be XOR'd.

## Note:
If the two strings are of different lengths, the output string should be the same length as the smallest string. This means that the longer string will be cut down to the same size as the smaller string, then xor'd

### Further help

More information on the XOR operation can be found here https://www.khanacademy.org/computing/computer-science/cryptography/ciphers/a/xor-bitwise-operation

More information of the binary and hex bases can be found here https://www.khanacademy.org/math/algebra-home/alg-intro-to-algebra/algebra-alternate-number-bases/v/number-systems-introduction

Examples:

```python
fixed_xor("ab3f", "ac") == "07"
fixed_xor("aadf", "bce2") == "163d"
fixed_xor("1c0111001f010100061a024b53535009181c", "686974207468652062756c6c277320657965") == "746865206b696420646f6e277420706c6179"
```

def fixed_xor(a, b):
     if a == "" or b == "":
            return ""

     m = min( len(a), len(b))
     ha = int(a[:m], 16)
     hb = int(b[:m], 16)

     return hex ( ha ^ hb)[2:].zfill(m)


Solve in Python:
## Grade book

Complete the function so that it finds the mean of the three scores passed to it and returns the letter value associated with that grade.

Numerical Score    | Letter Grade
---                | ---
90 <= score <= 100 | 'A'
80 <= score < 90   | 'B'
70 <= score < 80   | 'C'
60 <= score < 70   | 'D'
 0 <= score < 60   | 'F'

Tested values are all between 0 and 100. Theres is no need to check for negative values or values greater than 100.

import numpy as np

def get_grade(*scores):
    grades = {10: 'A', 9:'A', 8:'B', 7:'C', 6:'D'}
    return grades.get(np.mean(scores) // 10, 'F')


Solve in Python:
## If/else syntax debug

While making a game, your partner, Greg, decided to create a function to check if the user is still alive called `checkAlive`/`CheckAlive`/`check_alive`. Unfortunately, Greg made some errors while creating the function.

`checkAlive`/`CheckAlive`/`check_alive` should return true if the player's health is greater than 0 or false if it is 0 or below.

```if-not:csharp
The function receives one parameter `health` which will always be a whole number between -10 and 10.
```

def check_alive(health):
    return (lambda x: True if x > 0 else False)(health)


Solve in Python:
## Introduction

Each chemical element in its neutral state has a specific number of electrons associated with it. This is represented by the **atomic number** which is noted by an integer number next to or above each element of the periodic table (as highlighted in the image above).

As we move from left to right, starting from the top row of the periodic table, each element differs from its predecessor by 1 unit (electron). Electrons fill in different orbitals sets according to a specific order. Each set of orbitals, when full, contains an even number of electrons.

The orbital sets are:
* The _**s** orbital_ - a single orbital that can hold a maximum of 2 electrons.
* The _**p** orbital set_ - can hold 6 electrons.
* The _**d** orbital set_ - can hold 10 electrons.
* The _**f** orbital set_ - can hold 14 electrons.

The order in which electrons are filling the different set of orbitals is shown in the picture above. First electrons will occupy the **1s** orbital, then the **2s**, then the **2p** set, **3s** and so on.

Electron configurations show how the number of electrons of an element is distributed across each orbital set. Each orbital is written as a sequence that follows the order in the picture, joined by the number of electrons contained in that orbital set. The final electron configuration is a single string of orbital names and number of electrons per orbital set where the first 2 digits of each substring represent the orbital name followed by a number that states the number of electrons that the orbital set contains.

For example, a string that demonstrates an electron configuration of a chemical element that contains 10 electrons is: `1s2 2s2 2p6`. This configuration shows that there are two electrons in the `1s` orbital set, two electrons in the `2s` orbital set, and six electrons in the `2p` orbital set. `2 + 2 + 6 = 10` electrons total.

___

# Task

Your task is to write a function that displays the electron configuration built according to the Madelung rule of all chemical elements of...


Solve in Python:
## Nova polynomial add

This kata is from a series on polynomial handling. ( [#1](http://www.codewars.com/kata/nova-polynomial-1-add-1) [#2](http://www.codewars.com/kata/570eb07e127ad107270005fe) [#3](http://www.codewars.com/kata/5714041e8807940ff3001140 ) [#4](http://www.codewars.com/kata/571a2e2df24bdfd4e20001f5) )

Consider a polynomial in a list where each element in the list element corresponds to a factor. The factor order is the position in the list. The first element is the zero order factor (the constant).

`p = [a0, a1, a2, a3]` signifies the polynomial `a0 + a1x + a2x^2 + a3*x^3`

In this kata add two polynomials:

```python
poly_add ( [1, 2], [1] ) = [2, 2]
```

# return the sum of the two polynomials p1 and p2.
def poly_add(p1,p2):
    if p1 == []:
        return p2
    if p2 == []:
        return p1
    return [p1[0] + p2[0]] + poly_add(p1[1:], p2[1:])


Solve in Python:
## Number of people in the bus
There is a bus moving in the city, and it takes and drop some people in each bus stop.

You are provided with a list (or array) of integer arrays (or tuples). Each integer array has two items which represent number of people get into bus (The first item) and number of people get off the bus (The second item) in a bus stop.

Your task is to return number of people who are still in the bus after the last bus station (after the last array). Even though it is the last bus stop, the bus is not empty and some people are still in the bus, and they are probably sleeping there :D

Take a look on the test cases.

Please keep in mind that the test cases ensure that the number of people in the bus is always >= 0. So the return integer can't be negative.

The second value in the first integer array is 0, since the bus is empty in the first bus stop.

def number(bus_stops):
    return sum(x[0] for x in bus_stops) - sum(x[1] for x in bus_stops) # acquired - lost


Solve in Python:
## Number pyramid

Number pyramid is a recursive structure where each next row is constructed by adding adjacent values of the current row. For example:

```
Row 1     [1     2     3     4]
Row 2        [3     5     7]
Row 3           [8    12]
Row 4             [20]
```

___

## Task

Given the first row of the number pyramid, find the value stored in its last row.

___

## Examples

```python
reduce_pyramid([1])        ==  1
reduce_pyramid([3, 5])     ==  8
reduce_pyramid([3, 9, 4])  ==  25
```

___

## Performance tests

```python
Number of tests: 10
List size: 10,000
```

def _coefs(l):
    n = 1
    for i in range(l):
       yield n
       n = n * (l-i-1) // (i+1)
    yield n

def reduce_pyramid(base):
    coefs = _coefs(len(base))
    return sum(next(coefs)*n for n in base)


Solve in Python:
## Objective

Given a number `n` we will define it's sXORe to be `0 XOR 1 XOR 2 ... XOR n` where `XOR` is the [bitwise XOR operator](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).

Write a function that takes `n` and returns it's sXORe.

## Examples
|    n    | sXORe n
|---------|--------
| 0       | 0
| 1       | 1
| 50      | 51
| 1000000 | 1000000
---

d = {0: lambda x: x,
     1: lambda x: 1,
     2: lambda x: (x // 4) * 4 + 3,
     3: lambda x: 0}

def sxore(n):
    return d[n % 4](n)


Solve in Python:
## Overview
Resistors are electrical components marked with colorful stripes/bands to indicate both their resistance value in ohms and how tight a tolerance that value has. If you did my Resistor Color Codes kata, you wrote a function which took a string containing a resistor's band colors, and returned a string identifying the resistor's ohms and tolerance values.

Well, now you need that in reverse: The previous owner of your "Beyond-Ultimate Raspberry Pi Starter Kit" (as featured in my Fizz Buzz Cuckoo Clock kata) had emptied all the tiny labeled zip-lock bags of components into the box, so that for each resistor you need for a project, instead of looking for text on a label, you need to find one with the sequence of band colors that matches the ohms value you need.

## The resistor color codes
You can see this Wikipedia page for a colorful chart, but the basic resistor color codes are:

0: black, 1: brown, 2: red, 3: orange, 4: yellow, 5: green, 6: blue, 7: violet, 8: gray, 9: white

All resistors have at least three bands, with the first and second bands indicating the first two digits of the ohms value, and the third indicating the power of ten to multiply them by, for example a resistor with a value of 47 ohms, which equals 47 * 10^0 ohms, would have the three bands "yellow violet black".

Most resistors also have a fourth band indicating tolerance -- in an electronics kit like yours, the tolerance will always be 5%, which is indicated by a gold band. So in your kit, the 47-ohm resistor in the above paragraph would have the four bands "yellow violet black gold".

## Your mission
Your function will receive a string containing the ohms value you need, followed by a space and the word "ohms" (to avoid Codewars unicode headaches I'm just using the word instead of the ohms unicode symbol). The way an ohms value is formatted depends on the magnitude of the value:

* For resistors less than 1000 ohms, the ohms value is just formatted as the plain number. For example, with the 47-ohm resistor above, your...

import re
colors=['black', 'brown', 'red', 'orange', 'yellow', 'green', 'blue', 'violet', 'gray', 'white']
def encode_resistor_colors(ohms_string):
    split_string=ohms_string.split()
    number=split_string[0]
    if number[-1]=='k':
        number=str(int(float(number[0:-1])*1000))
    elif number[-1]=='M':
        number=str(int(float(number[0:-1])*1000000))
    color1=colors[int(number[0])]
    color2=colors[int(number[1])]
    color3=colors[len(number)-2]
    return color1 + ' ' + color2 + ' ' + color3 + ' gold'


Solve in Python:
## Overview
Resistors are electrical components marked with colorful stripes/bands to indicate both their resistance value in ohms and how tight a tolerance that value has. While you could always get a tattoo like Jimmie Rodgers to help you remember the resistor color codes, in the meantime, you can write a function that will take a string containing a resistor's band colors and return a string identifying the resistor's ohms and tolerance values.

## The resistor color codes
You can see this Wikipedia page for a colorful chart, but the basic resistor color codes are:

black: 0, brown: 1, red: 2, orange: 3, yellow: 4, green: 5, blue: 6, violet: 7, gray: 8, white: 9

Each resistor will have at least three bands, with the first and second bands indicating the first two digits of the ohms value, and the third indicating the power of ten to multiply them by, for example a resistor with the three bands "yellow violet black" would be 47 * 10^0 ohms, or 47 ohms.

Most resistors will also have a fourth band that is either gold or silver, with gold indicating plus or minus 5% tolerance, and silver indicating 10% tolerance. Resistors that do not have a fourth band are rated at 20% tolerance. (There are also more specialized resistors which can have more bands and additional meanings for some of the colors, but this kata will not cover them.)

## Your mission
The way the ohms value needs to be formatted in the string you return depends on the magnitude of the value:

* For resistors less than 1000 ohms, return a string containing the number of ohms, a space, the word "ohms" followed by a comma and a space, the tolerance value (5, 10, or 20), and a percent sign. For example,  for the "yellow violet black" resistor mentioned above, you would return `"47 ohms, 20%"`.

* For resistors greater than or equal to 1000 ohms, but less than 1000000 ohms, you will use the same format as above, except that the ohms value will be divided by 1000 and have a lower-case "k" after it. For example, for a resistor with bands of "yellow...

BANDS = {'black': 0, 'brown': 1, 'red': 2, 'orange': 3, 'yellow': 4,
         'green': 5, 'blue': 6, 'violet': 7, 'gray': 8, 'white': 9}
TOLERANCE_BAND = {'gold': 5, 'silver': 10}
LETTERS = {0: '', 1: 'k', 2: 'M'}
PATTERN = '{}{} ohms, {}%'

def decode_resistor_colors(bands):
    first, second, third, *fourth = bands.split(' ')
    ohms = (BANDS[first] * 10 + BANDS[second]) * 10 ** BANDS[third]

    count = 0
    while ohms >= 1000:
        ohms /= 1000
        count += 1
    ohms = int(ohms) if int(ohms) == ohms else ohms

    letter = LETTERS[count]

    if fourth:
        tolerance = TOLERANCE_BAND[fourth[0]]
    else:
        tolerance = 20

    return PATTERN.format(ohms, letter, tolerance)


Solve in Python:
## Preface

A collatz sequence, starting with a positive integern, is found by repeatedly applying the following function to n until n == 1 :

`$f(n) =
\begin{cases}
n/2,   \text{  if $n$ is even} \\
3n+1,  \text{  if $n$ is odd}
\end{cases}$`
----

A more detailed description of the collatz conjecture may be found [on Wikipedia](http://en.wikipedia.org/wiki/Collatz_conjecture).

## The Problem

Create a function `collatz` that returns a collatz sequence string starting with the positive integer argument passed into the function, in the following form:

"X0->X1->...->XN"

Where Xi is each iteration of the sequence and N is the length of the sequence.

## Sample Input

```python
collatz(4) # should return "4->2->1"
collatz(3) # should return "3->10->5->16->8->4->2->1"
```

Don't worry about invalid input. Arguments passed into the function are guaranteed to be valid integers >= 1.

def collatz_step(n):
    if n % 2 == 0:
        return n//2
    else:
        return n*3 + 1

def collatz_seq(n):
    while n != 1:
        yield n
        n = collatz_step(n)
    yield 1

def collatz(n):
    return '->'.join(str(x) for x in collatz_seq(n))


Solve in Python:
## Problem

Determine whether a positive integer number is **colorful** or not.

`263` is a colorful number because `[2, 6, 3, 2*6, 6*3, 2*6*3]` are all different; whereas `236` is not colorful, because `[2, 3, 6, 2*3, 3*6, 2*3*6]` have `6` twice.

So take all consecutive subsets of digits, take their product and ensure all the products are different.

## Examples
```pyhton
263  -->  true
236  -->  false
```

def colorful(number):
    if len(str(number)) == 1:
        return True
    else:
        output = list(str(number))
        for n,x in enumerate(list(str(number))):
            if n + 1 < len(str(number)):
                tmp = list(str(number))[n+1]

                #tmp = int()
                output.append(str(int(x) * int(tmp)))

        if len(output) == len(set(output)):
            return True
        else:
            return False


Solve in Python:
## Problem

There are `n` apples that need to be divided into four piles. We need two mysterious number `x` and `y`. Let The number of first pile equals to `x+y`, the number of second pile equals to `x-y`, the number of third pile equals to `x*y`, the number of fourth pile equals to `x/y`. We need to calculate how many apples are there in each pile.

Of course, there won't be so many unknowns. We know the total number of apples(`n`) and the second mysterious number(`y`).

For example: there are 48 apples need to divided into four piles. y=3. that is, 1st pile should be x+3, 2nd pile should be x-3, 3rd pile should be x*3, 4th pile should be x/3.
Do you know how much `x` is? `x` should be 9, because:
```
(9 + 3) + (9 - 3) + (9 * 3) + (9 / 3) = 12 + 6 + 27 + 3 = 48
```
So, 48 apples should be divided into `12, 6, 27, 3`.

## Task

Complete function `fourPiles()`/`four_piles()` that accepts two arguments `n` and `y`, return an array contains the number of for piles. Each element in the result array should be a positive integer. If can not divide, please return `[]`.

## Examples

```
fourPiles 48 3 -- [12,6,27,3]
//The elements are arranged in sequence according to:
//   x+y,x-y,x*y,x/y

fourPiles 100 4 -- [20,12,64,4]
-- Verify correctness:
-- x=16,y=4
(16+4) + (16-4) + (16*4) + (16/4) -- 100

-- Edge case:
fourPiles 25 4  -- []  -- [8,0,16,1] is not a correct answer

fourPiles 24 4  -- []  -- can not divide
```

def four_piles(n,y):
    x = y*n / (1+2*y+y**2)
    ans = [x+y, x-y, x*y, x/y]
    return ans if all(not z%1 and z for z in ans) else []


Solve in Python:
## Snail Sort

Given an `n x n` array, return the array elements arranged from outermost elements to the middle element, traveling clockwise.

```
array = [[1,2,3],
         [4,5,6],
         [7,8,9]]
snail(array) #=> [1,2,3,6,9,8,7,4,5]
```

For better understanding, please follow the numbers of the next array consecutively:

```
array = [[1,2,3],
         [8,9,4],
         [7,6,5]]
snail(array) #=> [1,2,3,4,5,6,7,8,9]
```

This image will illustrate things more clearly:

NOTE: The idea is not sort the elements from the lowest value to the highest; the idea is to traverse the 2-d array in a clockwise snailshell pattern.

NOTE 2: The 0x0 (empty matrix) is represented as en empty array inside an array `[[]]`.

def snail(array):
    mission = Game(array)
    path = []
    while mission.we_are_not_done:
        path.append(mission.dig_at_location())
        if mission.it_is_safe_to_slither:
            mission.slither_onwards_good_soldier()
        else:
            mission.turn_away_from_fire()
            mission.slither_onwards_good_soldier()
    return path

class Game(object):
    def __init__(self, array):
        self.map = array
        self.moves_left = len(array) * len(array[0])
        self.coords = {"x": 0, "y": len(array)-1}  # start in NW area.
        self.dir = "E"  # slitherin' east.
        self.fire = {"min_x": -1, "min_y": -1, "max_x": len(array),
                     "max_y": len(array)}  # the carpet is lava.
        self.rules = {"N": {"x": 0, "y": 1, "turn": "E"},
                      "E": {"x": 1, "y": 0, "turn": "S"},
                      "S": {"x": 0, "y": -1, "turn": "W"},
                      "W": {"x": -1, "y": 0, "turn": "N"}}

    def slither_onwards_good_soldier(self):
        self.coords["x"] = self.next_x
        self.coords["y"] = self.next_y
        self._subtract_move()

    def turn_away_from_fire(self):
        self._become_aware_that_the_world_is_closing_in()
        self.dir = self.rules[self.dir]["turn"]

    def dig_at_location(self):
        # have to invert the y location for the purpose of the array.
        return self.map[len(self.map)-self.coords["y"]-1][self.coords["x"]]

    def report_in(self):
        print(("Dear Sir! I'm stationed @ x: %s, y: %s, heading %s." %
              (self.coords["x"], self.coords["y"], self.dir)))

    @property
    def it_is_safe_to_slither(self):
        x = self.next_x
        y = self.next_y
        if x != self.fire["min_x"] and \
           x != self.fire["max_x"] and \
           y != self.fire["min_y"] and \
           y != self.fire["max_y"]:
            return True

    @property
    def we_are_not_done(self):
        if self.moves_left > 0:
            return True

    @property
    def next_x(self):
        return...


Solve in Python:
## Story

> "You have serious coding skillz? You wannabe a [scener](https://en.wikipedia.org/wiki/Demoscene)? Complete this mission and u can get in teh crew!"

You have read a similar message on your favourite [diskmag](https://en.wikipedia.org/wiki/Disk_magazine) back in the early 90s, and got really excited. You contacted the demo crew immediately and they gave you the following job: write a vertical sinus scroller... **for the printer!**

## Your task

Write a function that takes three parameters: `text`, `amp` (for [peak amplitude](https://en.wikipedia.org/wiki/Amplitude)) and `period` (or [wavelength](https://en.wikipedia.org/wiki/Wavelength)). Return a string (split into multiple lines) that will display the text as a vertical sine wave.

Note: `amp` and `period` are measured in characters and are always positive integers; `text` is never empty.

## Example

```python
>>> scroller('Hello World!', 3, 10)
'   H\n     e\n      l\n      l\n     o\n    \n W\no\nr\n l\n   d\n     !'
```

Doesn't make much sense? Well, let's print it!

```python
   H        1
     e      2
      l     3
      l     4
     o      5
            6
 W          7
o           8
r           9
 l         10
   d        1
     !      2

3210123
```

(Obviously, the numbers are only shown above to demonstrate `amp` and `period`)

Happy coding!

*Note:* due to the inevitable use of floats, solutions with slight rounding errors (1 space difference in less than 10% of the output lines) will be accepted.

---

## My other katas

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

#### *Translations are welcome!*

from math import*;scroller=lambda t,a,p:"\n".join(" "*round(a+a*sin(i/p*tau))+c for i,c in enumerate(t))


Solve in Python:
## Story

Before we dive into the exercise, I would like to show you why these numbers are so important in computer programming today.

It all goes back to the time of 19th century. Where computers we know today were non-existing. The first ever **computer program** was for the Analytical Engine to compute **Bernoulli numbers**. A woman named Ada Lovelace wrote the very first program. The sad part is the engine was never fully build so her code was never tested. She also predicted the start of **AI** (artificial intelligence).

Computers will be able to compose music by themselves, solve problems (not only numbers) ... So in her honor reproduce what was done back in 1842. The Bernoulli numbers are a sequence of rational numbers with deep connections to number theory. The Swiss mathematician Jakob Bernoulli and the Japanese mathematician Seki Kowa discovered the numbers around the same time at the start of the 18th Century. If you want to read more about her or Bernoulli numbers follow these links:

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

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

http://mathworld.wolfram.com/BernoulliNumber.html

## Exercise

Your job is to write a function `bernoulli_number(n)` which outputs the n-th Bernoulli number. The input will always be a non-negative integer so you do not need to worry about exceptions. How you will solve the problem is none of my business but here are some guidelines.
You can make pascal triangle and then with the basic formula generate all Bernoulli numbers. Look example below.

For the sake of floating numbers, just use `Fractions` so there will be no problems with rounding.

0 = 1 + 2b1 ...............................................................
  b1 = - 1/2

0 = 1 + 3b1 + 3b2 ...................................................    b2        = 1/6

0 = 1 + 4b1 + 6b2 + 4b3 .......................................  b3 = 0

0 = 1 + 5b1 + 10b2 + 10b3 + 5b4 ...................... b4 = - 1/30

... and so on.

```
bernoulli_number(0) # return...

from fractions import Fraction as f
def bernoulli_number(n):
    if n == 1: return f(-1, 2)
    if n % 2 == 1: return 0
    с = [i for i in zip(range(n + 2), consider())]
    с = [b for _, b in с]
    return с[n]
def consider():
    k, t = [], 0
    while True:
        k.append(f(1, t+1))
        for j in range(t, 0, -1):
            k[j-1] = j*(k[j-1] - k[j])
        yield k[0]
        t += 1


Solve in Python:
## Story

John runs a shop, bought some goods, and then sells them. He used a special accounting method, like this:
```
[[60,20],[60,-20]]
```
Each sub array records the commodity price and profit/loss to sell (percentage). Positive mean profit and negative means loss.

In the example above, John's first commodity sold at a price of $60, he made a profit of 20%; Second commodities are sold at a price of $60 too, but he lost 20%.

Please calculate, whether his account is profit or loss in the end?

## Rules

Write a function ```profitLoss```, argument ```records``` is the list of sales.

return a number(positive or negative), round to two decimal places.

## Examples

def profitLoss(records):
    return round(sum(x * p / (100 + p) for x, p in records), 2)


Solve in Python:
## Story

There are four warriors, they need to go through a dark tunnel. Tunnel is very narrow, every time only can let two warriors through, and there are lot of dangerous traps. Fortunately, they have a lamp that can illuminate the tunnel to avoid being trapped by the trap.

In order to pass this tunnel, they need five steps:

1. Two people go through the tunnel with the lamp
2. And then one people come back with the lamp
3. And then two people go through the tunnel with the lamp
4. And then one people come back with the lamp
5. And then two people go through the tunnel with the lamp

Each warrior has his own walking speed, we need to calculate the shortest time they have to cross the tunnel.

For example:

Four warriors is `a,b,c,d`. Their speed are `[3,4,5,6]`. It means they need 3 minutes, 4 minutes, 5 minutes and 6 minutes to cross the tunnel. The shortest crossing time should be 21 minutes, the method is as follows:

```
a and b go through the tunnel  ---> Spend 4 minutes
(Time spent should be calculated by the person who is slow)
a come back                    ---> Spend 3 minutes
a and c go through the tunnel  ---> Spend 5 minutes
a come back                    ---> Spend 3 minutes
a and d go through the tunnel  ---> Spend 6 minutes
```
Do you have any other better way?

## Task
Complete function `shortestTime()` that accepts 1 argument: `speed` that are the spent time of four warriors. Returns the shortest time that all warriors go through the tunnel.

**Note: The method in example above is not always the best way.**

## Example

def shortest_time(speed):
    speed = sorted(speed)
    return min(speed[1]*3+speed[0]+speed[3],speed[0]+sum(speed))


Solve in Python:
## Story

Your company migrated the last 20 years of it's *very important data* to a new platform, in multiple phases. However, something went wrong: some of the essential time-stamps were messed up! It looks like that some servers were set to use the `dd/mm/yyyy` date format, while others were using the `mm/dd/yyyy` format during the migration. Unfortunately, the original database got corrupted in the process and there are no backups available... Now it's up to you to assess the damage.

## Task

You will receive a list of records as strings in the form of `[start_date, end_date]` given in the ISO `yyyy-mm-dd` format, and your task is to count how many of these records are:
* **correct**: there can be nothing wrong with the dates, the month/day cannot be mixed up, or it would not make a valid timestamp in any other way; e.g. `["2015-04-04", "2015-05-13"]`
* **recoverable**: invalid in its current form, but the original timestamp can be recovered, because there is only one valid combination possible; e.g. `["2011-10-08", "2011-08-14"]`
* **uncertain**: one or both dates are ambiguous, and they may generate multiple valid timestamps, so the original cannot be retrieved; e.g. `["2002-02-07", "2002-12-10"]`

**Note:** the original records always defined a *non-negative* duration

Return your findings in an array: `[ correct_count, recoverable_count, uncertain_count ]`

## Examples

---

## My other katas

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

from datetime import date

def less(d1, d2):
    if d1 == None or d2 == None:
        return 0

    return 1 if d1 <= d2 else 0

def check_dates(records):
    correct = recoverable = uncertain = 0
    for interval in records:
        start = interval[0].split('-')
        end = interval[1].split('-')
        try:
            start1 = date(int(start[0]), int(start[1].lstrip('0')), int(start[2].lstrip('0')))
        except:
            start1 = None
        try:
            start2 = date(int(start[0]), int(start[2].lstrip('0')), int(start[1].lstrip('0')))
        except:
            start2 = None
        try:
            end1 = date(int(end[0]), int(end[1].lstrip('0')), int(end[2].lstrip('0')))
        except:
            end1 = None
        try:
            end2 = date(int(end[0]), int(end[2].lstrip('0')), int(end[1].lstrip('0')))
        except:
            end2 = None

        combinations = less(start1, end1) + less(start1, end2) + less(start2, end1) + less(start2, end2)
        if start1 == start2:
            combinations -= 1
        if end1 == end2:
            combinations -= 1
        if start1 == start2 and end1 == end2:
            combinations -= 1

        if less(start1, end1) == 1 and combinations == 1:
            correct += 1
        elif combinations == 1:
            recoverable += 1
        else:
            uncertain += 1

    return [correct, recoverable, uncertain]


Solve in Python:
## Sum Even Fibonacci Numbers

* Write a func named SumEvenFibonacci that takes a parameter of type int and returns a value of type int

* Generate all of the Fibonacci numbers starting with 1 and 2 and ending on the highest number before exceeding the parameter's value

#### Each new number in the Fibonacci sequence is generated by adding the previous two numbers - by starting with 1 and 2(the input could be smaller), the first 10 numbers will be:

```
 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
```

* Sum all of the even numbers you generate and return that int

#### Example:

```
sumEvenFibonacci(8) // returns 10 by adding the even values 2 and 8
```

from functools import lru_cache
from itertools import takewhile, count
even_fib = lru_cache(maxsize=None)(lambda n: 2 if n==0 else 8 if n==1 else 4*even_fib(n-1) + even_fib(n-2))

def SumEvenFibonacci(limit):
    return sum(takewhile(limit.__ge__, map(even_fib, count())))


Solve in Python:
## TL;DR

Given a number of vertices `N` and a list of weighted directed edges in a directed acyclic graph (each edge is written as `[start, end, weight]` where `from < to`), compute the weight of the shortest path from vertex `0` to vertex `N - 1`.  If there is no such path, return `-1`.

## Background

A weighted DAG is a directed acyclic graph where each edge has a weight associated with it:

1
5
3
1
5

A
B
C
D

In this example, the shortest path from A to D is given by A -> B -> D, which has a total weight of 4.

Finding shortest distances in DAGs is made easier by the fact that the nodes can be _linearized:_ they can be given an order `A1, A2, ..., An` such that edges only point forward (that is, there are no edges from `Aj` to `Ai` when `j > i`).  In the example above, the two possible linear orderings are `A, B, C, D` and `A, C, B, D.`

1

1
5
5
3

A
B
C
D

## Your Task

Given a number `N` (indicating a graph with vertices `0, 1, ..., N-1`) and a list of weighted edges `[start, end, weight]` for a DAG, where `start < end` for each edge, find the weight (a.k.a. length) of the shortest path from node `0` to node `N-1`.

For example, if the input is

```
N = 4
edgeList = [
  [0, 1, 1], [0, 2, 5], [0, 3, 5], [1, 3, 3], [2, 3, 1]
]
```

then we have the graph depicted above (with `0 = A`, `1 = B`, etc.) and the answer is `4`.

If there is no path from node `0` to node `N-1`, return `-1`.

## Notes and Warnings

**Precondition:** `N` will always be greater than 1, and edge weights will always be positive integers.  There may be multiple edges going between two nodes.

**Warning:** You will probably need to use a dynamic programming solution if you want your solution to run fast enough not to time out--that's the whole point of this kata!

However, a well-written general shortest-path algorithm such as Dijkstra's Algorithm may also be fast enough to past the soak tests.  (The reason is that the dividing line between linear and linearithmic time is hard to define and depends...

def shortest(N, edgeList):

    edgeList.sort(key= lambda x: x[0])
    path_values = [None for _ in range(N)]
    path_values[0] = 0

    for edge in edgeList:

        if path_values[edge[0]] != None: # If the node value is 0, then we can not use it as a base to go further.
            new_val = edge[2] + path_values[edge[0]]

            if path_values[edge[1]] == None:
                path_values[edge[1]] = new_val
            else:
                path_values[edge[1]] = min(path_values[edge[1]], new_val)

    if path_values[-1] == None: # no path goes to the end
        return -1
    else:
        return path_values[-1]


Solve in Python:
## Task

**_Given_** *an array of integers* , **_Find_** **_the maximum product_** *obtained from multiplying 2 adjacent numbers in the array*.
____

# Notes

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

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

# Input >> Output Examples
```
adjacentElementsProduct([1, 2, 3]); ==> return 6
```

## **_Explanation_**:

* **_The maximum product_** *obtained from multiplying* ` 2 * 3 = 6 `, and **_they're adjacent numbers in the array_**.
___
```
adjacentElementsProduct([9, 5, 10, 2, 24, -1, -48]); ==> return 50
```
## **_Explanation_**:
**_Max product_** obtained *from multiplying*   ``` 5 * 10  =  50  ```.
___
```
adjacentElementsProduct([-23, 4, -5, 99, -27, 329, -2, 7, -921])  ==>  return -14
```

## **_Explanation_**:

* **_The maximum product_** *obtained from multiplying* ` -2 * 7 = -14 `, and **_they're adjacent numbers in the array_**.
___
___
___

# [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 adjacent_element_product(array):
    M = array[0]*array[1]
    for i, element in enumerate(array[1:]):
        x = element * array[i]
        if x > M:
            M = x
    return M


Solve in Python:
## Task

Complete function `splitOddAndEven`, accept a number `n`(n>0), return an array that contains the continuous parts of odd or even digits.

Please don't worry about digit `0`, it won't appear ;-)

## Examples

from itertools import groupby

def split_odd_and_even(n):
    return [int(''.join(str(b) for b in g)) for k, g in
            groupby((int(a) for a in str(n)), key=lambda b: b % 2)]


Solve in Python:
## Task

Complete the function that receives an array of strings (`arr`) as an argument and returns all the valid Roman numerals.

Basic Roman numerals are denoted as:

```
I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000
```

For the purposes of this kata we will consider valid only the numbers in range 0 - 5000 (both exclusive) since numbers >= 5000 were written in a different way (you had to place a heavy bar over the numeral that meant it was multiplied with 1000).

There are other ways of tackling this problem but the easiest is probably writing a Regular Expression.

### Let's break the problem down:

To match a set of characters `/[1-9]/`(single digits) you should take into consideration the Roman numbers `I, II, III, IV, V, VI, VII, VIII, IX`. This could be done by testing with `/IX|IV|V?I{0,3}/`. This part `/I{0,3}/` matches `I, II or III` but we have a `V` appearing 0 or 1 times because of the `?` so `/V?I{0,3}/` would match `I,II,III,V,VI,VII or VIII`. However there is one flaw with this. Do you see it? It is the fact that it would also match an empty string `""` because of the {0,3}. In order to pass the tests you will have to **filter out the empty strings** as well. So the entire part matches `I to IX`(inclusive) but what about larger digits?

Use the same logic for the digit in the tens place and the hundreds place. Be sure to wrap each part (units, tens, hundreds, thousands) in a pair of braces `(IX|IV|V?I{0,3})` and for the digit in the thousands place the logic is pretty straight forward, you just have to match `M` 0 to 4 times (since 5000 is not included). Wrap everything up with `^` and `$` to make sure you match the entire string (^ matches from the beginning of the string, while $ denotes the end, meaning there is nothing after that sign.

## Examples

```
["I", "IIV", "IVI", "IX", "XII", "MCD"] ==> ["I", "IX", "XII", "MCD"]

["MMMMCMXCIX", "MMDCXLIV", "MMCIX", "CLD", "LCD"]) ==> ["MMMMCMXCIX", "MMDCXLIV", "MMCIX"]
```

Good luck!

ones = [''] + 'I II III IV V VI VII VIII IX'.split()
tens = [''] + 'X XX XXX XL L LX LXX LXXX XC'.split()
hundreds = [''] + 'C CC CCC CD D DC DCC DCCC CM'.split()
thousands = [''] + 'M MM MMM MMMM'.split()
good = ['MMMMM'] + [i+j+k+l for i in thousands for j in hundreds for k in tens for l in ones]

def valid_romans(arr):
    return [i for i in arr if i and i in good]


Solve in Python:
## Task

Create a RomanNumerals class that can convert a roman numeral to and from an integer value.  It should follow the API demonstrated in the examples below. Multiple roman numeral values will be tested for each helper method.

Modern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. In Roman numerals 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC. 2008 is written as 2000=MM, 8=VIII; or MMVIII. 1666 uses each Roman symbol in descending order: MDCLXVI.

## Examples

```python
RomanNumerals.to_roman(1000) # should return 'M'
RomanNumerals.from_roman('M') # should return 1000
```

## Help

| Symbol | Value |
|----------------|
| I          | 1     |
| V          | 5     |
| X          | 10    |
| L          | 50    |
| C          | 100   |
| D          | 500   |
| M          | 1000  |


Solve in Python:
## Task

Create a function that given a sequence of strings, groups the elements that can be obtained by rotating others, ignoring upper or lower cases.

In the event that an element appears more than once in the input sequence, only one of them will be taken into account for the result, discarding the rest.

## Input

Sequence of strings. Valid characters for those strings are uppercase and lowercase characters from the alphabet and whitespaces.

## Output

Sequence of elements. Each element is the group of inputs that can be obtained by rotating the strings.

Sort the elements of each group alphabetically.

Sort the groups descendingly by size and in the case of a tie, by the first element of the group alphabetically.

## Examples

```python
['Tokyo', 'London', 'Rome', 'Donlon', 'Kyoto', 'Paris', 'Okyot'] --> [['Kyoto', 'Okyot', 'Tokyo'], ['Donlon', 'London'], ['Paris'], ['Rome']]

['Rome', 'Rome', 'Rome', 'Donlon', 'London'] --> [['Donlon', 'London'], ['Rome']]

[] --> []
```

from collections import defaultdict

def group_cities(seq):
    key = lambda s: min(s[i:]+s[:i] for i in range(len(s)))
    d = defaultdict(set)
    for e in seq: d[key(e.lower())].add(e)
    return sorted((sorted(v) for v in d.values()), key=lambda x: (-len(x),x))


Solve in Python:
## Task

Find the sum of the first `n` elements in the Recamán Sequence.

Input range:

```python
1000 tests
0 <= n <= 2,500,000
```

___

## Sequence

The sequence is formed using the next formula:
* We start with `0`
* At each step `i`, we subtract `i` from the previous number
* If the result is not negative, and not yet present in the sequence, it becomes the `i`th element of the sequence
* Otherwise the `i`th element of the sequence will be previous number plus `i`

The beginning of the sequence is `[0, 1, 3, 6, 2, ...]` because:
0) `0` <- we start with `0`
1) `1` <- `0 - 1` is negative, hence we choose `0 + 1`
2) `3` <- `1 - 2` is negative, hence we choose `1 + 2`
3) `6` <-`3 - 3` is not negative, but we already have a `0` in the sequence, hence we choose `3 + 3`
4) `2` <- `6 - 4` is positive, and is not present in the sequence yet, so we go for it

___

## Examples

```
rec(0) == 0
rec(1) == 0
rec(2) == 1
rec(3) == 4
rec(4) == 10
rec(5) == 12
```

R=[0,0]

s=0
p=0
S={0}
for i in range(1,2500000):
    x=p-i
    if x<0 or x in S:x=p+i
    S|={x}
    s+=x
    p=x
    R+=[s]
def rec(x):return R[x]


Solve in Python:
## Task

Generate a sorted list of all possible IP addresses in a network.

For a subnet that is not a valid IPv4 network return `None`.

## Examples
```
ipsubnet2list("192.168.1.0/31") == ["192.168.1.0", "192.168.1.1"]
ipsubnet2list("213.256.46.160/28") == None
```

def ipsubnet2list(subnet):
    netaddr,prefix=subnet.split('/')
    if not all([0<=int(x)<256 for x in netaddr.split('.')]):
        return None
    netaddrbyte=0
    for x in netaddr.split('.'):
        netaddrbyte=netaddrbyte*256+int(x)
    r=[]
    for i in range(2**(32-int(prefix))):
        addr=netaddrbyte+i
        a=[]
        for _ in range(4):
            a.append(addr%256)
            addr//=256
        r.append('.'.join(map(str,a[::-1])))
    if int(prefix)<31:
        r=r[1:-1]
    return r


Solve in Python:
## Task

Given `n` representing the number of floors build a beautiful multi-million dollar mansions like the ones in the example below:

```
     /\
    /  \
   /    \
  /______\  number of floors 3
  |      |
  |      |
  |______|

     /\
    /  \
   /____\
   |    |   2 floors
   |____|

     /\
    /__\    1 floor
    |__|
```

**Note:** whitespace should be preserved on both sides of the roof. Number of floors will go up to 30. There will be no tests with invalid input.

If you manage to complete it, you can try a harder version [here](https://www.codewars.com/kata/58360d112fb0ba255300008b).

Good luck!

class House(object):
    roofleft, roofright = '/', '\\'
    wall = '|'
    bottom = '_'

    def __init__(self, floors):
        self.floors = floors

    def __new__(cls, floors):
        a = super(House, cls).__new__(cls)
        a.__init__(floors)
        return str(a)

    @property
    def width(self):
        return self.floors * 2 + 2

    @property
    def height(self):
        return self.floors * 2 + 1

    @property
    def roofparts(self):
        return list(range(self.floors))

    @property
    def gutterparts(self):
        return list(range(max(self.roofparts) + 1, max(self.roofparts) + 2))

    @property
    def floorparts(self):
        return list(range(max(self.gutterparts) + 1, self.height - 1))

    @property
    def groundparts(self):
        return list(range(self.height -1, self.height))

    def genpart(self, index):
        if index in self.roofparts:
            return self.genroof(index, outerfill=" ", innerfill=" ")
        if index in self.gutterparts:
            return self.genroof(index, outerfill="", innerfill="_")
        if index in self.floorparts:
            return self.genfloor(index, outerfill="", innerfill=" ")
        if index in self.groundparts:
            return self.genfloor(index, outerfill="", innerfill="_")

    def genroof(self, index, innerfill, outerfill):
        margin = "{:{outerfill}^{width}}".format("", outerfill=outerfill, width=(self.floors - index))
        roofpart = "{margin}{roofleft}{centerfill}{roofright}{margin}".format(
            margin=margin,
            roofleft=self.roofleft,
            roofright=self.roofright,
            centerfill=innerfill * 2 * index)
        return roofpart

    def genfloor(self, index, innerfill, outerfill):
        margin = "{outerfill:{innerfill}^{width}}".format(innerfill=innerfill, outerfill=outerfill, width=self.width)
        roofpart = "{wall}{centerfill}{wall}".format(
            wall=self.wall,
           ...


Solve in Python:
## Task

Given a positive integer `n`, calculate the following sum:

```
n + n/2 + n/4 + n/8 + ...
```

All elements of the sum are the results of integer division.

## Example

```
25  =>  25 + 12 + 6 + 3 + 1 = 47
```

import math
def halving_sum(n):
    if n < 1:
        return 0
    elif n == 1:
        return 1
    return math.floor(n) + halving_sum(n/2)


Solve in Python:
## Task

Given a positive integer as input, return the output as a string in the following format:

Each element, corresponding to a digit of the number, multiplied by a power of 10 in such a way that with the sum of these elements you can obtain the original number.

## Examples

Input | Output
---   | ---
0     | ""
56    | "5\*10+6"
60    | "6\*10"
999   | "9\*100+9\*10+9"
10004 | "1\*10000+4"

Note: `input >= 0`

def simplify(number: int) -> str:
    digits = str(number)
    res = [f"{n}*1{'0' * i}" for i, n in zip(list(range(len(digits) - 1, 0, -1)), digits) if n != '0']
    return '+'.join(res + ([digits[-1]] if digits[-1] != '0' else []))


import operator as op
from functools import reduce

def factors(n):
    div = 2
    d = dict()

    while n > (div - 1) ** 2:
        if n % div == 0:
            n = n // div
            if div in d:
                d[div] += 1
            else:
                d[div] = 1
        else:
            div += 1
    if n in d:
        d[n] += 1
    elif n > 1:
        d[n] = 1
    r = []
    for k in d.keys():
        r.append((k, d[k]))
    return r

def get_pascal(r):
    if r == 1:
        return [1]
    elif r == 2:
        return [1,1]

    s = [1,1]
    while len(s) < r:
        ns = [1]
        for i in range(len(s) - 1):
            ns.append(s[i] + s[i + 1])
        ns = ns + [1]
        s = ns
    return s

def ncr(n, r):
    if r > n:
        return 0
    r = min(r, n-r)
    numer = reduce(op.mul, range(n, n-r, -1), 1)
    denom = reduce(op.mul, range(1, r+1), 1)
    return numer // denom

def get_cases(r,k):
    p = get_pascal(r)
    sum_v = 0
    for i,v in enumerate(p):
        sum_v += v * ncr(k,i + 1)
    #print(r, k, p, sum_v)
    return sum_v

def multiply(n,k):
    if n == 1: return 1
    f = factors(n)
    #print(f)
    s = 1
    for r in f:
        s *= get_cases(r[1], k)
    return s


Solve in Python:
## Task

Given a string, add the fewest number of characters possible from the front or back to make it a palindrome.

## Example

For the input `cdcab`, the output should be `bacdcab`

## Input/Output

Input is a string consisting of lowercase latin letters with length 3 <= str.length <= 10

The output is a palindrome string satisfying the task.

For s = `ab` either solution (`aba` or `bab`) will be accepted.

def is_palindrome(s):
    """Check if s is a palindrome"""
    return s == s[::-1]

def left_strip_palindrome(s):
    """Keeps stripping from left to find a palindrome. If not found return None.
    If found return the stripped characters in stripping order"""
    for i in range(len(s)-1):
        if is_palindrome(s[i:]):
            return s[:i]
    return None

def right_strip_palindrome(s):
    """Keeps stripping from right to find a palindrome. If not found return None.
    If found return the stripped characters in stripping order"""
    for i in range(-1,1-len(s),-1):
        if is_palindrome(s[:i]):
            return s[i:]

def build_palindrome(s):
    """Build a palindrome by adding the min number of characters possible."""
    lsp = left_strip_palindrome(s)
    rsp = right_strip_palindrome(s)
    # Answer is obtained by getting the stripped characters and add them in reverse order
    # to the opps direction they were stripped from in reverse direction.
    if lsp is not None:
        lsp_ans = s+lsp[::-1]
        if rsp is not None:
            rsp_ans = rsp[::-1]+s
            # In the case both left stripping and right stripping works, return the shortest answer.
            return min((lsp_ans,rsp_ans), key=len)
        return lsp_ans

    if rsp is not None:
        rsp_ans = rsp[::-1]+s
        return rsp_ans

    # If stripping does not work return the string with the copy of all characters
    # but the first concatenated at the starting in reverse order.
    return s[1:][::-1]+s


Solve in Python:
## Task

Implement a function which finds the numbers less than `2`, and the indices of numbers greater than `1` in the given sequence, and returns them as a pair of sequences.

Return a nested array or a tuple depending on the language:

* The first sequence being only the `1`s and `0`s from the original sequence.
* The second sequence being the indexes of the elements greater than `1` in the original sequence.

## Examples

```python
[ 0, 1, 2, 1, 5, 6, 2, 1, 1, 0 ] => ( [ 0, 1, 1, 1, 1, 0 ], [ 2, 4, 5, 6 ] )
```

Please upvote and enjoy!

def binary_cleaner(seq):
    list_a, list_b = [],[]
    for k,v in enumerate(seq):
        if v>1:
            list_b.append(k)
        else: list_a.append(v)
    return (list_a, list_b)


Solve in Python:
## Task

Let's say we have a positive integer, `$n$`. You have to find the smallest possible positive integer that when multiplied by `$n$`, becomes a perfect power of integer `$k$`. A perfect power of `$k$` is any positive integer that can be represented as `$a^k$`. For example if `$k = 2$`, then `$36$` is a perfect power of `$k$`, but `$27$` isn't.

## Examples

```python
n, k = 100, 3  return  10, #because 10*100 becomes 1000, and 1000 = 10**3
n, k = 36, 2   return   1, #because 36 is already a perfect square 6**2
n, k = 72, 4   return  18, #because 18*72 = 1296 = 6**4
```

**Notes:**
+ `$k, n \in \mathbb{N} $` and `$ 1 \lt n \lt 10^6,\text{ } 1 \lt k \lt 10 $`
+ However, the output may be way larger than `$10^6$`.

If you have trouble seeing the numbers, refresh your page ;-) Please rate this kata. All translations are welcome.

ABOVE: [If you see this:](https://imgur.com/TKY59S4), refresh your page.

from collections import Counter
def decompose(n):
    result = Counter()
    while n % 2 == 0:
        result[2] += 1
        n //= 2
    k = 3
    m = int(n ** 0.5)
    while k <= m:
        if n % k == 0:
            result[k] += 1
            n //= k
            m = int(n ** 0.5)
        else:
            k += 2
    if n > 1:
        result[n] += 1
    return result

def mul_power(n, k):
    r = 1
    for p, f in decompose(n).items():
        r *= p ** (-f % k)
    return r


Solve in Python:
## Task

Write a function that accepts two arguments and generates a sequence containing the integers from the first argument to the second inclusive.

## Input

Pair of integers greater than or equal to `0`. The second argument will always be greater than or equal to the first.

## Example

```python
generate_integers(2, 5) # --> [2, 3, 4, 5]
```

def generate_integers(m, n):
    return [i for i in range(m,n+1)]


Solve in Python:
## Task

Write a method `remainder` which takes two integer arguments, `dividend` and `divisor`, and returns the remainder when dividend is divided by divisor. Do NOT use the modulus operator (%) to calculate the remainder!

#### Assumption

Dividend will always be `greater than or equal to` divisor.

#### Notes

Make sure that the implemented `remainder` function works exactly the same as the `Modulus operator (%)`.

```if:java
`SimpleInteger` is a tiny and immutable implementation of an integer number. Its interface is a very small subset of the `java.math.BigInteger` API:

* `#add(SimpleInteger val)`
* `#subtract(SimpleInteger val)`
* `#multiply(SimpleInteger val)`
* `#divide(SimpleInteger val)`
* `#compareTo(SimpleInteger val)`
```


Solve in Python:
## Task

You are at position [0, 0] in maze NxN and you can **only** move in one of the four cardinal directions (i.e. North, East, South, West).  Return `true` if you can reach position [N-1, N-1] or `false` otherwise.

Empty positions are marked `.`. Walls are marked `W`. Start and exit positions are empty in all test cases.

## Path Finder Series:
-       [#1: can you reach the exit?](https://www.codewars.com/kata/5765870e190b1472ec0022a2)
-       [#2: shortest path](https://www.codewars.com/kata/57658bfa28ed87ecfa00058a)
-       [#3: the Alpinist](https://www.codewars.com/kata/576986639772456f6f00030c)
-       [#4: where are you?](https://www.codewars.com/kata/5a0573c446d8435b8e00009f)
-       [#5: there's someone here](https://www.codewars.com/kata/5a05969cba2a14e541000129)

def path_finder(maze):
    grid = [list(v) for v in maze.split('\n')]
    n = len(grid)
    end = (n-1, n-1)
    def search(x, y):
        if (x,y) == end:
            return True
        elif grid[x][y] == 'W':
            return False
        elif grid[x][y] == 'V':
            return False

        grid[x][y] = 'V'

        if ((x < n-1 and search(x+1, y))
            or (y > 0 and search(x, y-1))
            or (x > 0 and search(x-1, y))
            or (y < n-1 and search(x, y+1))):

            return True

        return False

    return search(0,0)


Solve in Python:
## Task

You are at position `[0, 0]` in maze NxN and you can **only** move in one of the four cardinal directions (i.e. North, East, South, West). Return the minimal number of steps to exit position `[N-1, N-1]` *if* it is possible to reach the exit from the starting position.  Otherwise, return `false` in **JavaScript**/**Python** and `-1` in **C++**/**C#**/**Java**.

Empty positions are marked `.`.  Walls are marked `W`.  Start and exit positions are guaranteed to be empty in all test cases.

## Path Finder Series:

-       [#1: can you reach the exit?](https://www.codewars.com/kata/5765870e190b1472ec0022a2)
-       [#2: shortest path](https://www.codewars.com/kata/57658bfa28ed87ecfa00058a)
-       [#3: the Alpinist](https://www.codewars.com/kata/576986639772456f6f00030c)
-       [#4: where are you?](https://www.codewars.com/kata/5a0573c446d8435b8e00009f)
-       [#5: there's someone here](https://www.codewars.com/kata/5a05969cba2a14e541000129)

def path_finder(maze):
    maze = maze.split('\n')
    x_, y_ = len(maze)-1, len(maze[0])-1

    DMap, exit = {(0,0):1}, (x_, y_)

    while 1:
        chkr = len(DMap)
        for x, r in enumerate(maze):
            for y, c in enumerate(r):

                if maze[x][y]=='.' and not DMap.get((x,y)):
                    ways = []
                    for e in ((x-1,y),(x+1,y),(x,y-1),(x,y+1)):
                        (not DMap.get(e) or ways.append(DMap[e]))

                    if ways:  DMap[(x,y)] = min(ways) + 1

        if chkr == len(DMap): break

    return DMap.get(exit, 1) - 1


Solve in Python:
## Task

You are given three non negative integers `a`, `b` and `n`, and making an infinite sequence just like fibonacci sequence, use the following rules:

- step 1: use `ab` as the initial sequence.
- step 2: calculate the sum of the last two digits of the sequence, and append it to the end of sequence.
- repeat step 2 until you have enough digits

Your task is to complete the function which returns the `n`th digit (0-based) of the sequence.

### Notes:

- `0 <= a, b <= 9`, `0 <= n <= 10^10`
- `16` fixed testcases
- `100` random testcases, testing for correctness of solution
- `100` random testcases, testing for performance of code
- All inputs are valid.
- Pay attention to code performance.

## Examples

For `a = 7, b = 8 and n = 9` the output should be `5`, because the sequence is:
```
78 -> 7815 -> 78156 -> 7815611 -> 78156112 -> 781561123 -> 7815611235 -> ...
```

and the 9th digit of the sequence is `5`.

---

For `a = 0, b = 0 and n = 100000000` the output should be `0`, because all the digits in this sequence are `0`.

def find(a,b,n):
    str_ = str(a) + str(b)
    for i in range(11 + 20):
        str_ += str(int(str_[-2]) + int(str_[-1]))

    return int(str_[n])  if n < 33 else int(str_[(n - 13) % 20 + 13])


Solve in Python:
## Task

You have to write three functions namely - `PNum, GPNum and SPNum` (JS, Coffee), `p_num, g_p_num and s_p_num` (Python and Ruby), `pNum, gpNum and spNum` (Java, C#), `p-num, gp-num and sp-num` (Clojure) - to check whether a given argument `n` is a Pentagonal, Generalized Pentagonal, or Square Pentagonal Number, and return `true` if it is and `false` otherwise.

### Description

`Pentagonal Numbers` - The nth pentagonal number Pn is the number of distinct dots in a pattern of dots consisting of the outlines of regular pentagons with sides up to n dots (means the side contains n number of dots), when the pentagons are overlaid so that they share one corner vertex.

> First few Pentagonal Numbers are: 1, 5, 12, 22...

`Generalized Pentagonal Numbers` - All the Pentagonal Numbers along with the number of dots inside the outlines of all the pentagons of a pattern forming a pentagonal number pentagon are called Generalized Pentagonal Numbers.

> First few Generalized Pentagonal Numbers are: 0, 1, 2, 5, 7, 12, 15, 22...

`Square Pentagonal Numbers` - The numbers which are Pentagonal Numbers and are also a perfect square are called Square Pentagonal Numbers.

> First few are: 1, 9801, 94109401...

### Examples

#### Note:
* Pn = Nth Pentagonal Number
* Gpn = Nth Generalized Pentagonal Number

     ^        ^          ^             ^                 ^
    P1=1     P2=5      P3=12         P4=22             P5=35   //Total number of distinct dots used in the Pattern
    Gp2=1    Gp4=5     Gp6=12        Gp8=22                    //All the Pentagonal Numbers are Generalised
             Gp1=0     Gp3=2         Gp5=7             Gp7=15  //Total Number of dots inside the outermost Pentagon

def p_num(n):
    r = (1 + (24*n+1)**.5) / 6
    return r.is_integer() and (3*(r**2) - r) / 2 == n

def g_p_num(n):
    r = ((1 + 24 * n) ** .5) % 6
    return r != 0 and r.is_integer()

s_p_num=lambda n:(n**.5).is_integer() and p_num(n) and g_p_num(n)


Solve in Python:
## Task

You will receive a string consisting of lowercase letters, uppercase letters and digits as input. Your task is to return this string as blocks separated by dashes (`"-"`). The elements of a block should be sorted with respect to the hierarchy listed below, and each block cannot contain multiple instances of the same character. Elements should be put into the first suitable block.

The hierarchy is:
1. lowercase letters (`a - z`), in alphabetical order
2. uppercase letters (`A - Z`), in alphabetical order
3. digits (`0 - 9`), in ascending order

## Examples

* `"21AxBz" -> "xzAB12"` - since input does not contain repeating characters, you only need 1 block
* `"abacad" -> "abcd-a-a"` - character "a" repeats 3 times, thus 3 blocks are needed
* `"" -> ""` - an empty input should result in an empty output
* `"hbh420sUUW222IWOxndjn93cdop69NICEep832" -> "bcdehjnopsxCEINOUW0234689-dhnpIUW239-2-2-2"` - a more sophisticated example

Good luck!

from string import ascii_letters, digits
from collections import Counter

ALPHABET = ascii_letters + digits
C_ALPHABET = Counter(ALPHABET)

def blocks(s):
    d = Counter(ALPHABET + s) - C_ALPHABET
    return "-".join("".join(x for x in d if d[x] > i) for i in range(max(d.values(), default=0)))


Solve in Python:
## Task

Your challenge is to write a function named `getSlope`/`get_slope`/`GetSlope` that calculates the slope of the line through two points.

## Input

```if:javascript,python
Each point that the function takes in is an array 2 elements long. The first number is the x coordinate and the second number is the y coordinate.
If the line through the two points is vertical or if the same point is given twice, the function should return `null`/`None`.
```

```if:csharp
`GetSlope` will take in two Point objects. If the line through the two points is vertical, or the two points are the same, return `null`.

The Point object:

~~~
public class Point : System.Object
{
  public double X;
  public double Y;

  public Point(double x, double y)
  {
    this.X = x;
    this.Y = y;
  }

  public override string ToString()
  {
    return $"({this.X}, {this.Y})";
  }

  public override bool Equals(object point)
  {
    // Typechecking
    if (point == null || point.GetType() != this.GetType())
    {
      return false;
    }

    return this.ToString() == point.ToString();
  }
}
~~~

```


Solve in Python:
## Task
 An `ATM` ran out of 10 dollar bills and only has `100, 50 and 20` dollar bills.

 Given an amount between `40 and 10000 dollars (inclusive)` and assuming that the ATM wants to use as few bills as possible, determinate the minimal number of 100, 50 and 20 dollar bills the ATM needs to dispense (in that order).

## Example

 For `n = 250`, the result should be `[2, 1, 0]`.

 For `n = 260`, the result should be `[2, 0, 3]`.

 For `n = 370`, the result should be `[3, 1, 1]`.

## Input/Output

 - `[input]` integer `n`
  Amount of money to withdraw. Assume that `n` is always exchangeable with `[100, 50, 20]` bills.
 - `[output]` integer array
  An array of number of `100, 50 and 20` dollar bills needed to complete the withdraw (in that order).


Solve in Python:
## Task
 In your favorite game, you must shoot a target with a water-gun to gain points. Each target can be worth a different amount of points.

 You are guaranteed to hit every target that you try to hit. You cannot hit consecutive targets though because targets are only visible for one second (one at a time) and it takes you a full second to reload your water-gun after shooting (you start the game already loaded).

 Given an array `vals` with the order of each target's point value, determine the maximum number of points that you can win.

## Example
 For `vals = [1, 2, 3, 4]`, the result should be `6`.

 your optimal strategy would be to let the first one pass and shoot the second one with value 2 and the 4th one with value 4 thus:

 `vals[1](2) + vals[3](4) = 6`

 For `vals = [5, 5, 5, 5, 5]`, the result should be `15`.

 your optimal strategy would be to shoot the 1st, 3rd and 5th value:

 `5 + 5 + 5 = 15`

 You haven't shoot the 2nd, 4th value because you are reloading your water-gun after shooting other values.

 Note that the value can be zero or negative, don't shoot them ;-)

 For `vals = [0, 0, -1, -1]`, the result should be `0`.

 For `vals = [5, -2, -9, -4]`, the result should be `5`.

 Shoot the first one is enough.

## Input/Output

 - `[input]` integer array `vals`

  The point values (negative or non-negative) of the targets (in order of appearance).

 - `[output]` an integer

  The maximum number of points that you can score.

def target_game(values):
    sum1 = 0
    sum2 = 0
    for value in values:
        sum1 = max(sum1 + value, sum2)
        sum1, sum2 = sum2, sum1
    return max(sum1, sum2)


Solve in Python:
## Task
 You are given an array of integers. On each move you are allowed to increase exactly one of its element by one. Find the minimal number of moves required to obtain a strictly increasing sequence from the input.

## Example

 For `arr = [1, 1, 1]`, the output should be `3`.

## Input/Output

 - `[input]` integer array `arr`

    Constraints:

    `3 ≤ inputArray.length ≤ 100,`

    `-10000 ≤ inputArray[i] ≤ 10000.`

 - `[output]` an integer

    The minimal number of moves needed to obtain a strictly increasing sequence from inputArray.

    It's guaranteed that for the given test cases the answer always fits signed 32-bit integer type.

def array_change(arr):
    m, s = 0, arr[0]
    for i in arr[1:]:
        if s >= i:
            s += 1
            m += s - i
        else:
            s = i
    return m


Solve in Python:
## Task
Given an array of strings, reverse them and their order in such way that their length stays the same as the length of the original inputs.

### Example:

```
Input:  {"I", "like", "big", "butts", "and", "I", "cannot", "lie!"}
Output: {"!", "eilt", "onn", "acIdn", "ast", "t", "ubgibe", "kilI"}
```

Good luck!

def reverse(a):
    b = ''.join(a)[::-1]
    l = []
    for i in a:
        l.append(b[:len(i)])
        b = b[len(i):]
    return l


Solve in Python:
## Task
In this kata you'll be given a string of English digits "collapsed" together, like this:

`zeronineoneoneeighttwoseventhreesixfourtwofive`

Your task is to split the string back to digits:

`zero nine one one eight two seven three six four two five`

## Examples
```
three -> three
eightsix -> eight six
fivefourseven -> five four seven
ninethreesixthree -> nine three six three
fivethreefivesixthreenineonesevenoneeight -> five three five six three nine one seven one eight
```

import re

def uncollapse(digits):
    return re.sub(r'(zero|one|two|three|four|five|six|seven|eight|nine)',r'\1 ',digits).strip()


Solve in Python:
## Task
To charge your mobile phone battery, do you know how much time it takes from 0% to 100%? It depends on your cell phone battery capacity and the power of the charger. A rough calculation method is:

```
0% --> 85%  (fast charge)
(battery capacity(mAh) * 85%) / power of the charger(mA)

85% --> 95% (decreasing charge)
(battery capacity(mAh) * 10%) / (power of the charger(mA) * 50%)

95% --> 100% (trickle charge)
(battery capacity(mAh) * 5%) / (power of the charger(mA) * 20%)
```
For example: Your battery capacity is 1000 mAh and you use a charger 500 mA,  to charge your mobile phone battery from 0% to 100% needs time:

```
0% --> 85%  (fast charge) 1.7 (hour)

85% --> 95% (decreasing charge) 0.4 (hour)

95% --> 100% (trickle charge) 0.5 (hour)

total times = 1.7 + 0.4 + 0.5 = 2.6 (hour)
```

 Complete function `calculateTime` that accepts two arguments `battery` and `charger`, return how many hours can charge the battery from 0% to 100%. The result should be a number, round to 2 decimal places (In Haskell, no need to round it).

def calculate_time(battery,charger):
    return round(1e-10 + 1.3 * battery / charger, 2)


Solve in Python:
## Task
You need to implement two functions, `xor` and `or`, that replicate the behaviour of their respective operators:

- `xor` = Takes 2 values and returns `true` if, and only if, one of them is truthy.
- `or` = Takes 2 values and returns `true` if either one of them is truthy.

When doing so, **you cannot use the or operator: `||`**.

# Input
- Not all input will be booleans - there will be truthy and falsey values [the latter including also empty strings and empty arrays]
- There will always be 2 values provided

## Examples
- `xor(true, true)` should return `false`
- `xor(false, true)` should return `true`
- `or(true, false)` should return `true`
- `or(false, false)` should return `false`

def func_or(a,b):
    if a:
        return True
    else:
        return not(not b)

def func_xor(a,b):
    if a:
        return not b
    else:
        return not(not b)


Solve in Python:
## Task

Using `n` as a parameter in the function `pattern`, where `n>0`, complete the codes to get the pattern (take the help of examples):

**Note:** There is no newline in the end (after the pattern ends)

### Examples

`pattern(3)` should return `"1\n1*2\n1**3"`, e.g. the following:
```
1
1*2
1**3
```
`pattern(10):` should return the following:
```
1
1*2
1**3
1***4
1****5
1*****6
1******7
1*******8
1********9
1*********10
```

def pattern(n):
    if n == 1:
        return "1"
    elif n > 1:
        return pattern(n-1) + "\n1{}{}".format("*" * (n-1), n)


def pattern(n):
    lines = []
    for i in range(1, n + 1):
        line = ' ' * (n - i)
        line += ''.join(str(j % 10) for j in range(1, i + 1))
        line += line[::-1][1:]
        lines.append(line)
    return '\n'.join(lines + lines[::-1][1:])


Solve in Python:
## Task:

You have to write a function `pattern` which returns the following Pattern(See Examples) upto desired number of rows.

* Note:`Returning` the pattern is not the same as `Printing` the pattern.

### Parameters:

    pattern(        n        ,        x        );
                    ^                 ^
                    |                 |
             Term upto which   Number of times
              Basic Pattern     Basic Pattern
                should be         should be
                 created          repeated
                                horizontally

* Note: `Basic Pattern` means what we created in [Complete the pattern #12]("http://www.codewars.com/kata/558ac25e552b51dbc60000c3")
### Rules/Note:

* The pattern should be created using only unit digits.
* If `n < 1` then it should return "" i.e. empty string.
* If `x <= 1` then the basic pattern should not be repeated horizontally.
* `The length of each line is same`, and is equal to the length of longest line in the pattern.
* Range of Parameters (for the sake of CW Compiler) :
  + `n ∈ (-∞,50]`
  + `x ∈ (-∞,25]`
* If only one argument is passed then the function `pattern` should run as if `x <= 1`.
* The function `pattern` should work when extra arguments are passed, by ignoring the extra arguments.

###Examples:

* Having Two Arguments-

 + pattern(4,3):

        1     1     1     1
         2   2 2   2 2   2
          3 3   3 3   3 3
           4     4     4
          3 3   3 3   3 3
         2   2 2   2 2   2
        1     1     1     1

  + pattern(10,2):

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

def pattern(n, *args):
    if n < 1:
        return ''
    x = 1 if len(args) == 0 else max(args[0], 1)
    width, height = (1 + 2*(n-1)*x), 2*n - 1
    pict = [[' '] * width for _ in range(height)]
    x_positions = set()
    for x in range(0, width, 2*(n-1)):
        x_positions.add(('r', x))
        x_positions.add(('l', x))
    for y, n in enumerate(list(range(1, n+1)) + list(range(n-1, 0, -1))):
        new_x_positions = set()
        for d, x in x_positions:
            pict[y][x] = str(n)[-1]
            if d == 'r' and x + 1 < width:
                new_x_positions.add((d, x+1))
            elif d == 'l' and 0 <= x - 1:
                new_x_positions.add((d, x-1))
        x_positions = new_x_positions
    return '\n'.join(''.join(p) for p in pict)


def pattern(n):
    return '\n'.join(''.join(str((n - min(i, j))%10) for j in range(n)) for i in range(n))


Solve in Python:
## Task:

Your task is to write a function which returns the sum of following series upto nth term(parameter).

    Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +...

## Rules:

* You need to round the answer to 2 decimal places and return it as String.

* If the given value is 0 then it should return 0.00

* You will only be given Natural Numbers as arguments.

## Examples:

    SeriesSum(1) => 1 = "1.00"
    SeriesSum(2) => 1 + 1/4 = "1.25"
    SeriesSum(5) => 1 + 1/4 + 1/7 + 1/10 + 1/13 = "1.57"

**NOTE**: In PHP the function is called `series_sum()`.

import math
def series_sum(n):
    # Happy Coding ^_^
    result = 0.00
    for i in (list(range(0, n))):
        result += 1.00 / (1.00 + (3.00 * float(i)) )
    return "{:.2f}".format(result)


Solve in Python:
## Task:
You have to create a function `isPronic` to check whether the argument passed is a Pronic Number and return true if it is & false otherwise.

### Description:

`Pronic Number` -A pronic number, oblong number, rectangular number or heteromecic number, is a number which is the product of two consecutive integers, that is, n(n + 1).

> The first few Pronic Numbers are - 0, 2, 6, 12, 20, 30, 42...

### Explanation:

      0 = 0 × 1   // ∴  0 is a Pronic Number
      2 = 1 × 2   // ∴  2 is a Pronic Number
      6 = 2 × 3   // ∴  6 is a Pronic Number
     12 = 3 × 4   // ∴ 12 is a Pronic Number
     20 = 4 × 5   // ∴ 20 is a Pronic Number
     30 = 5 × 6   // ∴ 30 is a Pronic Number
     42 = 6 × 7   // ∴ 42 is a Pronic Number

pronics = {i * (i+1) for i in range(1000)}

def is_pronic(n):
    return n in pronics


Solve in Python:
## Task:
You have to write a function `pattern` which returns the following Pattern (See Pattern & Examples) upto `n` number of rows.

* Note: `Returning` the pattern is not the same as `Printing` the pattern.

### Rules/Note:
* If `n < 1` then it should return "" i.e. empty string.
* There are `no whitespaces` in the pattern.

### Pattern:

    (n)(n-1)(n-2)...4321
    (n)(n-1)(n-2)...432
    (n)(n-1)(n-2)...43
    (n)(n-1)(n-2)...4
    ...............
    ..............
    (n)(n-1)(n-2)
    (n)(n-1)
    (n)

### Examples:

* pattern(4):

      4321
      432
      43
      4

* pattern(11):

      1110987654321
      111098765432
      11109876543
      1110987654
      111098765
      11109876
      1110987
      111098
      11109
      1110
      11

~~~if-not:cfml
* Hint: Use \n in string to jump to next line
~~~
~~~if:cfml
* Hint: Use chr(10) in string to jump to next line
~~~

[List of all my katas]("http://www.codewars.com/users/curious_db97/authored")

def pattern(n):
    return '\n'.join(''.join(map(str, range(n, stop, -1))) for stop in range(n))


Solve in Python:
## Task:
You have to write a function `pattern` which returns the following Pattern(See Pattern & Examples) upto `n` number of rows.

* Note:`Returning` the pattern is not the same as `Printing` the pattern.

#### Rules/Note:
* If `n < 1` then it should return "" i.e. empty string.
* There are `no whitespaces` in the pattern.

### Pattern:

    1
    22
    333
    ....
    .....
    nnnnnn

### Examples:

+ pattern(5):

      1
      22
      333
      4444
      55555

* pattern(11):

      1
      22
      333
      4444
      55555
      666666
      7777777
      88888888
      999999999
      10101010101010101010
      1111111111111111111111

```if-not:cfml
* Hint: Use \n in string to jump to next line
```
```if:cfml
* Hint: Use Chr(10) in string to jump to next line
```
[List of all my katas]('http://www.codewars.com/users/curious_db97/authored')

def pattern(n):
    return "".join(list([str(x)*x+"\n" if n > x else str(x)*x for x in range(1,n+1)]))


Solve in Python:
## Terminal game move function

In this game, the hero moves from left to right. The player rolls the dice and moves the number of spaces indicated by the dice **two times**.

~~~if-not:sql
Create a function for the terminal game that takes the current position of the hero and the roll (1-6) and return the new position.
~~~
~~~if:sql
In SQL, you will be given a table `moves` with columns `position` and `roll`. Return a table which uses the current position of the hero and the roll (1-6) and returns the new position in a column `res`.
~~~

### Example:
```python
move(3, 6) should equal 15
```

```if:bf
### BF:

Since this is an 8kyu kata, you are provided a modified runBF function, numericRunBF, that automatically parses input and output for your ease.

See the sample test cases to see what I mean: You can simply input two numbers and get a number as output (unless you're doing something wrong), so it should be convenient for you to modify the tests as you wish.

Oh, and you won't have to worry about overflow, the correct answer will never be higher than 255. :)
```

def move(position, roll):
    n = roll * 2 + position
    return n


Solve in Python:
## The Problem

James is a DJ at a local radio station. As it's getting to the top of the hour, he needs to find a song to play that will be short enough to fit in before the news block. He's got a database of songs that he'd like you to help him filter in order to do that.

## What To Do

Create `longestPossible`(`longest_possible` in python and ruby) helper function that takes 1 integer argument which is a maximum length of a song in seconds.

`songs` is an array of objects which are formatted as follows:

```python
{'artist': 'Artist', 'title': 'Title String', 'playback': '04:30'}
```

You can expect playback value to be formatted exactly like above.

Output should be a title of the longest song from the database that matches the criteria of not being longer than specified time. If there's no songs matching criteria in the database, return `false`.

songs = [{'artist': 'Marillion', 'title': 'Keyleigh', 'playback': '03:36'}, {'artist': 'Pink Floyd', 'title': 'Time', 'playback': '06:48'}, {'artist': 'Rush', 'title': 'YYZ', 'playback': '04:27'}, {'artist': 'Bonobo', 'title': 'Days To Come', 'playback': '03:50'}, {'artist': 'Coldplay', 'title': 'Yellow', 'playback': '04:32'}, {'artist': 'Bloc Party', 'title': 'Like Eating Glass', 'playback': '04:22'}, {'artist': 'The Killers', 'title': 'For Reasons Unknown', 'playback': '03:30'}, {'artist': 'Arctic Monkeys', 'title': 'Teddy Picker', 'playback': '03:25'}, {'artist': 'Joe Satriani', 'title': 'Surfing With The Alien', 'playback': '04:34'}]
def calculate_seconds(s):
    minutes, seconds = [int(x) for x in s.split(':')]
    return minutes * 60 + seconds

def longest_possible(playback):
    candidates = [song for song in songs if calculate_seconds(song['playback']) <= playback]
    return sorted(candidates, key=lambda x: calculate_seconds(x['playback']), reverse=True)[0]['title'] if len(candidates) > 0 else False


Solve in Python:
## The Riddle

The King of a small country invites 1000 senators to his annual party. As a tradition, each senator brings the King a bottle of wine. Soon after, the Queen discovers that one of the senators is trying to assassinate the King by giving him a bottle of poisoned wine. Unfortunately, they do not know which senator, nor which bottle of wine is poisoned, and the poison is completely indiscernible.

However, the King has 10 lab rats. He decides to use them as taste testers to determine which bottle of wine contains the poison. The poison when taken has no effect on the rats, until exactly 24 hours later when the infected rats suddenly die. The King needs to determine which bottle of wine is poisoned by tomorrow, so that the festivities can continue as planned.

Hence he only has time for one round of testing, he decides that each rat tastes multiple bottles, according to a certain scheme.

## Your Task

You receive an array of integers (`0 to 9`), each of them is the number of a rat which died after tasting the wine bottles. Return the number of the bottle (`1..1000`) which is poisoned.

**Good Luck!**

*Hint: think of rats as a certain representation of the number of the bottle...*

def find(r):
    return sum(2**i for i in r)


Solve in Python:
## The Story
Green Lantern's long hours of study and practice with his ring have really paid off -- his skills, focus, and control have improved so much that now he can even use his ring to update and redesign his web site. Earlier today he was focusing his will and a beam from his ring upon the Justice League web server, while intensely brainstorming and visualizing in minute detail different looks and ideas for his web site, and when he finished and reloaded his home page, he was absolutely thrilled to see that among other things it now displayed

~~~~
In brightest day, in blackest night,
There's nothing cooler than my site!
~~~~

in his favorite font in very large blinking green letters.

The problem is, Green Lantern's ring has no power over anything yellow, so if he's experimenting with his web site and accidentally changes some text or background color to yellow, he will no longer be able to make any changes to those parts of the content or presentation (because he doesn't actually know any HTML, CSS, programming languages, frameworks, etc.) until he gets a more knowledgable friend to edit the code for him.

## Your Mission
You can help Green Lantern by writing a function that will replace any color property values that are too yellow with shades of green or blue-green. Presumably at a later time the two of you will be doing some testing to find out at exactly which RGB values yellow stops being yellow and starts being off-white, orange, brown, etc. as far as his ring is concerned, but here's the plan to get version 1.0 up and running as soon as possible:

Your function will receive either an HTML color name or a six-digit hex color code. (You're not going to bother with other types of color codes just now because you don't think they will come up.) If the color is too yellow, your function needs to return a green or blue-green shade instead, but if it is not too yellow, it needs to return the original color name or hex color code unchanged.

### HTML Color Names
(If don't know what HTML color names...

def yellow_be_gone(s):
    d = {'gold':'ForestGreen','khaki':'LimeGreen','lemonchiffon':'PaleGreen', 'lightgoldenrodyellow':'SpringGreen','lightyellow':'MintCream','palegoldenrod':'LightGreen','yellow':'Lime'}
    if s.lower() in d: return d.get(s.lower())
    if not s.startswith('#'): return s
    flag = any(i.isupper() for i in s)
    r,g,b = map(lambda x: int(x,16), (s[1:3],s[3:5],s[5:8]))
    if r>b and g>b:
        x,y,z = sorted((r,g,b))
        r,g,b = x,z,y
    c = '#' + ''.join(format(i,'02x') for i in (r,g,b))
    return c.upper() if flag else c


Solve in Python:
## The galactic games have begun!

It's the galactic games! Beings of all worlds come together to compete in several interesting sports, like nroogring, fredling and buzzing (the beefolks love the last one). However, there's also the traditional marathon run.

Unfortunately, there have been cheaters in the last years, and the committee decided to place sensors on the track. Committees being committees, they've come up with the following rule:

> A sensor should be placed every 3 and 5 meters from the start, e.g.
> at 3m, 5m, 6m, 9m, 10m, 12m, 15m, 18m….

Since you're responsible for the track, you need to buy those sensors. Even worse, you don't know how long the track will be! And since there might be more than a single track, and you can't be bothered to do all of this by hand, you decide to write a program instead.

## Task
Return the sum of the multiples of 3 and 5 __below__ a number. Being the _galactic_ games, the tracks can get rather large, so your solution should work for _really_ large numbers (greater than 1,000,000).

### Examples
```python
solution (10) # => 23 = 3 + 5 + 6 + 9
solution (20) # => 78 = 3 + 5 + 6 + 9 + 10 + 12 + 15 + 18
```

val = lambda x: x*(x+1)>>1

def solution(number):
    res1 =  3 * val((number-1) //  3)
    res2 =  5 * val((number-1) //  5)
    res3 = 15 * val((number-1) // 15)
    return res1 + res2 - res3


Solve in Python:
## The story you are about to hear is true
Our cat, Balor, sadly died of cancer in 2015.

While he was alive, the three neighborhood cats Lou, Mustache Cat, and Raoul all recognized our house and yard as Balor's territory, and would behave respectfully towards him and each other when they would visit.

But after Balor died, gradually each of these three neighborhood cats began trying to claim his territory as their own, trying to drive the others away by growling, yowling, snarling, chasing, and even fighting, when one came too close to another, and no human was right there to distract or extract one of them before the situation could escalate.

It is sad that these otherwise-affectionate animals, who had spent many afternoons peacefully sitting and/or lying near Balor and each other on our deck or around our yard, would turn on each other like that. However, sometimes, if they are far enough away from each other, especially on a warm day when all they really want to do is pick a spot in the sun and lie in it, they will ignore each other, and once again there will be a Peaceable Kingdom.

## Your Mission
In this, the first and simplest of a planned trilogy of cat katas :-), all you have to do is determine whether the distances between any visiting cats are large enough to make for a peaceful afternoon, or whether there is about to be an altercation someone will need to deal with by carrying one of them into the house or squirting them with water or what have you.

As input your function will receive a list of strings representing the yard as a grid, and an integer representing the minimum distance needed to prevent problems (considering the cats' current states of sleepiness). A point with no cat in it will be represented by a "-" dash. Lou, Mustache Cat, and Raoul will be represented by an upper case L, M, and R respectively. At any particular time all three cats may be in the yard, or maybe two, one, or even none.

If the number of cats in the yard is one or none, or if the distances between all cats are...

def peaceful_yard(yard, min_distance):
    # Extract cat positions
    cats = {ch: (r, c) for r, row in enumerate(yard) for c, ch in enumerate(row) if ch != "-"}
    if len(cats) < 2:
        return True
    # Extract coordinates amd calculate euclidean distances between them
    coords = list(cats.values())
    euc_dist = lambda x, y: ((x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2) ** 0.5
    r = list(range(len(coords)))
    dists = [euc_dist(coords[i], coords[j]) for i in r for j in r if i < j]
    # Check minimum distance against required minimum
    return min_distance <= min(dists)


Solve in Python:
## Welcome to my (amazing) kata!

You are given a gigantic number to decode.  Each number is a code that alternates in a pattern between encoded text and a smaller, encoded number.  The pattern's length varies with every test, but the alternation between encoded text and an encoded number will always be there.  Following this rule, each number tested begins with encoded text and ends with an encoded number.

## How the encoding works

Now, we should probably review how the string of numbers is formed - considering you have to unform it. So, first, some text is taken, and encoded.  The system of encoding is taking each letter's position in the alphabet and adding 100 to it.  For example, `m` in the real text would be `113` in the code-number.

After the text, there is a binary number.  You should convert this number to a normal, base 10 decimal (all of them can be converted into whole, non-negative numbers).

Separating encoded text and encoded numbers, there is a `98`.  Because the numbers are in binary, the only digits they use are '0' and '1', and each letter of the alphabet, encoded, is between 101-127, all instances of `98` are to indicate a separation between encoded text and encoded numbers.  There may also be a `98` at the very end of the number.

When you return your final answer, the text and numbers should always be separated by a comma (`,`)

## Example

```python
decode(103115104105123101118119981001098113113113981000) = "codewars, 18, mmm, 8"
```
The part of the code until the first `98` can be decoded to `"codewars"`.  `10010` is binary for `18`. `113113113` translates to `"mmm"`.  And `1000` is binary for `8`.

Here is a visualisation of the example:

Good luck!

import re
def decode(number):
    arr = []
    for match in re.finditer(r'((?:1[01][1-9]|110|12[0-7])+)98([01]+)(?:98)?', str(number)):
        arr.append(re.sub(r'\d{3}', lambda m: chr(int(m.group()) - 4), match.group(1)))
        arr.append(str(int(match.group(2), 2)))
    return ', '.join(arr)


Solve in Python:
## Witamy!

You are in Poland and want to order a drink. You need to ask "One beer please": "Jedno piwo poprosze"

``` java
Translator.orderingBeers(1) = "Jedno piwo poprosze"
```

But let's say you are really thirsty and want several beers. Then you need to count in Polish. And more difficult, you need to understand the Polish grammar and cases (nominative, genitive, accustative and more).

## The grammar

In English, the plural of "beer" is simply "beers", with an "s".

In Polish, the plural of "piwo" (nominative singular) is "piw" (genitive plural) or "piwa" (nominative plural). It depends!

The rules:

* usually the plural is genitive: "piw"
* but after the numerals 2, 3, 4, and compound numbers ending with them (e.g. 22, 23, 24), the noun is plural and takes the same case as the numeral, so nominative: "piwa"
* and exception to the exception: for 12, 13 and 14, it's the genitive plural again: "piw" (yes, I know, it's crazy!)

## The numbers

From 0 to 9:

    "zero", "jeden", "dwa", "trzy", "cztery", "piec", "szesc" , "siedem", "osiem", "dziewiec"

From 10 to 19 it's nearly the same, with "-ascie" at the end:

    "dziesiec", "jedenascie", "dwanascie", "trzynascie", "czternascie", "pietnascie", "szesnascie", "siedemnascie", "osiemnascie", "dziewietnascie"

Tens from 10 to 90 are nearly the same, with "-ziesci" or "ziesiat" at the end:

    "dziesiec", "dwadziescia", "trzydziesci", "czterdziesci", "piecdziesiat", "szescdziesiat", "siedemdziesiat", "osiemdziesiat", "dziewiecdziesiat"

Compound numbers are constructed similarly to English: tens + units. For example, 22 is "dwadziescia dwa".

"One" could be male ("Jeden"), female ("Jedna") or neuter ("Jedno"), which is the case for "beer" (piwo). But all other numbers are invariant, even if ending with "jeden".

Ah, and by the way, if you don't want to drink alcohol (so no beers are ordered), ask for mineral water instead: "Woda mineralna".

Note: if the number of beers is outside your (limited) Polish knowledge (0-99), raise an error!

---
More about...

def ordering_beers(beers):
    num_0_to_19_in_polish=("zero", "jeden", "dwa", "trzy", "cztery", "piec", "szesc" , "siedem", "osiem", "dziewiec","dziesiec", "jedenascie", "dwanascie", "trzynascie", "czternascie", "pietnascie", "szesnascie", "siedemnascie", "osiemnascie", "dziewietnascie")
    tens_10_to_90_in_polish=("dziesiec", "dwadziescia", "trzydziesci", "czterdziesci", "piecdziesiat", "szescdziesiat", "siedemdziesiat", "osiemdziesiat", "dziewiecdziesiat")
    if beers==0:
        number="Woda"
        beverage="mineralna"
    elif beers==1:
        number="Jedno"
        beverage="piwo"
    elif beers<=19 and beers>0:
        number=num_0_to_19_in_polish[beers]
        if beers in (2,3,4):
            beverage="piwa"
        else:
            beverage="piw"
    elif beers<=99 and beers>0:
        tens=beers//10
        remains=beers%10
        if remains==0:
            number=tens_10_to_90_in_polish[tens-1]
        else:
            number=tens_10_to_90_in_polish[tens-1]+" "+num_0_to_19_in_polish[remains]
        if remains in (2,3,4):
            beverage="piwa"
        else:
            beverage="piw"
    else:
        raise Exception("输入变量越界")
    number1=number.capitalize()
    return number1+" "+beverage+" poprosze"


Solve in Python:
## Your Job

  Find the sum of all multiples of `n` below `m`

## Keep in Mind

  * `n` and `m` are natural numbers (positive integers)
  * `m` is **excluded** from the multiples

## Examples

def sum_mul(n, m):
    return sum(range(n, m, n)) if n > 0 < m else 'INVALID'