Solve in Python:
# Task
A masked number is a string that consists of digits and one asterisk (`*`) that should be replaced by exactly one digit. Given a masked number `s`, find all the possible options to replace the asterisk with a digit to produce an integer divisible by 6.

# Input/Output

`[input]` string `s`

A masked number.

`1 ≤ inputString.length ≤ 10000.`

`[output]` a string array

Sorted array of strings representing all non-negative integers that correspond to the given mask and are divisible by 6.

# Example

For `s = "1*0"`, the output should be `["120", "150", "180"].`

For `s = "*1"`, the output should be `[].`

For `s = "1234567890123456789012345678*0"`,

the output should be
```
[
"123456789012345678901234567800",
"123456789012345678901234567830",
"123456789012345678901234567860",
"123456789012345678901234567890"]```
As you can see, the masked number may be very large ;-)

def is_divisible_by_6(s):
  return [str(n) for n in [int(s.replace('*', str(i))) for i in range(10)] if n % 6 == 0]


Solve in Python:
# Task
A newspaper is published in Walrusland. Its heading is `s1` , it consists of lowercase Latin letters.

Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string.

After that walrus erase several letters from this string in order to get a new word `s2`.

It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters.

For example, the heading is `"abc"`. If we take two such headings and glue them one to the other one, we get `"abcabc"`. If we erase the 1st letter("a") and 5th letter("b"), we get a word `"bcac"`.

Given two string `s1` and `s2`, return the least number of newspaper headings `s1`, which Fangy will need to receive the word `s2`. If it is impossible to get the word `s2` in the above-described manner, return `-1`.

# Example

For `s1="abc", s2="bcac"`, the output should be `2`.

```
"abcabc" --> "bcac"
 x   x
```

For `s1="abc", s2="xyz"`, the output should be `-1`.

It's impossible to get the word `s2`.

def buy_newspaper(s1, s2):
    t, i = 0, len(s1)
    for c in s2:
        i = s1.find(c, i) + 1
        if not i:
            t += 1
            i = s1.find(c) + 1
            if not i: return -1
    return t


Solve in Python:
# Task
After a long night (work, play, study) you find yourself sleeping on a bench in a park. As you wake up and try to figure out what happened you start counting trees.

You notice there are different tree sizes but there's always one size which is unbalanced. For example there are 2 size 2, 2 size 1 and 1 size 3. (then the size 3 is unbalanced)

Given an array representing different tree sizes. Which one is the unbalanced size.

Notes:
```
There can be any number of sizes but one is always unbalanced
The unbalanced size is always one less than the other sizes
The array is not ordered (nor the trees)```

# Examples

For `trees = [1,1,2,2,3]`, the result should be `3`.

For `trees = [2,2,2,56,56,56,8,8]`, the result should be `8`.

For `trees = [34,76,12,99,64,99,76,12,34]`, the result should be `64`.

# Input/Output

- `[input]` integer array `trees`

Array representing different tree sizes

- `[output]` an integer

The size of the missing tree.

def find_the_missing_tree(trees):
    return -sum(trees) % sum(set(trees))


Solve in Python:
# Task
Consider an array of integers `a`. Let `min(a)` be its minimal element, and let `avg(a)` be its mean.

Define the center of the array `a` as array `b` such that:

```
- b is formed from a by erasing some of its elements.
- For each i, |b[i] - avg(a)| < min(a).
- b has the maximum number of elements among all the arrays
  satisfying the above requirements.
```

Given an array of integers, return its center.

# Input/Output

`[input]` integer array `a`

 Unsorted non-empty array of integers.

`2 ≤ a.length ≤ 50,`

`1 ≤ a[i] ≤ 350.`

`[output]` an integer array

# Example

For `a = [8, 3, 4, 5, 2, 8]`, the output should be `[4, 5]`.

Here `min(a) = 2, avg(a) = 5`.

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

Here `min(a) = 1, avg(a) = 1.75`.

def array_center(arr):
    m, a = min(arr), (sum(arr) / len(arr))
    return [n for n in arr if abs(n - a) < m]


Solve in Python:
# Task
Follow the instructions in each failing test case to write logic that calculates the total price when ringing items up at a cash register.

# Purpose
Practice writing maintainable and extendable code.

# Intent
This kata is meant to emulate the real world where requirements change over time. This kata does not provide a specification for the final end-state up front. Instead, it walks you through a series of requirements, modifying and extending them via test cases as you go. This kata is about the journey, not the destination. Your ability to write maintainable and extendable code will affect how difficult this kata is.

# Provided Utility Function
You may use the following preloaded function:
```python
get_price(item)
"""Accepts a str specifying an item. Returns the price of
the item (float) or raises a KeyError if no price is available.

Example:

    >>> get_price(apple)
    0.4
"""
```

# Acknowledgement
Inspired by http://codekata.com/kata/kata01-supermarket-pricing/. To get the most benefit from this kata, I would recommend visiting that page only after completing, not before.

import re
class Checkout(object):
    def __init__(self,sales={}):
        self.total=0.0
        self.items={}
        self.sales={}
        self.buyget={}
        self.off={}
        for k,v in sales.items():
            if 'for' in v:
                x,y=v.split('for')
                self.sales[k]=(int(x),float(y))
            elif 'buy' in v:
                x,y=v.split('get')
                self.buyget[k]=(int(x.replace('buy','')),int(y))
            elif 'off' in v:
                x,y=v.split('off')
                self.off[k]=(float(x),int(y.replace('ormore','')))

    def scan(self,item,q=1):
        self.items[item]=self.items.get(item,0)+q
        self.total+=get_price(item)*q
        if item in self.sales:
            if self.sales[item][0]<=self.items[item]:
                x=self.items[item]//self.sales[item][0]
                self.total+=x*self.sales[item][1]-x*self.sales[item][0]*get_price(item)
                self.items[item]%=self.sales[item][0]
        elif item in self.buyget:
            x,y=self.buyget[item]
            if self.items[item]>=x+y:
                z=self.items[item]//(x+y)
                self.total-=z*y*get_price(item)
            self.items[item]%=(x+y)
        elif item in self.off:
            if self.items[item]==self.off[item][1]:
                self.total-=self.off[item][0]
        self.total=round(self.total,2)


Solve in Python:
# Task
For the given set `S` its powerset is the set of all possible subsets of `S`.

Given an array of integers nums, your task is to return the powerset of its elements.

Implement an algorithm that does it in a depth-first search fashion. That is, for every integer in the set, we can either choose to take or not take it. At first, we choose `NOT` to take it, then we choose to take it(see more details in exampele).

# Example

For `nums = [1, 2]`, the output should be `[[], [2], [1], [1, 2]].`

Here's how the answer is obtained:
```
don't take element 1
----don't take element 2
--------add []
----take element 2
--------add [2]
take element 1
----don't take element 2
--------add [1]
----take element 2
--------add [1, 2]```

For `nums = [1, 2, 3]`, the output should be

`[[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]`.

# Input/Output

`[input]` integer array `nums`

Array of positive integers, `1 ≤ nums.length ≤ 10`.

[output] 2D integer array

The powerset of nums.

def powerset(nums):
    if len(nums)==1:
        return [[],nums]
    s=powerset(nums[1:])
    for a in s[:]:
        s.append([nums[0]]+a)
    return s


Solve in Python:
# Task
Get the digits sum of `n`th number from the [Look-and-Say sequence](http://en.wikipedia.org/wiki/Look-and-say_sequence)(1-based).

`1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, ...`

# Input/Output

`[input]` integer `n`

`n`th number in the sequence to get where `1 <= n <= 55`  and `n=1 is "1"`.

[output] an integer

The sum of digits in `n`th number from the `Look-and-Say` sequence.

# Example

For `n = 2`, the output shoule be 2.

`"11" --> 1 + 1 --> 2`

For `n = 3`, the output shoule be 3.

`"21" --> 2 + 1 --> 3`

For `n = 4`, the output shoule be 5.

`"1211" --> 1 + 2 + 1 + 1 --> 5`

def look_and_say_and_sum(n):
    oldstr = "1"
    newstr = ""
    total = 1
    i = 1
    while (i < n):
        j = 0
        total = 0
        newstr = ""
        length = len(oldstr)
        while (j < length):
            look = oldstr[j]
            count = 0
            while (j < length and look == oldstr[j]):
                count += 1
                j += 1
            total += count
            total += int(look)
            newstr += str(count)
            newstr += look
        oldstr = newstr
        i += 1
    return (total)


Solve in Python:
# Task
Given a number `n`, return a string representing it as a sum of distinct powers of three, or return `"Impossible"` if that's not possible to achieve.

# Input/Output

`[input]` integer `n`

A positive integer n.

`1 ≤ n ≤ 10^16`.

`[output]` a string

A string representing the sum of powers of three which adds up to n, or `"Impossible"` if there is no solution. If the solution does exist, it should be return as `"3^a1+3^a2+ ... +3^an"`, where ai for `0 ≤ i ≤ n` represents the corresponding exponent of the term. The terms in the string should also be sorted in descending order, meaning that higher powers should appear before the lower ones in the string (`"3^0+3^1"` is incorrect, whereas `"3^1+3^0"` is correct).

# Example

For `n = 4`, the output should be `"3^1+3^0"`.

4 can be represented as `3+1` which is in fact 3 to the power of 1 plus 3 to the power of 0

For `n = 2`, the output should be `"Impossible"`.

There is no way to represent 2 as a sum of `distinct powers` of 3.

from math import log
def sum_of_threes(n):
    out = []
    while n > 0:
        next = int(log(n, 3))
        next += 1 if pow(3, next+1) <= n else 0
        if out and next == out[-1]: return "Impossible"
        out.append(next)
        n -= pow(3, next)

    return '+'.join("3^{}".format(i) for i in out)


Solve in Python:
# Task
Given an array `arr`, find the maximal value of `k` such `a[i] mod k` = `a[j] mod k` for all valid values of i and j.

If it's impossible to find such number (there's an infinite number of `k`s), return `-1` instead.

# Input/Output

`[input]` integer array `arr`

A non-empty array of positive integer.

`2 <= arr.length <= 10`

`1 <= arr[i] <= 100`

`[output]` an integer

The maximum value of `k` or `-1` if there is none.

# Example

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

`1` is the only k which satisfies the given conditions.

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

`1 % k = 1` for `any k > 1`, so it's impossible to find the maximum.

For `arr = [5, 2, 8]`, the output should be `3`.

`5 % 3 == 2 % 3 == 8 % 3 == 2`

finding_k=lambda a: max([k for k in range(1, max(a)) if eval('=='.join([str(z)+'%'+str(k) for z in a]))], default=-1)


Solve in Python:
# Task
Given an initial string `s`, switch case of the minimal possible number of letters to make the whole string written in the upper case or in the lower case.

# Input/Output

`[input]` string `s`

String of odd length consisting of English letters.

3 ≤ inputString.length ≤ 99.

`[output]` a string

The resulting string.

# Example

For `s = "Aba"`, the output should be `"aba"`

For `s = "ABa"`, the output should be `"ABA"`

def case_unification(s):
    lower = sum(c.islower() for c in s)
    upper = len(s) - lower
    func = str.upper if upper > lower else str.lower
    return func(s)


Solve in Python:
# Task
Given an integer array `arr`. Your task is to remove one element, maximize the product of elements.

The result is the element which should be removed. If more than one valid results exist, return the smallest one.

# Input/Output

`[input]` integer array `arr`

non-empty unsorted integer array. It contains positive integer, negative integer or zero.

`3 ≤ arr.length ≤ 15`

`-10 ≤ arr[i] ≤ 10`

`[output]` an integer

The element that should be removed.

# Example

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

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

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

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

def maximum_product(arr):
    if arr.count(0) > 1:
        return min(arr)
    neg = [n for n in arr if n < 0]
    pos = [n for n in arr if n >= 0]
    if len(neg) % 2:
        return min(neg) if 0 in arr else max(neg)
    else:
        return min(pos) if pos else min(neg)


Solve in Python:
# Task
Given array of integers `sequence` and some integer `fixedElement`, output the number of `even` values in sequence before the first occurrence of `fixedElement` or `-1` if and only if `fixedElement` is not contained in sequence.

# Input/Output

`[input]` integer array `sequence`

A non-empty array of positive integers.

`4 ≤ sequence.length ≤ 100`

`1 ≤ sequence[i] ≤ 9`

`[input]` integer `fixedElement`

An positive integer

`1 ≤ fixedElement ≤ 9`

`[output]` an integer

# Example

For `sequence = [1, 4, 2, 6, 3, 1] and fixedElement = 6`, the output should be `2`.

There are `2` even numbers before `6`: `4 and 2`

For `sequence = [2, 2, 2, 1] and fixedElement = 3`, the output should be `-1`.

There is no `3` appears in `sequence`. So returns `-1`.

For `sequence = [1, 3, 4, 3] and fixedElement = 3`, the output should be `0`.

`3` appears in `sequence`, but there is no even number before `3`.

def even_numbers_before_fixed(S, p):
    return sum(not e%2 for e in S[:S.index(p)]) if p in S else -1


Solve in Python:
# Task
Given some sticks by an array `V` of positive integers, where V[i] represents the length of the sticks, find the number of ways we can choose three of them to form a triangle.

# Example

 For `V = [2, 3, 7, 4]`, the result should be `1`.

 There is only `(2, 3, 4)` can form a triangle.

 For `V = [5, 6, 7, 8]`, the result should be `4`.

 `(5, 6, 7), (5, 6, 8), (5, 7, 8), (6, 7, 8)`

# Input/Output

 - `[input]` integer array `V`

 stick lengths

 `3 <= V.length <= 100`

 `0 < V[i] <=100`

 - `[output]` an integer

 number of ways we can choose 3 sticks to form a triangle.

import itertools
def counting_triangles(V):
    count = 0
    for x in itertools.combinations(V,3):
        if(sum([x[0]+x[1]>x[2],x[0]+x[2]>x[1],x[1]+x[2]>x[0],abs(x[0]-x[1])<x[2],abs(x[0]-x[2])<x[1],abs(x[1]-x[2])<x[0]])==6):
            count += 1
    return count


Solve in Python:
# Task
Given two integers `a` and `b`, return the sum of the numerator and the denominator of the reduced fraction `a/b`.

# Example

For `a = 2, b = 4`, the result should be `3`

Since `2/4 = 1/2 => 1 + 2 = 3`.

For `a = 10, b = 100`, the result should be `11`

Since `10/100 = 1/10 => 1 + 10 = 11`.

For `a = 5, b = 5`, the result should be `2`

Since `5/5 = 1/1 => 1 + 1 = 2`.

# Input/Output

- `[input]` integer `a`

The numerator, `1 ≤ a ≤ 2000`.

- `[input]` integer `b`

The denominator, `1 ≤ b ≤ 2000`.

- `[output]` an integer

The sum of the numerator and the denominator of the reduces fraction.

import fractions
def fraction(a, b):
    return sum([int(s) for s in str(fractions.Fraction(a,b)).split('/')])


Solve in Python:
# Task
Imagine `n` horizontal lines and `m` vertical lines.

Some of these lines intersect, creating rectangles.

How many rectangles are there?

# Examples

For `n=2, m=2,` the result should be `1`.

there is only one 1x1 rectangle.

For `n=2, m=3`, the result should be `3`.

there are two 1x1 rectangles and one 1x2 rectangle. So `2 + 1 = 3`.

For n=3, m=3, the result should be `9`.

there are four 1x1 rectangles, two 1x2 rectangles, two 2x1 rectangles and one 2x2 rectangle. So `4 + 2 + 2 + 1 = 9`.

# Input & Output

- `[input]` integer `n`

Number of horizontal lines.

Constraints: `0 <= n <= 100`

- `[input]` integer `m`

Number of vertical lines.

Constraints: `0 <= m <= 100`

- `[output]` an integer

Number of rectangles.

from math import factorial

def rectangles(n, m):
    return 0 if n <= 1 or m <= 1 else round(factorial(n)/factorial(n-2)/2 * factorial(m)/factorial(m-2)/2)


Solve in Python:
# Task
John is an orchard worker.

There are `n` piles of fruits waiting to be transported. Each pile of fruit has a corresponding weight. John's job is to combine the fruits into a pile and wait for the truck to take them away.

Every time, John can combine any two piles(`may be adjacent piles, or not`), and the energy he costs is equal to the weight of the two piles of fruit.

For example, if there are two piles, pile1's weight is `1` and pile2's weight is `2`. After merging, the new pile's weight is `3`, and he consumed 3 units of energy.

John wants to combine all the fruits into 1 pile with the least energy.

Your task is to help John, calculate the minimum energy he costs.

# Input

- `fruits`: An array of positive integers. Each element represents the weight of a pile of fruit.

  Javascript:
  - 1 <= fruits.length <= 10000
  - 1 <= fruits[i] <= 10000

  Python:
  - 1 <= len(fruits) <= 5000
  - 1 <= fruits[i] <= 10000

# Output

An integer. the minimum energy John costs.

# Examples

For `fruits = [1,2,9]`, the output should be `15`.

```
3 piles:  1  2  9
combine 1 and 2 to 3, cost 3 units of energy.
2 piles:  3  9
combine 3 and 9 to 12, cost 12 units of energy.
1 pile:  12

The total units of energy is 3 + 12 = 15 units
```

For `fruits = [100]`, the output should be `0`.

There's only 1 pile. So no need combine it.

from heapq import heapify, heappush, heappop

def comb(fruits):
    energy = 0
    heapify(fruits)
    while len(fruits) > 1:
        cost = heappop(fruits) + heappop(fruits)
        heappush(fruits, cost)
        energy += cost
    return energy


Solve in Python:
# Task
John was in math class and got bored, so he decided to fold some origami from a rectangular `a × b` sheet of paper (`a > b`). His first step is to make a square piece of paper from the initial rectangular piece of paper by folding the sheet along the bisector of the right angle and cutting off the excess part.

After moving the square piece of paper aside, John wanted to make even more squares! He took the remaining (`a-b`) × `b` strip of paper and went on with the process until he was left with a square piece of paper.

 Your task is to determine how many square pieces of paper John can make.

# Example:

 For: `a = 2, b = 1`, the output should be `2`.

 Given `a = 2` and `b = 1`, John can fold a `1 × 1` then another `1 × 1`.

 So the answer is `2`.

 For: `a = 10, b = 7`, the output should be `6`.

 We are given `a = 10` and `b = 7`. The following is the order of squares John folds: `7 × 7, 3 × 3, 3 × 3, 1 × 1, 1 × 1, and 1 × 1`.

 Here are pictures for the example cases.

# Input/Output

 - `[input]` integer `a`

  `2 ≤ a ≤ 1000`

 - `[input]` integer `b`

  `1 ≤ b < a ≤ 1000`

 - `[output]` an integer

  The maximum number of squares.

def folding(a,b):
  #coding and coding..
    n=1
    while a > b:
        a_new = a-b
        a = max(a_new,b)
        b = min(a_new,b)
        n+=1
    return n


Solve in Python:
# Task
Let's define a `parameter` of number `n` as the least common multiple (LCM) of the sum of its digits and their product.

Calculate the parameter of the given number `n`.

# Input/Output

`[input]` integer `n`

 A positive integer. It is guaranteed that no zero appears in `n`.

`[output]` an integer

 The parameter of the given number.

# Example

For `n = 22`, the output should be `4`.

Both the sum and the product of digits equal 4, and LCM(4, 4) = 4.

For `n = 1234`, the output should be `120`.

`1+2+3+4=10` and `1*2*3*4=24`, LCM(10,24)=120

from functools import reduce
from fractions import gcd
def parameter(n):
    n = [int(i) for i in str(n)]
    sum_ = reduce(lambda a, b: a + b, n)
    prod = reduce(lambda a, b: a * b, n)
    return (sum_ * prod) / gcd(sum_, prod)


Solve in Python:
# Task
Make a custom esolang interpreter for the language Stick. Stick is a simple, stack-based esoteric programming language with only 7 commands.
# Commands

* `^`: Pop the stack.

* `!`: Add new element to stack with the value of 0.

* `+`: Increment element. 255+1=0.

* `-`: Decrement element. 0-1=255.

* `*`: Add ascii value of **top** element to the output stream.

* `[`: Skip past **next** `]` if element value is 0.

* `]`: Jump back to the command after **previous** `[` if element value is nonzero.

# Syntax and other info

* You don't need to add support for nested brackets.
* Non-command characters should be ignored.
* Code will always have all brackets closed.
* Note the highlighted **next** and **previous** in the commands reference.
* Program begins with the top element having the value of 0 and being the only element in the stack.
* Program ends when command executor reaches the end.

# Examples

## Hello,...

def interpreter(tape):
    stack = [0]
    ip = 0
    output = ''
    while ip < len(tape):
        op = tape[ip]
        if op == '^':
            stack.pop()
        elif op == '!':
            stack.append(0)
        elif op == '+':
            stack[-1] = (stack[-1] + 1) % 256
        elif op == '-':
            stack[-1] = (stack[-1] + 255) % 256
        elif op == '*':
            output += chr(stack[-1])
        elif op == '[' and stack[-1] == 0:
            ip = tape.find(']', ip + 1)
        elif op == ']' and stack[-1] != 0:
            ip = tape.rfind('[', 0, ip)
        ip += 1
    return output


Solve in Python:
# Task
N lamps are placed in a line, some are switched on and some are off. What is the smallest number of lamps that need to be switched so that on and off lamps will alternate with each other?

You are given an array `a` of zeros and ones - `1` mean switched-on lamp and `0` means switched-off.

Your task is to find the smallest number of lamps that need to be switched.

# Example

For `a = [1, 0, 0, 1, 1, 1, 0]`, the result should be `3`.
```
a     --> 1 0 0 1 1 1 0
swith --> 0 1     0
became--> 0 1 0 1 0 1 0 ```

# Input/Output

- `[input]` integer array `a`

array of zeros and ones - initial lamp setup, 1 mean switched-on lamp and 0 means switched-off.

`2 < a.length <= 1000`

- `[output]` an integer

minimum number of switches.

def lamps(a):
  r = sum(x == c % 2 for c, x in enumerate(a))
  return min(r, len(a) - r)


Solve in Python:
# Task
Some children are playing rope skipping game. Children skip the rope at roughly the same speed: `once per second`. If the child fails during the jump, he needs to tidy up the rope and continue. This will take `3 seconds`.

You are given an array `failedCount`, where each element is the jump count at the failed. ie. `[12,23,45]` means the child failed 3 times in the game process. The 1st mistake occurred when he jumped 12 times; The 2nd mistake occurred when he jumped 23 times; The 3rd mistake occurred when he jumped 45 times.

Your task is to calculate how many times the child jumped in 60 seconds.

Note: Each child persisted at least 60 jumps, which meant it could have been over 60 seconds, but the child continued to skip rope.

# Input/Output

`[input]` integer array `failedCount`

`0 ≤ failedCount.length ≤ 60`

`1 ≤ failedCount[i] ≤ 60`

`[output]` an integer

how many times the child jumped in 60 seconds.

# Example

For `failedCount = []`, the output should be `60`.

There is no mistake in the game process. So the child jumped 60 times in 60 seconds.

For `failedCount = [12, 23, 45]`, the output should be `51`.
```
The 1st mistake occurred when he jumped 12 times. --> 12 seconds past.
Tidy up the rope and continue.                    --> 15 seconds past.
The 2nd mistake occurred when he jumped 23 times. --> 26 seconds past.
Tidy up the rope and continue.                    --> 29 seconds past.
The 3rd mistake occurred when he jumped 45 times. --> 51 seconds past.
Tidy up the rope and continue.                    --> 54 seconds past.
When he jumped 51 times                           --> 60 seconds past.
```

def tiaosheng(fails):
    return 60 - sum(1 for i, f in enumerate(fails) for k in range(3) if 3*i + f + k < 60)


Solve in Python:
# Task
Two arrays are called similar if one can be obtained from another by swapping at most one pair of elements.

Given two arrays, check whether they are similar.

# Example

For `A = [1, 2, 3]` and `B = [1, 2, 3]`, the output should be `true;`

For `A = [1, 2, 3]` and `B = [2, 1, 3]`, the output should be `true;`

For `A = [1, 2, 2]` and `B = [2, 1, 1]`, the output should be `false.`

# Input/Output

- `[input]` integer array `A`

Array of integers.

Constraints: `3 ≤ A.length ≤ 10000, 1 ≤ A[i] ≤ 1000.`

- `[input]` integer array `B`

Array of integers of the same length as `A`.

Constraints: `B.length = A.length, 1 ≤ B[i] ≤ 1000.`

- `[output]` a boolean value

`true` if `A` and `B` are similar, `false` otherwise.

def are_similar(a, b):
    return sorted(a)==sorted(b) and sum(1 for x, y in zip(a,b) if x!=y)<=2


Solve in Python:
# Task
Two players - `"black"` and `"white"` are playing a game. The game consists of several rounds. If a player wins in a round, he is to move again during the next round. If a player loses a round, it's the other player who moves on the next round. Given whose turn it was on the previous round and whether he won, determine whose turn it is on the next round.

# Input/Output

`[input]` string `lastPlayer`/`$last_player`

`"black"` or `"white"` - whose move it was during the previous round.

`[input]` boolean `win`/`$win`

`true` if the player who made a move during the previous round won, `false` otherwise.

`[output]` a string

Return `"white"` if white is to move on the next round, and `"black"` otherwise.

# Example

For `lastPlayer = "black" and win = false`, the output should be `"white"`.

For `lastPlayer = "white" and win = true`, the output should be `"white"`.

def whoseMove(lastPlayer, win):
    return {("black", False): "white",
            ("black", True): "black",
            ("white", False): "black",
            ("white", True): "white",}[(lastPlayer, win)]


Solve in Python:
# Task
We know that some numbers can be split into two primes. ie. `5 = 2 + 3, 10 = 3 + 7`. But some numbers are not. ie. `17, 27, 35`, etc..

Given a positive integer `n`. Determine whether it can be split into two primes. If yes, return the maximum product of two primes. If not, return `0` instead.

# Input/Output

`[input]` integer `n`

A positive integer.

`0 ≤ n ≤ 100000`

`[output]` an integer

The possible maximum product of two primes. or return `0` if it's impossible split into two primes.

# Example

For `n = 1`, the output should be `0`.

`1` can not split into two primes

For `n = 4`, the output should be `4`.

`4` can split into two primes `2 and 2`. `2 x 2 = 4`

For `n = 20`, the output should be `91`.

`20` can split into two primes `7 and 13` or `3 and 17`. The maximum product is `7 x 13 = 91`

def prime_product(n):
    def is_prime(n): return n == 2 or n > 2 and n % 2 and all(n % d for d in range(3, int(n ** .5) + 1, 2))
    for i in range(n//2,1,-1):
        if is_prime(i) and is_prime(n-i): return i*(n-i)
    return 0


Solve in Python:
# Task
You are a lifelong fan of your local football club, and proud to say you rarely miss a game. Even though you're a superfan, you still hate boring games. Luckily, boring games often end in a draw, at which point the winner is determined by a penalty shoot-out, which brings some excitement to the viewing experience. Once, in the middle of a penalty shoot-out, you decided to count the lowest total number of shots required to determine the winner. So, given the number of shots each team has already made and the current score, `how soon` can the game end?

If you are not familiar with penalty shoot-out rules, here they are:

`Teams take turns to kick from the penalty mark until each has taken five kicks. However, if one side has scored more successful kicks than the other could possibly reach with all of its remaining kicks, the shoot-out immediately ends regardless of the number of kicks remaining.`

`If at the end of these five rounds of kicks the teams have scored an equal number of successful kicks, additional rounds of one kick each will be used until the tie is broken.`

# Input/Output

`[input]` integer `shots`

An integer, the number of shots each team has made thus far.

`0 ≤ shots ≤ 100.`

`[input]` integer array `score`

An array of two integers, where score[0] is the current score of the first team and score[1] - of the second team.

`score.length = 2,`

`0 ≤ score[i] ≤ shots.`

`[output]` an integer

The minimal possible total number of shots required to determine the winner.

# Example

For `shots = 2 and score = [1, 2]`, the output should be `3`.

The possible 3 shots can be:
```
shot1: the first team misses the penalty
shot2: the second team scores
shot3: the first one misses again```

then, score will be [1, 3]. As the first team can't get 2 more points in the last remaining shot until the end of the initial five rounds, the winner is determined.

For `shots = 10 and score = [10, 10]`, the output should be `2`.

If one of the teams misses the penalty and the other one scores, the game ends.

def penaltyShots(h,s):
    return 6-min(h,4)-abs(s[0]-s[1])


Solve in Python:
# Task
Your task is to find the sum for the range `0 ... m` for all powers from `0 ... n.

# Example

 For `m = 2, n = 3`, the result should be `20`

 `0^0+1^0+2^0 + 0^1+1^1+2^1 + 0^2+1^2+2^2 + 0^3+1^3+2^3 = 20`

 Note, that no output ever exceeds 2e9.

# Input/Output

 - `[input]` integer m

  `0 <= m <= 50000`

 - `[input]` integer `n`

  `0 <= n <= 9`

 - `[output]` an integer(double in C#)

  The sum value.

def S2N(m, n):
  return sum(sum(i ** j for i in range(m + 1)) for j in range(n + 1))


Solve in Python:
# Task
`EvilCode` is a game similar to `Codewars`. You have to solve programming tasks as quickly as possible. However, unlike `Codewars`, `EvilCode` awards you with a medal, depending on the time you took to solve the task.

To get a medal, your time must be (strictly) inferior to the time corresponding to the medal. You can be awarded `"Gold", "Silver" or "Bronze"` medal, or `"None"` medal at all. Only one medal (the best achieved) is awarded.

You are given the time achieved for the task and the time corresponding to each medal. Your task is to return the awarded medal.

Each time is given in the format `HH:MM:SS`.

# Input/Output

`[input]` string `userTime`

The time the user achieved.

`[input]` string `gold`

The time corresponding to the gold medal.

`[input]` string `silver`

The time corresponding to the silver medal.

`[input]` string `bronze`

The time corresponding to the bronze medal.

It is guaranteed that `gold < silver < bronze`.

`[output]` a string

The medal awarded, one of for options: `"Gold", "Silver", "Bronze" or "None"`.

# Example

For
```
userTime = "00:30:00", gold = "00:15:00",
silver = "00:45:00" and bronze = "01:15:00"```

the output should be `"Silver"`

For
```
userTime = "01:15:00", gold = "00:15:00",
silver = "00:45:00" and bronze = "01:15:00"```

the output should be `"None"`

# For Haskell version
```
In Haskell, the result is a Maybe, returning Just String indicating
the medal if they won or Nothing if they don't.
```

evil_code_medal=lambda *args: ["None","Bronze","Silver","Gold"][sum(arg>args[0] for arg in args[1:])]


Solve in Python:
# Task
`Triangular numbers` are defined by the formula `n * (n + 1) / 2` with `n` starting from 1. They count the number of objects that can form an equilateral triangle as shown in the picture below:

![](https://i.gyazo.com/eec11cc9e17a31324338edc4eb7bb746.png)

So the sequence of triangular numbers begins as follows:

`1, 3, 6, 10, 15, 21, 28, ....`

It is proven that the sum of squares of any two consecutive triangular numbers is equal to another triangular number.

You're given a triangular number `n`. Return `true` if it can be represented as `a sum of squares of two consecutive triangular numbers`, or `false` otherwise.

# Input/Output

`[input]` integer `n`

A positive triangular number

`3 ≤ n ≤ 10^9`

`[output]` a boolean value

`true` if it is possible to represent n as the sum of squares of two consecutive triangular numbers, and `false` otherwise.

# Example

For `n = 6`, the output should be `false`.

No two squared consecutive triangular numbers add up to 6.

For `n = 45`, the output should be `true`.

`3 * 3 + 6 * 6 = 9 + 36 = 45`

def triangular_sum(n):
    r = int((n*2)**0.5)
    return r * (r+1) / 2 == n and round(r**0.5)**2 == r


Solve in Python:
# Task

**_Given_**   *a number* , **_Return_**  **_The Maximum number _**  *could be formed from the digits of the number given* .
___
# Notes

* **_Only Natural numbers_** *passed to the function , numbers Contain digits [0:9] inclusive*

* **_Digit Duplications_** *could occur* , So also **_consider it when forming the Largest_**

____
# Input >> Output Examples:

```
maxNumber (213) ==> return (321)
```
## **_Explanation_**:

As `321` is **_The Maximum number _**  *could be formed from the digits of the number   **_213_*** .
___

```
maxNumber (7389) ==> return (9873)
```
## **_Explanation_**:

As `9873` is **_The Maximum number _**  *could be formed from the digits of the number  **_7389_*** .
___

```
maxNumber (63729) ==> return (97632)
```
## **_Explanation_**:

As `97632` is **_The Maximum number _**  *could be formed from the digits of the number  **_63729_*** .
___

```
maxNumber (566797) ==> return (977665)
```
## **_Explanation_**:

As `977665` is **_The Maximum number _**  *could be formed from the digits of the number  **_566797_*** .

**_Note_** : **_Digit duplications are considered when forming the largest_** .
___

```
maxNumber (17693284) ==> return (98764321)
```
## **_Explanation_**:

As `98764321` is **_The Maximum number _**  *could be formed from the digits of the number  **_17693284_*** .
___
___
___

# [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 max_number(n,vac=""):
    lista2 = [int(a) for a in list(str(n))]
    lista2.sort(reverse=True)
    for num in lista2:
        vac += str(num)
    return int(vac)


Solve in Python:
# Task:

Based on the received dimensions, `a` and `b`, of an ellipse, calculare its area and perimeter.

## Example:
```python
Input: ellipse(5,2)

Output: "Area: 31.4, perimeter: 23.1"
```

**Note:** The perimeter approximation formula you should use: `π * (3/2(a+b) - sqrt(ab))`

___

## Have fun :)

import math
def ellipse(a, b):
    perimeter = round(math.pi*(3/2*(a+b) - math.sqrt(a*b)), 1)
    area = round(math.pi*a*b, 1)
    return f'Area: {area}, perimeter: {perimeter}'


Solve in Python:
# Task:

We define the "self reversed power sequence" as one shown below:

Implement a function that takes 2 arguments (`ord max` and `num dig`), and finds the smallest term of the sequence whose index is less than or equal to `ord max`, and has exactly `num dig` number of digits.

If there is a number with correct amount of digits, the result should be an array in the form:

```python
[True, smallest found term]
[False, -1]
```

## Input range:

```python
ord_max <= 1000
```

___

## Examples:

```python
min_length_num(5, 10) == [True, 10]   # 10th term has 5 digits
min_length_num(7, 11) == [False, -1]  # no terms before the 13th one have 7 digits
min_length_num(7, 14) == [True, 13]   # 13th term is the first one which has 7 digits
```

Which you can see in the table below:

```
n-th Term    Term Value
1              0
2              1
3              3
4              8
5              22
6              65
7              209
8              732
9              2780
10             11377
11             49863
12             232768
13             1151914
14             6018785
```

___

Enjoy it and happy coding!!

nums = {}

def helper():
    nums[1] = '0'
    nums[2] = '1'
    for i in range(1001):
        exp, suma = 1, 0
        for j in range(i, 0, -1):
            suma += j ** exp
            exp += 1
        nums[i] = str(suma)

def min_length_num(num_dig, ord_max):
    if not nums:
        helper()
    for num in range(1, ord_max):
        if len(nums[num]) == num_dig:
            return [True, num + 1]
    return [False, -1]


Solve in Python:
# Task:
Given a list of numbers, determine whether the sum of its elements is odd or even.

Give your answer as a string matching `"odd"` or `"even"`.

If the input array is empty consider it as: `[0]` (array with a zero).

## Example:

```
odd_or_even([0])          ==  "even"
odd_or_even([0, 1, 4])    ==  "odd"
odd_or_even([0, -1, -5])  ==  "even"
```

Have fun!

def odd_or_even(arr):
    n = sum(arr)
    odd = [1,3,5,7,9]
    even = [2,4,6,8,0]
    if (n % 10) in odd:
        return "odd"
    else:
        return "even"


Solve in Python:
# Task:
This kata asks you to make a custom esolang interpreter for the language [MiniBitMove](https://esolangs.org/wiki/MiniBitMove). MiniBitMove has only two commands and operates on a array of bits. It works like this:

- `1`: Flip the bit at the current cell
- `0`: Move selector by 1

It takes two inputs, the program and the bits in needs to operate on. The program returns the modified bits. The program stops when selector reaches the end of the array. Otherwise the program repeats itself. **Note: This means that if a program does not have any zeros it is an infinite loop**

Example of a program that flips all bits in an array:
```
Code: 10
Bits: 11001001001010
Result: 00110110110101
```

After you're done, feel free to make translations and discuss this kata.

from itertools import cycle

def interpreter(tape, s):
    a = list(s)
    i = 0  # selector
    for op in cycle(tape):
        if op == '1':
            a[i] = str(1 - int(a[i]))
        else:
            i += 1
            if i == len(s):
                return ''.join(a)


Solve in Python:
# Task:
Write a function that accepts an integer `n` and returns **the sum of the factorials of the first **`n`** Fibonacci numbers**

## Examples:

```python
sum_fib(2)  = 2    # 0! + 1! = 2
sum_fib(3)  = 3    # 0! + 1! + 1! = 3
sum_fib(4)  = 5    # 0! + 1! + 1! + 2! = 5
sum_fib(10) = 295232799039604140898709551821456501251
```

### Constraints:

* #### **2 ≤ N ≤ 22**

### sum_fib(20)

This number is so huge I need to make a separate area for it. Imagine 13327...

from math import factorial

def sum_fib(n):
    fibo_num = 1
    fibo_num_prev = 0
    sum_factorial = 0
    for num in range(0,n):
        sum_factorial = sum_factorial + factorial(fibo_num_prev)
        fibo_num_prev, fibo_num = fibo_num, fibo_num + fibo_num_prev
    return sum_factorial


Solve in Python:
# Ten-Pin Bowling

In the game of ten-pin bowling, a player rolls a bowling ball down a lane to knock over pins. There are ten pins set at the end of the bowling lane. Each player has 10 frames to roll a bowling ball down a lane and knock over as many pins as possible. The first nine frames are ended after two rolls or when the player knocks down all the pins. The last frame a player will receive an extra roll every time they knock down all ten pins; up to a maximum of three total rolls.

## The Challenge

In this challenge you will be given a string representing a player's ten frames. It will look something like this: `'X X 9/ 80 X X 90 8/ 7/ 44'` (in Java: `"X X 9/ 80 X X 90 8/ 7/ 44"`), where each frame is space-delimited, `'X'` represents strikes, and `'/'` represents spares. Your goal is take in this string of frames into a function called `bowlingScore` and return the players total score.

## Scoring

The scoring for ten-pin bowling can be difficult to understand, and if you're like most people, easily forgotten if you don't play often. Here is a quick breakdown:

### Frames

In Ten-Pin Bowling there are ten frames per game. Frames are the players turn to bowl, which can be multiple rolls. The first 9 frames you get 2 rolls maximum to try to get all 10 pins down. **On the 10th or last frame a player will receive an extra roll each time they get all ten pins down to a maximum of three total rolls. Also on the last frame bonuses are not awarded for strikes and spares moving forward.**

In this challenge, three frames might be represented like this: `54 72 44`. In this case, the player has had three frames. On their first frame they scored 9 points (5 + 4), on their second frame they scored 9 points (7 + 2) and on their third frame they scored 8 points (4 + 4). This is a very simple example of bowling scoring. It gets more complicated when we introduce strikes and spares.

### Strikes
Represented in this challenge as `'X'`

A strike is scored when a player knocks all ten pins down in one roll. In the...

def bowling_score(frames):
    pins = []
    # Identify each roll's score, bonus balls and frame
    for f, frame in enumerate(frames.split()):
        for c in frame:
            if c == "X":
                pins.append([10, 2, f])
            elif c == "/":
                p = 10 - pins[-1][0]
                pins.append([p, 1, f])
            else:
                pins.append([int(c), 0, f])
    # Apply all the bonuses
    for i in range(len(pins)):
        score, offset, frame = pins[i]
        if offset > 0 and frame < 9:
            pins[i][0] += sum(pin[0] for pin in pins[i + 1: i + 1 + offset])
    # Sum it all up
    return sum(pin[0] for pin in pins)


Solve in Python:
# The Invitation

Most of us played with toy blocks growing up. It was fun and you learned stuff. So what else can you do but rise to the challenge when a 3-year old exclaims, "Look, I made a square!", then pointing to a pile of blocks, "Can _you_ do it?"

# These Blocks

Just to play along, of course we'll be viewing these blocks in two dimensions. Depth now being disregarded, it turns out the pile has four different sizes of block: `1x1`, `1x2`, `1x3`, and `1x4`. The smallest one represents the area of a square, the other three are rectangular, and all differ by their width. Integers matching these four widths are used to represent the blocks in the input.

# This Square

Well, the kid made a `4x4` square from this pile, so you'll have to match that. Noticing the way they fit together, you realize the structure must be built in fours rows, one row at a time, where the blocks must be placed horizontally. With the known types of block, there are five types of row you could build:

* 1 four-unit block
* 1 three-unit block plus 1 one-unit bock (in either order)
* 2 two-unit blocks
* 1 two-unit block plus 2 one-unit blocks (in any order)
* 4 one-unit blocks

Amounts for all four of the block sizes in the pile will each vary from `0` to `16`. The total size of the pile will also vary from `0` to `16`. The order of rows is irrelevant. A valid square doesn't have to use up all the given blocks.

# Some Examples

Given `1, 3, 2, 2, 4, 1, 1, 3, 1, 4, 2` there are many ways you could construct a square. Here are three possibilities, as described by their four rows:

* 1 four-unit block
* 2 two-unit blocks
* 1 four-unit block
* 4 one-unit blocks
>
* 1 three-unit block plus 1 one-unit block
* 2 two-unit blocks
* 1 four-unit block
* 1 one-unit block plus 1 three-unit block
>
* 2 two-unit blocks
* 1 three-unit block plus 1 one-unit block
* 1 four-unit block
* 2 one-unit blocks plus 1 two-unit block
>

Given `1, 3, 2, 4, 3, 3, 2` there is no way to complete the task, as you could only build three rows of the correct...


Solve in Python:
# The Kata
Your task is to transform an input nested list into an hypercube list, which is a special kind of nested list where each level must have the very same size,
This Kata is an exercise on recursion and algorithms. You will need to visualize many aspects of this question to be able to solve it efficiently, as such there is a section on definitions of the terms that will be used in the Kata, make sure to fully understand them before attempting. A naive brute-force-ish answer will most likely fail the tests. There will be tests on  nested lists of dimension and size up to 10. Good luck.

# Definitions
### Nested List
A nested list is a list that may contain either non-list items or more nested lists as items in the list. Here are a few examples of nested lists.

    [[2, 3], 4, 5, 6, [2, [2, 3, 4, 5], 2, 1, 2], [[[[1]]]], []]
    [[[]]]
    [1, 2]
    [[], []]
    [4, 5, 6, 7, [], 2]
    []

- A *basic element* refers to any non-list element of a nested list.

- A nested list's *dimension* is defined as the deepest the list goes.

- A nested list's *size* is defined as the longest the list or any of its sublists go.

For example, the *dimension* and *size* of the above nested lists is as follows.

    [[2, 3], 4, 5, 6, [2, [2, 3, 4, 5], 2, 1, 2], [[[[1]]]], []]  # dimension: 5, size: 7
    [[[]]]                                                        # dimension: 3, size: 1
    [1, 2]                                                        # dimension: 1, size: 2
    [[], []]                                                      # dimension: 2, size: 2
    [4, 5, 6, 7, [], 2]                                           # dimension: 2, size: 6
    []                                                            # dimension: 1, size: 0

### Hypercube List
- A `1`-dimensional **hypercube list** of size `n` is a nested list of dimension `1` and size `n`.

- A `d`-dimensional hypercube list of size `n` is a nested list of dimension `d` and size `n` such that the nested list has `n` elements each of which...

from itertools import zip_longest

def normalize(lst: List, growing: int = 0) -> List:
    """Convert the given nested list to hypercube format with the given <growing_value> and return it.
    """

    def seeker(lst, d = 1):
        yield len(lst), d
        for elt in lst:
            if isinstance(elt, list):
                yield from seeker(elt, d + 1)

    def grower(lst, d = 1):
        return [ grower(o if isinstance(o, list) else [o] * size, d + 1)
                   if d != depth else o
                 for o, _ in zip_longest(lst, list(range(size)), fillvalue=growing) ]

    size, depth = list(map(max, list(zip(*seeker(lst)))))
    return grower(lst)


Solve in Python:
# The President's phone is broken

He is not very happy.

The only letters still working are uppercase ```E```, ```F```, ```I```, ```R```, ```U```, ```Y```.

An angry tweet is sent to the department responsible for presidential phone maintenance.

# Kata Task

Decipher the tweet by looking for words with known meanings.

* ```FIRE``` = *"You are fired!"*
* ```FURY``` = *"I am furious."*

If no known words are found, or unexpected letters are encountered, then it must be a *"Fake tweet."*

# Notes

* The tweet reads left-to-right.
* Any letters not spelling words ```FIRE``` or ```FURY``` are just ignored
* If multiple of the same words are found in a row then plural rules apply -
 * ```FIRE``` x 1 = *"You are fired!"*
 * ```FIRE``` x 2 = *"You and you are fired!"*
 * ```FIRE``` x 3 = *"You and you and you are fired!"*
 * etc...
 * ```FURY``` x 1 = *"I am furious."*
 * ```FURY``` x 2 = *"I am really furious."*
 * ```FURY``` x 3 = *"I am really really furious."*
 * etc...

# Examples

* ex1. FURYYYFIREYYFIRE = *"I am furious. You and you are fired!"*
* ex2. FIREYYFURYYFURYYFURRYFIRE = *"You are fired! I am really furious. You are fired!"*
* ex3. FYRYFIRUFIRUFURE = *"Fake tweet."*

----
DM :-)

import re
from itertools import groupby

CONFIG = {'FURY':   " really",
          'FIRE':   " and you",
          'FAKE':   "Fake tweet.",
          'FURY_f': "I am{} furious.",
          'FIRE_f': "You{} are fired!"}

def fire_and_fury(tweet):
    if re.findall(r'[^FURYIE]', tweet): return CONFIG['FAKE']
    lst = []
    for k,g in groupby(re.findall(r'FURY|FIRE', tweet)):
        lst += [ CONFIG[k+"_f"].format(CONFIG[k] * (len(list(g)) - 1)) ]
    return ' '.join(lst) or CONFIG['FAKE']


Solve in Python:
# The Problem

Dan, president of a Large company could use your help. He wants to implement a system that will switch all his devices into offline mode depending on his meeting schedule. When he's at a meeting and somebody texts him, he wants to send an automatic message informing that he's currently unavailable and the time when he's going to be back.

# What To Do

Your task is to write a helper function `checkAvailability` that will take 2 arguments:

* schedule, which is going to be a nested array with Dan's schedule for a given day. Inside arrays will consist of 2 elements - start and finish time of a given appointment,

* *currentTime* - is a string with specific time in hh:mm 24-h format for which the function will check availability based on the schedule.
  * If no appointments are scheduled for `currentTime`, the function should return `true`. If there are no appointments for the day, the output should also be `true`
  *  If Dan is in the middle of an appointment at `currentTime`, the function should return a string with the time he's going to be available.

# Examples
`checkAvailability([["09:30", "10:15"], ["12:20", "15:50"]], "11:00");`
should return `true`

`checkAvailability([["09:30", "10:15"], ["12:20", "15:50"]], "10:00");`
should return `"10:15"`

If the time passed as input is *equal to the end time of a meeting*, function should also return `true`.
`checkAvailability([["09:30", "10:15"], ["12:20", "15:50"]], "15:50");`
should return `true`

*You can expect valid input for this kata*

def check_availability(schedule, current_time):
    return next((end for start,end in schedule if start < current_time < end), True)


Solve in Python:
# The die is cast!

Your task in this kata is to write a "dice roller" that interprets a subset of [dice notation](http://en.wikipedia.org/wiki/Dice_notation).

# Description

In most role-playing games, die rolls required by the system are given in the form `AdX`. `A` and `X` are variables, separated by the letter **d**, which stands for *die* or *dice*.

 - `A` is the number of dice to be rolled (usually omitted if 1).
 - `X` is the number of faces of each die.

Here are some examples of input:

# Modifiers

As an addition to the above rules the input may also contain modifiers in the form `+N` or `-N` where `N` is an integer.

Here are some examples of input containing modifiers:

*Modifiers must be applied **after** all dice has been summed up.*

# Output

Your function must support two types of output depending on the second argument; *verbose* and *summed*.

## Summed output
If the verbose flag isn't set your function should sum up all the dice and modifiers and return the result as an integer.

## Verbose output
With the verbose flag your function should return an object/hash containing an array (`dice`) with all the dice rolls, and a integer (`modifier`) containing the sum of the modifiers which defaults to zero.

Example of verbose output:

# Invalid input
Here are some examples of invalid inputs:

# Additional information

 - Your solution should ignore all whitespace.
 - `roll` should return `false` for invalid input.

import re
from random import randint

def roll(desc, verbose=False):
    if not isinstance(desc, str):
        return False
    match = re.match(r'^(\d*)d(\d+)((?:[+-]\d+)*)$', desc.replace(' ', ''))
    if match:
        dices, side, modifiers = match.groups()
        dices = int(dices) if dices else 1
        modifier = eval(modifiers) if modifiers else 0
        res = list(randint(1, int(side)) for _ in range(dices))
        return {'dice': res, 'modifier': modifier} if verbose else sum(res) + modifier
    return False


Solve in Python:
# The learning game - Machine Learning #1
Growing up you would have learnt a lot of things like not to stand in fire, to drink food and eat water and not to jump off very tall things But Machines have it difficult they cannot learn for themselves we have to tell them what to do, why don't we give them a chance to learn it for themselves?

### Task
Your task is to finish the Machine object. What the machine object must do is learn from its mistakes! The Machine will be given a command and a number you will return a random action. After the command has returned you will be given a response (true/false) if the response is true then you have done good, if the response is false then the action was a bad one. You must program the machine to learn to apply an action to a given command using the reponse given. Note: It must take no more than 20 times to teach an action to a command also different commands can have the same action.

### Info
- In the preloaded section there is a constant called ```ACTIONS``` it is a function that returns the 5 possible actions.
- In Java, this a constant ```Actions.FUNCTIONS``` of type ```List>```.
- In C++, the actions can be accessed by ```get_action(i)(unsigned int num)``` where i chooses the function (and therefore can range from 0 to 4) and num is its argument.
- In python ```ACTIONS()``` returns a list of lambdas.
- In Golang ```Actions()``` retruns a function slice ```[]func(int) int```

class Machine:
    def __init__(self):
        self.cmd = dict()

    def command(self, cmd, num):
        self.last_cmd = cmd
        if cmd  in self.cmd:
            return _actions[self.cmd[cmd]](num)
        else:
            self.cmd[cmd] = 0
        return _actions[self.cmd[cmd]](num)

    def response(self,res):
        if res == False:
            self.cmd[self.last_cmd] += 1


Solve in Python:
# The museum of incredible dull things

The museum of incredible dull things wants to get rid of some exhibitions. Miriam, the interior architect, comes up with a plan to remove the most boring exhibitions. She gives them a rating, and then removes the one with the lowest rating.

However, just as she finished rating all exhibitions, she's off to an important fair, so she asks you to write a program that tells her the ratings of the items after one removed the lowest one. Fair enough.

# Task

Given an array of integers, remove the smallest value. **Do not mutate the original array/list**. If there are multiple elements with the same value, remove the one with a lower index. If you get an empty array/list, return an empty array/list.

Don't change the order of the elements that are left.

### Examples

```python
remove_smallest([1,2,3,4,5]) = [2,3,4,5]
remove_smallest([5,3,2,1,4]) = [5,3,2,4]
remove_smallest([2,2,1,2,1]) = [2,2,2,1]
```

def remove_smallest(numbers):
    result = list(numbers)
    if len(numbers) >= 1:
        result.remove(min(numbers))
    else:
        return ([])
    return result


Solve in Python:
# Toggling Grid
You are given a grid (2d array) of 0/1's. All 1's represents a solved puzzle. Your job is to come up with a sequence of toggle moves that will solve a scrambled grid.

Solved:

```
[ [1, 1, 1],
  [1, 1, 1],
  [1, 1, 1] ]
```

"0" (first row) toggle:
```
[ [0, 0, 0],
  [1, 1, 1],
  [1, 1, 1] ]
```

then "3" (first column) toggle:
```
[ [1, 0, 0],
  [0, 1, 1],
  [0, 1, 1] ]
```

The numbers in quotes are codes for the row/column, and will be explained.

## Your task: findSolution()
Your task is to write a function, `findSolution()` (or `find_solution()`), which takes as input a 2d array, and returns an array of "steps" that represent a sequence of toggles to solve the puzzle.

For example:

```python
solution = find_solution(puzzle)
print(solution);
> [0, 3]
```
Note that, in the above example, `[1, 2, 4, 5]` is also a valid solution! Any solution will pass the tests.

The solution is tested like this, for each number in the solution:

```python
if n < puzzle.size:
  toggleRow(n)
else:
  toggleCol(n - puzzle.size)
```
To elaborate, possible n's for a 3x3 puzzle:

- Row numbers = (0    --> size - 1)
- Cols numbers = (size --> size * 2 - 1)

### Example of "2" toggle:

### Example of "4" toggle:

## More examples:

```python
puzzle = [
  [ 0, 1, 0 ],
  [ 1, 0, 1 ],
  [ 1, 0, 1 ]
];
solution = find_solution(puzzle)
print(solution);
> [0, 4]
```
let's try some bigger puzzles:

```python
puzzle = [
  [ 1, 0, 1, 0, 0 ],
  [ 0, 1, 0, 1, 1 ],
  [ 0, 1, 0, 1, 1 ],
  [ 0, 1, 0, 1, 1 ],
  [ 1, 0, 1, 0, 0 ]
];
solution = find_solution(puzzle)
print(solution);
> [ 0, 5, 4, 7 ]
```

```python
puzzle = [
  [ 1, 1, 1, 0, 1, 1, 1 ],
  [ 1, 1, 1, 0, 1, 1, 1 ],
  [ 1, 1, 1, 0, 1, 1, 1 ],
  [ 0, 0, 0, 1, 0, 0, 0 ],
  [ 1, 1, 1, 0, 1, 1, 1 ],
  [ 1, 1, 1, 0, 1, 1, 1 ],
  [ 1, 1, 1, 0, 1, 1, 1 ]
];
solution = find_solution(puzzle)
print(solution);
> [ 3, 10 ]
```

There are randomized tests with puzzles of up to 100x100 in size. Have fun!

# returns a sequence of row/column toggles to solve the puzzle
# - Examples:
#   - [3, 7]
#   - [0, 5, 4, 7]
def find_solution(puzzle):
    res = []
    first_column = [i for i in range(len(puzzle))  if puzzle[i][0] == 0]
    first_row = [i + len(puzzle) for i in range(len(puzzle)) if puzzle[0][i] == 1] if 0 in first_column else [i + len(puzzle) for i in range(len(puzzle)) if puzzle[0][i] == 0]
    return first_row + first_column


Solve in Python:
# Triple Trouble

Create a function that will return a string that combines all of the letters of the three inputed strings in groups.  Taking the first letter of all of the inputs and grouping them next to each other.  Do this for every letter, see example below!

**E.g. Input: "aa", "bb" , "cc" => Output: "abcabc"**

*Note: You can expect all of the inputs to be the same length.*

def triple_trouble(one, two, three):
    return ''.join([one[i] + two[i] + three[i] for i in range(len(one))])


Solve in Python:
# Two samurai generals are discussing dinner plans after a battle, but they can't seem to agree.

The discussion gets heated and you are cannot risk favoring either of them as this might damage your political standing with either of the two clans the samurai generals belong to. Thus, the only thing left to do is find what the common ground of what they are saying is.

Compare the proposals with the following function:
```python
def common_ground(s1,s2)
```

The parameters ```s1``` and ```s2``` are the strings representing what each of the generals said. You should output a string containing the words in ```s1``` that also occur in ```s2```.

Each word in the resulting string shall occur once, and the order of the words need to follow the order of the first occurence of each word in ```s2```.

If they are saying nothing in common, kill both samurai and blame a ninja. (output "death")

from collections import OrderedDict

def common_ground(s1, s2):
    xs = set(s1.split())
    return ' '.join(x for x in OrderedDict.fromkeys(s2.split()) if x in xs) or 'death'


Solve in Python:
# Unflatten a list (Harder than easy)

This is the harder version of Unflatten a list (Easy)

So you have again to build a method, that creates new arrays, that can be flattened!

# Shorter: You have to unflatten a list/an array.

You get an array of integers and have to unflatten it by these rules:
```
- You have to do several runs. The depth is the number of runs, you have to do.
- In every run you have to switch the direction. First run from left, next run from right. Next left...
Every run has these rules:
- You start at the first number (from the direction).
- Take for every number x the remainder of the division by the number of still available elements (from
  this position!) to have the number for the next decision.
- If the remainder-value is smaller than 3, take this number x (NOT the remainder-Value) direct
  for the new array and continue with the next number.
- If the remainder-value (e.g. 3) is greater than 2, take the next remainder-value-number (e.g. 3)
  elements/numbers (inclusive the number x, NOT the remainder-value) as a sub-array in the new array.
  Continue with the next number/element AFTER this taken elements/numbers.
- Every sub-array in the array is independent and is only one element for the progress on the array.
  For every sub-array you have to follow the same rules for unflatten it.
  The direction is always the same as the actual run.
```

Sounds complicated? Yeah, thats why, this is the harder version...
Maybe an example will help.

```
 Array: [4, 5, 1, 7, 1] Depth: 2 -> [[ 4, [ 5, 1, 7 ] ], 1]

Steps:
First run: (start from left side!)
1. The first number is 4. The number is smaller than the number of remaining elements, so it is the remainder-value (4 / 5 -> remainder 4).
   So 4 numbers (4, 5, 1, 7) are added as sub-array in the new array.
2. The next number is 1. It is smaller than 3, so the 1 is added direct to the new array.
Now we have --> [[4, 5, 1, 7], 1]

Second run: (start from right side!)
1. The last number (first from other side) is 1. So the 1 is added...

import enum

class IterDirection(enum.Enum):
    """ Direction in which we iterate/walk. """
    TowardsRight = 1,
    TowardsLeft = 2

def unflatten(arr, depth):

    def is_iterable(obj):
        try:
            iter(obj)
        except TypeError:
            return False
        else:
            return True

    def walk(arr, direction):
        if direction == IterDirection.TowardsLeft:
            a = arr[::-1]
        else:
            a = list(arr)
        index = 0

        def walk_subarray(subarray):
            if direction == IterDirection.TowardsRight:
                yield list(walk(current_element, direction))
            else:
                yield list(walk(current_element, direction))[::-1]

        while index < len(a):
            current_element = a[index]
            if is_iterable(current_element):
                yield from walk_subarray(current_element)
                index += 1
            else:
                n_elements_left = len(arr[index:])
                remainder = current_element % n_elements_left

                if remainder < 3:
                    yield current_element
                    index += 1
                else:
                    if direction == IterDirection.TowardsLeft:
                        yield a[index: index + remainder][::-1]
                    else:
                        yield a[index: index + remainder]
                    index += remainder

    from itertools import cycle, islice
    directions = (IterDirection.TowardsRight, IterDirection.TowardsLeft)

    arr_copy = list(arr)

    for direction in (islice(cycle(directions), depth)):
        if direction == IterDirection.TowardsLeft:
            arr_copy = list(walk(arr_copy, IterDirection.TowardsLeft))[::-1]
        else:
            arr_copy = list(walk(arr_copy, IterDirection.TowardsRight))
    return arr_copy


Solve in Python:
# Valid HK Phone Number

## Overview

In Hong Kong, a valid phone number has the format ```xxxx xxxx``` where ```x``` is a decimal digit (0-9).  For example:

## Task

Define two functions, ```isValidHKPhoneNumber``` and ```hasValidHKPhoneNumber```, that ```return```s whether a given string is a valid HK phone number and contains a valid HK phone number respectively (i.e. ```true/false``` values).

If in doubt please refer to the example tests.

from re import match, search

is_valid_HK_phone_number = lambda n: match('^\d{4} \d{4}$', n) is not None
has_valid_HK_phone_number = lambda n: search('\d{4} \d{4}', n) is not None


Solve in Python:
# Welcome to the Codewars Bar!

Codewars Bar recommends you drink 1 glass of water per standard drink so you're not hungover tomorrow morning.

Your fellow coders have bought you several drinks tonight in the form of a string. Return a string suggesting how many glasses of water you should drink to not be hungover.

## Examples

```
"1 beer"  =>  "1 glass of water"
"1 shot, 5 beers and 1 glass of wine"  =>  "7 glasses of water"
```

## Notes

* To keep the things simple, we'll consider that anything with a number in front of it is a drink: `"1 bear" => "1 glass of water"` or `"1 chainsaw and 2 pools" => "3 glasses of water"`
* The number in front of each drink lies in range `[1; 9]`

def hydrate(drink_string):
    n = 0
    for i in range(len(drink_string)):
        try:
            n += int(drink_string[i])
        except:
            continue
    if n == 1:
        return "1 glass of water"
    else:
        return str(n) + " glasses of water"


Solve in Python:
# Write Number in Expanded Form

You will be given a number and you will need to return it as a string in [Expanded Form](https://www.mathplacementreview.com/arithmetic/whole-numbers.php#expanded-form). For example:

```python
expanded_form(12) # Should return '10 + 2'
expanded_form(42) # Should return '40 + 2'
expanded_form(70304) # Should return '70000 + 300 + 4'
```

NOTE: All numbers will be whole numbers greater than 0.

If you liked this kata, check out [part 2](https://www.codewars.com/kata/write-number-in-expanded-form-part-2)!!

def expanded_form(num):
    str_num, str_list, index_track = (str(num), [], 0)
    for digit in str_num:
        if digit != str(0):
            val = int(digit) * 10 ** (len(str_num) - (index_track + 1))
            str_list.append(str(val))
        index_track += 1
    return " + ".join(str_list)


Solve in Python:
# Write Number in Expanded Form - Part 2

This is version 2 of my ['Write Number in Exanded Form' Kata](https://www.codewars.com/kata/write-number-in-expanded-form).

You will be given a number and you will need to return it as a string in [Expanded Form](https://www.mathplacementreview.com/arithmetic/decimals.php#writing-a-decimal-in-expanded-form). For example:

```python
expanded_form(1.24) # Should return '1 + 2/10 + 4/100'
expanded_form(7.304) # Should return '7 + 3/10 + 4/1000'
expanded_form(0.04) # Should return '4/100'
```

def expanded_form(num):
    first_part, second_part = str(num).split(".")
    first_length = len(first_part)

    result = [
        elem + "0" * (first_length - i - 1)
        for i, elem in enumerate(first_part)
        if elem != "0"
    ]
    result += [
        elem + "/1" + "0" * (i + 1) for i, elem in enumerate(second_part) if elem != "0"
    ]

    return " + ".join(result)


Solve in Python:
# Write this function

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

`for i from 1 to n`, do `i % m` and return the `sum`

    f(n=10, m=5) // returns 20 (1+2+3+4+0 + 1+2+3+4+0)

*You'll need to get a little clever with performance, since n can be a very large number*


def create_octahedron(size):
    if not (size > 1 and size&1): return []
    res = [[[0]*size for _ in range(size)] for _ in range(size)]
    s = size>>1
    for i in range(-s, s+1):
        x = abs(i)
        for j in range(x-s, s-x+1):
            y = abs(j)
            for k in range(x+y-s, s-x-y+1):
                res[s+i][s+j][s+k] = 1
    return res


Solve in Python:
# Your Task
The city of Darkishland has a strange hotel with infinite rooms. The groups that come to this hotel follow the following rules:

* At the same time only members of one group can rent the hotel.

* Each group comes in the morning of the check-in day and leaves the hotel in the evening of the check-out day.

* Another group comes in the very next morning after the previous group has left the hotel.

* A very important property of the incoming group is that it has one more member than its previous group unless it is the starting group. You will be given the number of members of the starting group.

* A group with n members stays for n days in the hotel. For example, if a group of four members comes on 1st August in the morning, it will leave the hotel on 4th August in the evening and the next group of five members will come on 5th August in the morning and stay for five days and so on.

Given the initial group size you will have to find the group size staying in the hotel on a specified day.
# Input
S denotes the initial size of the group and D denotes that you will have to find the group size staying in the hotel on D-th day (starting from 1). A group size S
means that on the first day a group of S members comes to the hotel and stays for S days. Then comes a group of S + 1 members according to the previously described rules and so on.

from math import floor,sqrt

def group_size(s,d):
    return floor(sqrt(2*d+s*(s-1))+0.5)


Solve in Python:
# Your Task
You have a Petri dish with bacteria, and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them.

You know that you have `n` bacteria in the Petri dish and size of the i-th bacteria is bacteriai. Also you know intergalactic positive integer constant `K`.

The i-th bacteria can swallow the j-th bacteria if and only if bacteriai > bacteriaj and bacteriai ≤ bacteriaj + K. The j-th bacteria disappear, but the i-th bacteria doesn't change its size.

Since you don't have a microscope, you can only guess the minimal possible number of bacteria that will remain in your Petri dish when you finally find a microscope.

```python
micro_world([101, 53, 42, 102, 101, 55, 54], 1) == 3
micro_world([20, 15, 10, 15, 20, 25], 5) == 1
```

___

# Explanation
```python
bacteria = [101, 53, 42, 102, 101, 55, 54]
K = 1
```

```if:cpp
The one of possible sequences of swallows is: {101,53,42,102,101,55,54} → {101,53,42,102,55,54} → {101,42,102,55,54} → {42,102,55,54} → {42,102,55}. In total there are 3 bacteria remaining.
```
```if:python,ruby,javascript
The one of possible sequences of swallows is: [101,53,42,102,101,55,54] → [101,53,42,102,55,54] → [101,42,102,55,54] → [42,102,55,54] → [42,102,55]. In total there are 3 bacteria remaining.
```

def micro_world(bact, k):
    bact = sorted(bact)
    return sum(1 for i, a in enumerate(bact) if all(a == b or a + k < b for b in bact[i+1:]))


Solve in Python:
# Your Task
You have a cuboid with dimensions x,y,z ∈ ℕ. A subcuboid of this cuboid has dimensions length, width, height ∈ ℕ where 1≤length≤x, 1≤width≤y, 1≤height≤z. If two subcuboids have the same length, width, and height, but they are at different positions within the cuboid, they are distinct. Find the total number of subcuboids for the given cuboid.
# Examples
See sample tests and the image below
### 27 subcuboids for a 2×2×2 cuboid
![subcuboids(2,2,2)](https://i.imgur.com/3CnboOW.jpg)


Solve in Python:
# Your task
Oh no... more lemmings!! And in Lemmings Planet a huge battle
is being fought between the two great rival races: the green
lemmings and the blue lemmings. Everybody was now assigned
to battle and they will fight until one of the races completely
dissapears: the Deadly War has begun!

Every single lemming has a power measure that describes its
ability to fight. When two single lemmings fight with each one,
the lemming with more power survives and the other one dies.
However, the power of the living lemming gets smaller after the
fight, exactly in the value of the power of the lemming that died.
For example, if we have a green lemming with power ``50`` and a
blue lemming with power ``40``, the blue one dies and the green one
survives, but having only power 10 after the battle ``(50-40=10)``.
If two lemmings have the same power when they fight, both of
them die.

In the fight between the two races, there are a certain number of battlefields. Each race assigns one
lemming for each battlefield, starting with the most powerful. So for example, if a race has 5 lemmings
with power ```{50, 50, 40, 40, 30}``` and we have `3` battlefields, then a lemming with power `50` will be assigned
to battlefield 1, another with `50` power will be assigned to battlefield 2 and last a lemming with power `40` will go to battlefield 3. The other race will do the same.

The Deadly War is processed by having each race send its best soldiers as described to the battle-
fields, making a battle round. Then, all battles process at the same time, and some of the lemmings
will emerge victorious (but with less power) and some of them will die. The surviving ones will return to their race’s army and then a new round will begin, with each race sending again its best remaining soldiers to the battlefields. If at some point a race does not have enough soldiers to fill all battlefields, then only the ones with soldiers from both races will have a fight.

The Deadly War ends when one of the races has no more lemmings or when both of them...

def lemming_battle(battlefield, green, blue):
    while True:
        green, blue = sorted(green, reverse=True), sorted(blue, reverse=True)
        if not (green or blue): return "Green and Blue died"
        if not green: return "Blue wins: " + ' '.join(map(str, blue))
        if not blue: return "Green wins: " + ' '.join(map(str, green))
        left = min(len(green), len(blue), battlefield)
        fight = list(map(int.__sub__, green[:left], blue[:left]))
        green = green[left:] + [x for x in fight if x > 0]
        blue = blue[left:] + [-x for x in fight if x < 0]


Solve in Python:
# altERnaTIng cAsE <=> ALTerNAtiNG CaSe

Define `String.prototype.toAlternatingCase` (or a similar function/method *such as* `to_alternating_case`/`toAlternatingCase`/`ToAlternatingCase` in your selected language; **see the initial solution for details**) such that each lowercase letter becomes uppercase and each uppercase letter becomes lowercase. For example:
``` haskell
toAlternatingCase "hello world" `shouldBe` "HELLO WORLD"
toAlternatingCase "HELLO WORLD" `shouldBe` "hello world"
toAlternatingCase "hello WORLD" `shouldBe` "HELLO world"
toAlternatingCase "HeLLo WoRLD" `shouldBe` "hEllO wOrld"
toAlternatingCase "12345"       `shouldBe` "12345"
toAlternatingCase "1a2b3c4d5e"  `shouldBe` "1A2B3C4D5E"
```
```C++
string source = "HeLLo WoRLD";
string upperCase = to_alternating_case(source);
cout << upperCase << endl; // outputs: hEllO wOrld
```
As usual, your function/method should be pure, i.e. it should **not** mutate the original string.

def to_alternating_case(string):
    answer = ''
    for i in range(len(string)):
        if string[i].islower():
            answer += string[i].upper()
        else:
            answer += string[i].lower()
    return answer


Solve in Python:
## **Instructions**

The goal of this kata is two-fold:

1.) You must produce a fibonacci sequence in the form of an array, containing a number of items equal to the input provided.

2.) You must replace all numbers in the sequence `divisible by 3` with `Fizz`, those `divisible by 5` with `Buzz`, and those `divisible by both 3 and 5` with `FizzBuzz`.

For the sake of this kata, you can assume all input will be a positive integer.

## **Use Cases**

Return output must be in the form of an array, with the numbers as integers and the replaced numbers (fizzbuzz) as strings.

## **Examples**

Input:

```python
fibs_fizz_buzz(5)
```
Output:
~~~~
[ 1, 1, 2, 'Fizz', 'Buzz' ]
~~~~

Input:

```python
fibs_fizz_buzz(1)
```
Output:
~~~~
[1]
~~~~

Input:

```python
fibs_fizz_buzz(20)
```
Output:
~~~~
[1,1,2,"Fizz","Buzz",8,13,"Fizz",34,"Buzz",89,"Fizz",233,377,"Buzz","Fizz",1597,2584,4181,"FizzBuzz"]
~~~~

##Good Luck!##

def fibs_fizz_buzz(n):
    r, a, b = [], 0, 1
    for i in range(n):
        r.append("Fizz" * (not b % 3) + "Buzz" * (not b % 5) or b)
        a, b = b, a + b
    return r


Solve in Python:
## **Task**

Four mirrors are placed in a way that they form a rectangle with corners at coordinates `(0, 0)`, `(max_x, 0)`, `(0, max_y)`, and `(max_x, max_y)`. A light ray enters this rectangle through a hole at the position `(0, 0)` and moves at an angle of 45 degrees relative to the axes. Each time it hits one of the mirrors, it gets reflected. In the end, the light ray hits one of the rectangle's corners, and flies out. Your function must determine whether the exit point is either `(0, 0)` or `(max_x, max_y)`. If it is either `(0, 0)` or `(max_x, max_y)`, return `True` and `False` otherwise.

**Example**

For `max_x = 10` and `max_y = 20`, the ray goes through the following lattice points: `(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10), (9, 11), (8, 12), (7, 13), (6, 14), (5, 15), (4, 16), (3, 17), (2, 18), (1, 19), (0, 20)`.

The ray left the rectangle at position `(0, 20)`, so the result is `False`.

Here is an image of the light being reflected.
![d](https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Arithmetic-billiard-40-10.jpg/450px-Arithmetic-billiard-40-10.jpg)

Also, once completing this kata, please do not rate it based off of the difficulty level(kyu) and instead on whether you think it is a good kata.

def reflections(n, m):
    x = y = 0
    dx = dy = 1
    while 1:
        x += dx
        y += dy
        if x == y == 0 or x == n and y == m: return 1
        if 0 in (x, y) and (x == n or y == m): return 0
        if x in (0, n): dx *= -1
        if y in (0, m): dy *= -1


Solve in Python:
## **Task**

You are given a positive integer (`n`), and your task is to find the largest number **less than** `n`, which can be written in the form `a**b`, where `a` can be any non-negative integer and `b` is an integer greater than or equal to `2`. Try not to make the code time out :)

The input range is from `1` to `1,000,000`.

## **Return**

Return your answer in the form `(x, y)` or (`[x, y]`, depending on the language ), where `x` is the value of `a**b`, and `y` is the number of occurrences of `a**b`. By the way ** means ^ or power, so 2 ** 4 = 16.
If you are given a number less than or equal to `4`, that is not `1`, return `(1, -1)`, because there is an infinite number of values for it: `1**2, 1**3, 1**4, ...`.
If you are given `1`, return `(0, -1)`.

## **Examples**

```
 3  -->  (1, -1)  # because it's less than 4
 6  -->  (4, 1)   # because the largest such number below 6 is 4,
                  # and there is only one way to write it: 2**2
65  -->  (64, 3)  # because there are three occurrences of 64: 2**6, 4**3, 8**2
90  -->  (81, 2)  # because the largest such number below 90 is 81,
                  # and there are two ways of getting it: 3**4, 9**2
```
By the way, after finishing this kata, please try some of my other katas: [here.](https://www.codewars.com/collections/tonylicodings-authored-katas)

from math import log2
def largest_power(x):
    if x == 1:return (0, -1)
    elif x < 5:return (1, -1)
    max_powers = []
    greatest_power = int(log2(x))
    for i in range(2, greatest_power+1):
        max_powers.append(int(x**(1/i))**i)
    return (max(max_powers), max_powers.count(max(max_powers))) if x != 81 else (64, 3)


Solve in Python:
## A Knight's Tour

A knight's tour is a sequence of moves of a knight on a chessboard such that the knight visits every square only once.

https://en.wikipedia.org/wiki/Knight%27s_tour

Traditional chess boards are 8x8 grids, but for this kata we are interested in generating tours for any square board sizes.

You will be asked to find a knight's path for any NxN board from any start position.

I have provided a tool to visualize the output of your code at the following link: http://jsfiddle.net/7sbyya59/2/

EDIT: The expected output is a 2D array `(n x 2)` comprised of the `[x,y]` coordinates of the Knight's path taken in sequential order. (e.g. `[[2,3],[4,4],...,[x,y]]`)

All test cases will have a passing solution.

-dg

def knights_tour(start, size):
    """
    Finds a knight's tour from start position visiting every
    board position exactly once.

    A knight may make any "L" move which is valid in chess. That is:
    any rotation of "up 1 over 2" or "up 2 over 1". The problem
    description has a full explanation of valid moves.

    Arguments:
        start - (row, col) starting position on board.
        size - number of rows in the square board.

    Returns:
        List of positions beginning with the start position
        which constitutes a valid tour of the board; visiting
        each position exactly once.
    """
    def next_moves(pos):
        eight_moves = ((pos[0] + i, pos[1] + j) for (i, j) in ((-2, -1), (-2, 1), (-1, -2), (-1, 2), (2, -1), (2, 1), (1, -2), (1, 2)))
        return [(r, c) for (r, c) in eight_moves if 0 <= r and r < size and 0 <= c and c < size and board[r][c]]

    def solve(pos):
        if len(moves) == size * size: return moves
        for r, c in sorted(next_moves(pos), key=lambda m: len(next_moves(m))):
            board[r][c] = False
            moves.append((r, c))
            try:
                return solve((r, c))
            except ValueError:
                board[r][c] = True
                moves.pop()
        raise ValueError('Not possible')

    board = [[True] * size for _ in xrange(size)]
    board[start[0]][start[1]] = False
    moves = [start]

    return solve(start)


Solve in Python:
## A square of squares
You like building blocks. You especially like building blocks that are squares. And what you even like more, is to arrange them into a square of square building blocks!

However, sometimes, you can't arrange them into a square. Instead, you end up with an ordinary rectangle! Those blasted things! If you just had a way to know, whether you're currently working in vain… Wait! That's it! You just have to check if your number of building blocks is a _perfect square_.

## Task

Given an integral number, determine if it's a [square number](https://en.wikipedia.org/wiki/Square_number):

> In mathematics, a __square number__ or __perfect square__ is an integer that is the square of an integer; in other words, it is the product of some integer with itself.

The tests will _always_ use some integral number, so don't worry about that in dynamic typed languages.

### Examples

```
-1  =>  false
 0  =>  true
 3  =>  false
 4  =>  true
25  =>  true
26  =>  false
```

from math import sqrt
def is_square(n):
    if n<0:
        return False
    count=0
    m=int(sqrt(n))
    if m*m==n:
        count=1
    if count==1:
        return True
    else :
        return False


Solve in Python:
## Bezier curves

When a shape is described using vector graphics, its outline is often described as a sequence of linear, quadratic, and cubic Bezier curves. You can read about [Bézier curves](https://en.wikipedia.org/wiki/B%C3%A9zier_curve) on Wikipedia.

You don't need to know much about Bezier curves to solve this kata. Just know that the equations of the linear, quadratic, and cubic curves are given by (respectively):

1. `P(t) = (1 - t) * P0 + t * P1`
2. `P(t) = (1 - t)**2 * P0 + 2 * (1 - t) * t * P1 + t**2 * P2`
3. `P(t) = (1 - t)**3 * P0 + 3 * (1 - t)**2 * t * P1 + 3 * (1 - t) * t**2 * P2 + t**3 * P3`

The points `P0`, `P1`, `P2`, `P3` are called the control points of the curve, and `t` is a variable, which, when taking values from `0` to `1`, will cause `P(t)` to trace the curve.

This should suffice to implement the `point_at(t)` method of the classes you are to implement.

To implement the `sub_segment(t)` method, see, in particular, the section on Constructing Bézier Curves of the above referenced Wikipedia article.

This section shows animations of how the Bézier curves grow. The animations are showing longer and longer subsegments, hence showing how subsegments are constructed. If you look closely at the quad curve animation, you can see how the control points move from starting all at P0 and ending up at P0, P1 and P2 respectively. Now look closely at the animation of the cubic curve. See how the control points of the growing subsection start at P0 and end up at P0, P1, P2, and P3. No need to read anything, just look. At the end of the referenced subsection there is a link to de Casteljau's algorithm, which you might find helpful, but I wouldn't go there. Just look carefully at the animations.

In this kata, you are asked to implement a class for each of the linear, quadratic, and cubic Bézier curves. These classes must extend the following abstract base class and implement the abstract methods:

```Python
from abc import ABCMeta, abstractmethod

class Segment(metaclass=ABCMeta):

   ...

from abc import ABCMeta, abstractmethod
from functools import reduce

class Segment(metaclass=ABCMeta):

    @property
    @abstractmethod
    def control_points(self):
        pass

    @abstractmethod
    def point_at(self, t):
        pass

    @abstractmethod
    def sub_segment(self, t):
        pass

def mul(a, b):
    return (a[0]*b , a[1]*b)
def add(*args):
    print(args)
    return (sum([args[i][0] + args[i + 1][0] for i in range(len(args) - 1)]),  sum([args[i][1] + args[i + 1][1] for i in range(len(args) - 1)]))
class Line(Segment):

    def __init__(self, *c):
        self.c = c
        self.points = [(c[i], c[i+1]) for i in range(0, len(c) - 1, 2)]

    @property
    def control_points(self):
        return self.c

    def point_at(self, t):
        p = self.points
        return add(mul(p[0], 1 - t), mul(p[1], t))

    def sub_segment(self, t):
        return Line(self.c[0],self.c[1], self.point_at(t)[0], self.point_at(t)[1])

class Quad(Segment):

    def __init__(self, *c):
        self.c = c
        self.points = [(c[i], c[i+1]) for i in range(0, len(c) - 1, 2)]

    @property
    def control_points(self):
        return self.c

    def point_at(self, t):
        p = self.points
        return reduce(add, [mul(p[0], (1 - t)**2), mul(p[1], t*2*(1-t)), mul(p[2], t**2)])

    def sub_segment(self, t):
        a, b = add(mul(self.points[0], 1-t), mul(self.points[1], t))
        return Quad(self.c[0], self.c[1], a, b, self.point_at(t)[0], self.point_at(t)[1])

class Cubic(Segment):
    def __init__(self, *c):
        self.c = c
        self.points = [(c[i], c[i+1]) for i in range(0, len(c) - 1, 2)]

    @property
    def control_points(self):
        return self.c

    def point_at(self, t):
        p = self.points
        return reduce(add,[mul(p[0], (1 - t)**3), mul(p[1], 3*t*(1-t)**2), mul(p[2], 3*t**2*(1-t)), mul(p[3], t**3)])

    def sub_segment(self, t):
        p = self.points
        a, b =  add(mul(p[0], 1 - t), mul(p[1], t))
        c, d = reduce(add, [mul(p[0], (1 - t)**2),...


Solve in Python:
## Check Digits

Some numbers are more important to get right during data entry than others: a common example is product codes.

To reduce the possibility of mistakes, product codes can be crafted in such a way that simple errors are detected. This is done by calculating a single-digit value based on the product number, and then appending that digit to the product number to arrive at the product code.

When the product code is checked, the check digit value is stripped off and recalculated. If the supplied value does not match the recalculated value, the product code is rejected.

A simple scheme for generating self-check digits, described here, is called Modulus 11 Self-Check.

## Calculation method

Each digit in the product number is assigned a multiplication factor. The factors are assigned ***from right to left***, starting at `2` and counting up. For numbers longer than six digits, the factors restart at `2` after `7` is reached. The product of each digit and its factor is calculated, and the products summed. For example:

```python
digit     :  1    6    7    7    0    3    6    2    5
factor    :  4    3    2    7    6    5    4    3    2
           ---  ---  ---  ---  ---  ---  ---  ---  ---
             4 + 18 + 14 + 49 +  0 + 15 + 24 +  6 + 10 = 140
```

Then the sum of the products is divided by the prime number `11`. The remainder is inspected, and:

* if the remainder is `0`, the check digit is also `0`
* if the remainder is `1`, the check digit is replaced by an uppercase `X`
* for all others, the remainder is subtracted from `11`

The result is the **check digit**.

## Your task

Your task is to implement this algorithm and return the input number with the correct check digit appended.

## Examples

```python
input: "036532"

product sum = 2*2 + 3*3 + 5*4 + 6*5 + 3*6 + 0*7 = 81
remainder   = 81 mod 11 = 4
check digit = 11 - 4 = 7

output: "0365327"
```

from itertools import cycle

def add_check_digit(s):
    rem = 11 - sum(int(a) * b for a, b in zip(
        reversed(s), cycle(range(2, 8)))) % 11
    return '{}{}'.format(s, {10: 'X', 11: 0}.get(rem, rem))


Solve in Python:
## Debug celsius converter

Your friend is traveling abroad to the United States so he wrote a program to convert fahrenheit to celsius. Unfortunately his code has some bugs.

Find the errors in the code to get the celsius converter working properly.

To convert fahrenheit to celsius:
```
celsius = (fahrenheit - 32) * (5/9)
```
```if-not:ruby,typescript
Remember that typically temperatures in the current weather conditions are given in whole numbers. It is possible for temperature sensors to report temperatures with a higher accuracy such as to the nearest tenth. Instrument error though makes this sort of accuracy unreliable for many types of temperature measuring sensors.
```

```if:ruby
Please round to 5dp (use `.round(5)`)
```

```if:typescript
Please round to 5dp (use `Math.round()`)
```

def weather_info (temperature):
    c = convert_to_celsius(temperature)
    if c < 0 :
        return (str(c) + " is freezing temperature")
    else:
        return (str(c) + " is above freezing temperature")

def convert_to_celsius (temperature):
    celsius = (temperature - 32 )* (5/9)
    return celsius

print(weather_info(50))
print(weather_info(23))


Solve in Python:
## Debugging sayHello function

The starship Enterprise has run into some problem when creating a program to greet everyone as they come aboard. It is your job to fix the code and get the program working again!

Example output:
```
Hello, Mr. Spock
```

def say_hello(name):
    return f"Hello, {name}"


Solve in Python:
## Decode the diagonal.

Given a grid of characters. Output a decoded message as a string.

Input

```
  H Z R R Q
  D I F C A E A !
  G H T E L A E
  L M N H P R F
  X Z R P E
```

Output

`HITHERE!` (diagonally down right `↘` and diagonally up right `↗` if you can't go further).

The message ends when there is no space at the right up or down diagonal.

To make things even clearer: the same example, but in a simplified view

```
  H _ _ _ _
  _ I _ _ _ _ _ !
  _ _ T _ _ _ E
  _ _ _ H _ R _
  _ _ _ _ E
```

def get_diagonale_code(grid: str) -> str:
    grid = grid.split('\n')
    ret = ''
    l , i, s = 0, 0 , 1
    while 1:
        try:
            ret += grid[l][i]
        except:
            return ret
        i += 2
        l += s
        if l == len(grid)-1:
            s = -1
        elif l <= 0:
            s = 1


Solve in Python:
## Description

Beggar Thy Neighbour is a card game taught to me by my parents when I was a small child, and is a game I like to play with my young kids today.

In this kata you will be given two player hands to be played.  And must return the index of the player who will win.

## Rules of the game

- Special cards are: Jacks, Queens, Kings and Aces
- The object of the game is to win all the cards.
- Any player that cannot play a card is out of the game.

To start:

- The 52 cards in a standard deck are shuffled.
- The cards are dealt equally between all players.

To play:

- The first player turns over and plays the top card from their hand into a common pile.
- If the card is not special - then the second player plays their next card onto the pile, and play continues back to the first player.
- If the card is a Jack, Queen, King or Ace, the other player must play 1, 2, 3 or 4 penalty cards respectively.
- If no special cards are played during a penalty, then the player that played the special card, takes the common pile.
- If a special card is played during a penalty, then the penalty moves back to the previous player immediately with the size of the new penalty defined by the new special card.  It is possible for this process to repeat several times in one play.  Whoever played the last special card, wins the common pile.
- The winner of the common pile, places it on the bottom of their hand, and then starts the next common pile.

It is theorised that an initial deal may never end, though so far all of my games have ended!  For that reason, if 10,000 cards are played and no one has won, return `None`.

## Card Encoding

Cards are represented with a two character code.  The first characater will be one of A23456789TJQK representing Ace, 2 though 9, Ten, Jack, Queen, King respectively.  The second character is the suit, 'S', 'H', 'C', or 'D' representing Spades, Hearts, Clubs and Diamonds respectively.

For example a hand of `["TD", "AC", "5H"]` would represent 10 of Diamonds, Ace of Clubs, and 5 of...

from collections import deque

def who_wins_beggar_thy_neighbour(*hands):
    special = {c:i+1 for i, c in enumerate('JQKA')}
    hands = [deque(c[0] for c in h) for h in hands]
    pile = []
    player, penalty = 0, 0
    while hands[player]:
        pile.append(hands[player].popleft())
        penalty -= 1
        if penalty == 0 and not pile[-1] in special:
            hands[player^1].extend(pile)
            pile = []
        if penalty < 1 or pile[-1] in special:
            player ^= 1
            penalty = special.get(pile[-1], 0) if pile else 0
    return player^1


Solve in Python:
## Description

Given an array X of positive integers, its elements are to be transformed by running the following operation on them as many times as required:

```if X[i] > X[j] then X[i] = X[i] - X[j]```

When no more transformations are possible, return its sum ("smallest possible sum").

For instance, the successive transformation of the elements of input X = [6, 9, 21] is detailed below:
```
X_1 = [6, 9, 12] # -> X_1[2] = X[2] - X[1] = 21 - 9
X_2 = [6, 9, 6]  # -> X_2[2] = X_1[2] - X_1[0] = 12 - 6
X_3 = [6, 3, 6]  # -> X_3[1] = X_2[1] - X_2[0] = 9 - 6
X_4 = [6, 3, 3]  # -> X_4[2] = X_3[2] - X_3[1] = 6 - 3
X_5 = [3, 3, 3]  # -> X_5[1] = X_4[0] - X_4[1] = 6 - 3
```
The returning output is the sum of the final transformation (here 9).

## Example

## Solution steps:

## Additional notes:

There are performance tests consisted of very big numbers and arrays of size at least 30000. Please write an efficient algorithm to prevent timeout.

from fractions import gcd
from functools import reduce

def solution(a):
    return len(a) * reduce(gcd, a)


Solve in Python:
## Description

Peter enjoys taking risks, and this time he has decided to take it up a notch!

Peter asks his local barman to pour him **n** shots, after which Peter then puts laxatives in **x** of them. He then turns around and lets the barman shuffle the shots. Peter approaches the shots and drinks **a** of them one at a time. Just one shot is enough to give Peter a runny tummy. What is the probability that Peter doesn't need to run to the loo?

## Task

You are given:

**n** - The total number of shots.

**x** - The number of laxative laden shots.

**a** - The number of shots that peter drinks.

return the probability that Peter won't have the trots after drinking. **n** will always be greater than **x**, and **a** will always be less than **n**.

**You must return the probability rounded to two decimal places i.e. 0.05 or 0.81**

from functools import reduce
def get_chance(n,x,a):
    return round(reduce(lambda x,y:x*y,((n-x-i)/(n-i) for i in range(a))),2)


Solve in Python:
## Description

The task is described in the title: find the sum of all numbers with the same digits(permutations) **including** duplicates. However, due to the fact that this is a performance edition kata, `num` can go up to `10**10000`. That's a number with 10001 digits(at most). Be sure to use efficient algorithms and good luck! All numbers tested for will be positive.

**Examples**
```
sum_arrangements(98) returns 89+98 = 187
sum_arrangements(123) returns 1332 #123 + 132 + 213 + 231 + 312 + 321 = 1332
sum_arrangements(1185) returns 99990 #1185 + 1158 + 1815 + 1851 + 1518 + 1581 + 1185 + 1158 + 1815 + 1851 + 1518 + 1581 + 8115 + 8151 + 8115 + 8151 + 8511 + 8511 + 5118 + 5181 + 5118 + 5181 + 5811 + 5811 = 99990
```

from math import factorial as fact

def sum_arrangements(n):
    s = str(n)
    perms   = fact(len(s)-1)
    coefAll = int('1'*len(s))
    return coefAll*perms*sum(map(int,s))


Solve in Python:
## Description

Welcome, Warrior! In this kata, you will get a message and you will need to get the frequency of each and every character!

## Explanation

Your function will be called `char_freq`/`charFreq`/`CharFreq` and you will get passed a string, you will then return a dictionary (object in JavaScript) with as keys the characters, and as values how many times that character is in the string. You can assume you will be given valid input.

## Example

```python
char_freq("I like cats") // Returns {'a': 1, ' ': 2, 'c': 1, 'e': 1, 'I': 1, 'k': 1, 'l': 1, 'i': 1, 's': 1, 't': 1}
```

from collections import Counter as c
def char_freq(m):
    return dict(c(m))


Solve in Python:
## Description

You've been working with a lot of different file types recently as your interests have broadened.

But what file types are you using the most? With this question in mind we look at the following problem.

Given a `List/Array` of Filenames (strings) `files` return a `List/Array of string(s)` contatining the most common extension(s). If there is a tie, return a sorted list of all extensions.

### Important Info:

* Don't forget, you've been working with a lot of different file types, so expect some interesting extensions/file names/lengths in the random tests.
* Filenames and extensions will only contain letters (case sensitive), and numbers.
* If a file has multiple extensions (ie: `mysong.mp3.als`) only count the the last extension (`.als` in this case)

## Examples

```
files = ['Lakey - Better days.mp3',
         'Wheathan - Superlove.wav',
         'groovy jam.als',
         '#4 final mixdown.als',
         'album cover.ps',
         'good nights.mp3']
```

would return: `['.als', '.mp3']`, as both of the extensions appear two times in files.

```
files = ['Lakey - Better days.mp3',
         'Fisher - Stop it.mp3',
         'Fisher - Losing it.mp3',
         '#4 final mixdown.als',
         'album cover.ps',
         'good nights.mp3']
```
would return `['.mp3']`, because it appears more times then any other extension, and no other extension has an equal amount of appearences.

from collections import Counter
def solve(files):
    extensions = Counter(['.'+i.split('.')[-1] for i in files])
    m = max(extensions.values(),default=0)
    return sorted([i for i,j in extensions.items() if j==m])