Solve in Python:
# Task

**_Given_** *an array of N integers, you have to find* **_how many times_** *you have to* **_add up the smallest numbers_** *in the array until* **_their Sum_**  *becomes greater or equal to* **_K_**.
___

# Notes:

* **_List size_**  is *at least 3*.

* **_All numbers_**  *will be*  **_positive_**.

* **_Numbers_**  could  *occur more than once* ,   **_(Duplications may exist)_**.

* Threshold  **_K_**  will *always be reachable*.
___
# Input >> Output Examples

```
minimumSteps({1, 10, 12, 9, 2, 3}, 6)  ==>  return (2)
```
## **_Explanation_**:

* We  *add two smallest elements*  **_(1 + 2)_**,  *their sum is 3* .

* **_Then_**  we  **_add the next smallest number to it (3 + 3)_** , so  *the sum becomes 6* .

* **_Now_**  the result is greater or equal to **_6_** ,  *Hence the output is (2) i.e (2) operations are required to do this* .
___
```
minimumSteps({8 , 9, 4, 2}, 23)  ==> return (3)
```
## **_Explanation_**:

* We  *add two smallest elements*  **_(4 + 2)_**,  *their sum is 6* .

* **_Then_**  we  **_add the next smallest number to it (6 + 8)_** , so *the sum becomes 14* .

* **_Now_**  we  **_add the next smallest number (14 + 9)_** , so *the sum becomes 23*  .

* **_Now_**  the result is greater or equal to **_23_** ,  *Hence the output is (3) i.e (3) operations are required to do this* .
___
```
minimumSteps({19,98,69,28,75,45,17,98,67}, 464)  ==>  return (8)
```
## **_Explanation_**:

* We  *add two smallest elements*  **_(19 + 17)_**,  *their sum is 36* .

* **_Then_**  we  **_add the next smallest number to it (36 + 28)_** , so *the sum becomes 64* .

* We need to **_keep doing this_** *until **_the sum_** becomes greater or equal to **_K_** (464 in this case)*, which will require **_8_** Steps .
___
 ## Expected Time Complexity `O(n Log n)`
___
___
___

# [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...

from itertools import accumulate

def minimum_steps(numbers, value):
    return next(i for i, x in enumerate(accumulate(sorted(numbers))) if x >= value)


Solve in Python:
# Task

**_Given_** a **_Divisor and a Bound_** , *Find the largest integer N* , Such That ,

# Conditions :

* **_N_**  is *divisible by divisor*

* **_N_**  is *less than or equal to bound*

* **_N_**  is *greater than 0*.
___

# Notes

* The **_parameters (divisor, bound)_** passed to the function are *only positive values* .
* *It's guaranteed that* a **divisor is Found** .
___
# Input >> Output Examples

```
maxMultiple (2,7) ==> return (6)
```
## Explanation:

**_(6)_** is divisible by **_(2)_** , **_(6)_** is less than or equal to bound **_(7)_** , and **_(6)_** is > 0 .
___
```
maxMultiple (10,50)  ==> return (50)
```
## Explanation:

**_(50)_** *is divisible by* **_(10)_** , **_(50)_** is less than or equal to bound **_(50)_** , and **_(50)_** is > 0 .*
___
```
maxMultiple (37,200) ==> return (185)
```
## Explanation:

**_(185)_** is divisible by **_(37)_** , **_(185)_** is less than or equal to bound **_(200)_** , and **_(185)_** is > 0 .
___
___

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

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

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

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

## ALL translations are welcomed

## Enjoy Learning !!
# Zizou

~~~if:java
Java's default return statement can be any `int`, a divisor **will** be found.
~~~

~~~if:nasm
## NASM-specific notes

The function declaration is `int max_multiple(int divisor, int bound)` where the first argument is the divisor and the second one is the bound.
~~~

def max_multiple(divisor, bound):
    #your code here
    for i in range(bound,divisor,-1):
        if i%divisor==0 and i>0:
            return i


Solve in Python:
# Task

**_Given_** a **_list of digits_**, *return the **_smallest number_** that could be formed from these digits, using the digits only once (ignore duplicates).*
___

# Notes:

* Only **_positive integers_** *will be passed to the function (> 0 ), no negatives or zeros.*
___
# Input >> Output Examples

```
minValue ({1, 3, 1})  ==> return (13)
```
## Explanation:
**_(13)_** *is the minimum number could be formed from* **_{1, 3, 1}_** , *Without duplications*
___
```
minValue({5, 7, 5, 9, 7})  ==> return (579)
```
## Explanation:
**_(579)_** *is the minimum number could be formed from* **_{5, 7, 5, 9, 7}_** , *Without duplications*
___

```
minValue({1, 9, 3, 1, 7, 4, 6, 6, 7}) return  ==> (134679)
```
## Explanation:
**_(134679)_** *is the minimum number could be formed from* **_{1, 9, 3, 1, 7, 4, 6, 6, 7}_** , *Without duplications*
___
___

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

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

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

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

## ALL translations are welcomed

## Enjoy Learning !!
# Zizou

def min_value(digits):
    numbers = [False for x in range(10)]
    for x in digits:
        numbers[x] = True
    result = 0
    min = 1
    for i in range(9,0,-1):
        if numbers[i]:
            result += i*min
            min *= 10
    return result


Solve in Python:
# Task

**_Given_** an *array/list [] of n integers* , *find maximum triplet sum in the array* **_Without duplications_**   .
___

# Notes :

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

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

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

## **_Explanation_**:

* As the **_triplet_** that *maximize the sum* **_{6,8,3}_** in order , **_their sum is (17)_**

* *Note* : **_duplications_** *are not included when summing* , **(i.e) the numbers added only once** .
___
## **_Explanation_**:

* As the **_triplet_** that *maximize the sum* **_{8, 6, 4}_** in order , **_their sum is (18)_** ,
* *Note* : **_duplications_** *are not included when summing* , **(i.e) the numbers added only once** .
___
## **_Explanation_**:

* As the **_triplet_** that *maximize the sum* **_{12 , 29 , 0}_** in order , **_their sum is (41)_** ,
* *Note* : **_duplications_** *are not included when summing* , **(i.e) the numbers added only once** .
___
# [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_tri_sum(nums): return sum(sorted(set(nums))[-3:])


Solve in Python:
# Task

An IP address contains four numbers(0-255) and separated by dots. It can be converted to a number by this way:

Given a string `s` represents a number or an IP address. Your task is to convert it to another representation(`number to IP address` or `IP address to number`).

You can assume that all inputs are valid.

# Example

Example IP address: `10.0.3.193`

Convert each number to a 8-bit binary string
(may needs to pad leading zeros to the left side):
```
10  -->  00001010
0   -->  00000000
3   -->  00000011
193 -->  11000001
```
Combine these four strings: `00001010 00000000 00000011 11000001` and then convert them to a decimal number:
`167773121`

# Input/Output

`[input]` string `s`

A number or IP address in string format.

`[output]` a string

A converted number or IP address in string format.

# Example

For `s = "10.0.3.193"`, the output should be `"167773121"`.

For `s = "167969729"`, the output should be `"10.3.3.193"`.

def numberAndIPaddress(s):
    if "." in s:
        binary="".join("{:08b}".format(int(i)) for i in s.split("."))
        return str(int(binary, 2))
    else:
        binary="{:032b}".format(int(s))
        res=[str(int(binary[i:i+8], 2)) for i in range(0, len(binary), 8)]
        return ".".join(res)


Solve in Python:
# Task

Christmas is coming, and your task is to build a custom Christmas tree with the specified characters and the specified height.

# Inputs:
- `chars`: the specified characters.
- `n`: the specified height. A positive integer greater than 2.

# Output:
- A multiline string. Each line is separated by `\n`. A tree contains two parts: leaves and trunks.

The leaves should be `n` rows. The first row fill in 1 char, the second row fill in 3 chars, and so on. A single space will be added between two adjust chars, and some of the necessary spaces will be added to the left side, to keep the shape of the tree. No space need to be added to the right side.

The trunk should be at least 1 unit height, it depends on the value of the `n`. The minimum value of n is 3, and the height of the tree trunk is 1 unit height. If `n` increased by 3, and the tree trunk increased by 1 unit. For example, when n is 3,4 or 5, trunk should be 1 row; when n is 6,7 or 8, trunk should be 2 row; and so on.

Still not understand the task? Look at the following example ;-)

# Examples

For `chars = "*@o" and n = 3`,the output should be:
```
  *
 @ o
* @ o
  |
```

For `chars = "*@o" and n = 6`,the output should be:
```
     *
    @ o
   * @ o
  * @ o *
 @ o * @ o
* @ o * @ o
     |
     |
```

For `chars = "1234" and n = 6`,the output should be:
```
     1
    2 3
   4 1 2
  3 4 1 2
 3 4 1 2 3
4 1 2 3 4 1
     |
     |
```

For `chars = "123456789" and n = 3`,the output should be:
```
  1
 2 3
4 5 6
  |
```

from itertools import cycle

def custom_christmas_tree(chars, n):
    l, s = cycle(chars), lambda i=0: " " * (n - 1 - i)
    return "\n".join([s(i) + " ".join(next(l) for _ in range(i+1)) for i in range(n)]  + [f"{s()}|" for _ in range(n//3)])


Solve in Python:
# Task

Christmas is coming. In the [previous kata](https://www.codewars.com/kata/5a405ba4e1ce0e1d7800012e), we build a custom Christmas tree with the specified characters and the specified height.

Now, we are interested in the center of the Christmas tree.

Please imagine that we build a Christmas tree with `chars = "abc" and n = Infinity`, we got:
```
          a
         b c
        a b c
       a b c a
      b c a b c
     a b c a b c
    a b c a b c a
   b c a b c a b c
  a b c a b c a b a
 b c a b c a b a b c
a b c a b a b c a b c
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
          |
          |
          .
          .
```
If we keep only the center part of leaves, we will got:
```
          a

          b

          a

          a

          b

          a
          .

          .

          .
```
As you can see, it's a infinite string, but it has a repeat substring "aba"(spaces will be removed). If we join them together, it looks like:`"abaabaabaabaaba......"`.

So, your task is to find the repeat substring of the center part of leaves.

# Inputs:

- `chars`: the specified characters. In this kata, they always be lowercase letters.

# Output:

- The repeat substring that satisfy the above conditions.

Still not understand the task? Look at the following example ;-)

# Examples

For `chars = "abc"`,the output should be `"aba"`
```
center leaves sequence: "abaabaabaabaabaaba....."
```
For `chars = "abab"`,the output should be `a`
```
center leaves sequence: "aaaaaaaaaa....."
```
For `chars = "abcde"`,the output should be `aecea`
```
center leaves sequence: "aeceaaeceaaecea....."
```
For `chars = "aaaaaaaaaaaaaa"`,the output should be `a`
```
center leaves sequence: "aaaaaaaaaaaaaa....."
```
For `chars = "abaabaaab"`,the output should be `aba`
```
center leaves sequence: "abaabaabaaba....."
```

from collections import deque
from itertools import count, islice

def iter_center(s):
    q = deque(s)
    for i in count():
        yield q[i % len(q)]
        q.rotate(-3-i*4)

def find_repeat(g):
    xs = []
    for i in count(1):
        xs.extend(islice(g, 10))
        if all(len(set(xs[j::i])) == 1 for j in range(i)):
            return ''.join(xs[:i])

def center_of(chars):
    return chars and find_repeat(iter_center(chars))


Solve in Python:
# Task

Determine the client's membership level based on the invested `amount` of money and the given thresholds for membership levels.

There are four membership levels (from highest to lowest): `Platinum, Gold, Silver, Bronze`

The minimum investment is the threshold limit for `Bronze` membership. If the given amount is less than the `Bronze` treshold limit return `Not a member`.

A client belongs to a membership level when his invested amount is greater than or equal the level's threshold amount.

# Examples:
```
|--------+----------+------+--------+--------+--------------+------------------|
| Amount | Platinum | Gold | Silver | Bronze | Result       | Explanations     |
|--------+----------+------+--------+--------+--------------+------------------|
|   7000 |    10000 | 8000 |   6000 |   4000 | Silver       | Amount >= Silver |
|   3000 |    10000 | 8000 |   6000 |   5000 | Not a member | Amount < Bronze  |
|   8000 |    12000 | 8000 |   7000 |   5000 | Gold         | Amount >= Gold   |
|--------+----------+------+--------+--------+--------------+------------------|
```

# Restrictions

1. The first line of your code has to be `def membership(amount, platinum, gold, silver, bronze):`
2. Your code except for the firt line mustn't contain the words `platinum, gold, silver, bronze` or they reversed forms (e.g. `dlog`) or any string which contains these words or they reversed forms. (The check is **case-insensitive**.)
3. Must not contain: `+, %, {, }`.

# Disclaimer

This kata is about creativity not proper coding style. Your colleagues/boss won't like you if you make production code like this. :)

#### Don't forget to rate the kata after you finish it. :)

Happy coding!

suic

def membership(amount, platinum, gold, silver, bronze):
    if amount<eval(''.join(['b','r','o','n','z','e'])):
        return 'Not a member'
    elif amount<eval(''.join(['s','i','l','v','e','r'])):
        return ''.join(['B','r','o','n','z','e'])
    elif amount<eval(''.join(['g','o','l','d'])):
        return ''.join(['S','i','l','v','e','r'])
    elif amount<eval(''.join(['p','l','a','t','i','n','u','m'])):
        return ''.join(['G','o','l','d'])
    else:
        return ''.join(['P','l','a','t','i','n','u','m'])


Solve in Python:
# Task

Elections are in progress!

Given an array of numbers representing votes given to each of the candidates, and an integer which is equal to the number of voters who haven't cast their vote yet, find the number of candidates who still have a chance to win the election.

The winner of the election must secure strictly more votes than any other candidate. If two or more candidates receive the same (maximum) number of votes, assume there is no winner at all.

**Note**: big arrays will be tested.

# Examples

```
votes = [2, 3, 5, 2]
voters = 3

result = 2
```

* Candidate `#3` may win, because he's already leading.
* Candidate `#2` may win, because with 3 additional votes he may become the new leader.
* Candidates `#1` and `#4` have no chance, because in the best case scenario each of them can only tie with the candidate `#3`.

___

```
votes = [3, 1, 1, 3, 1]
voters = 2

result = 2
```

* Candidate `#1` and `#4` can become leaders if any of them gets the votes.
* If any other candidate gets the votes, they will get tied with candidates `#1` and `#4`.

___

```
votes = [1, 3, 3, 1, 1]
voters = 0

result = 0
```

* There're no additional votes to cast, and there's already a tie.

elections_winners=lambda v,k:v.sort()or sum(e+k>v[-1]for e in v)or v.count(v[-1])==1


Solve in Python:
# Task

Find the integer from `a` to `b` (included) with the greatest number of divisors. For example:

```
divNum(15, 30)   ==> 24
divNum(1, 2)     ==> 2
divNum(0, 0)     ==> 0
divNum(52, 156)  ==> 120
```

If there are several numbers that have the same (maximum) number of divisors, the smallest among them should be returned. Return the string `"Error"` if `a > b`.

import numpy as np
s = np.ones(100000)
for i in range(2, 100000):
    s[i::i] += 1

def div_num(a, b):
    return max(range(a, b+1), key=lambda i: (s[i], -i), default='Error')


Solve in Python:
# Task

Given a binary number, we are about to do some operations on the number. Two types of operations can be here:

* ['I', i, j] : Which means invert the bit from i to j (inclusive).

* ['Q', i] : Answer whether the i'th bit is 0 or 1.

The MSB (most significant bit) is the first bit (i.e. i = `1`). The binary number can contain leading zeroes.

## Example
```python
binary_simulation("0011001100", [['I', 1, 10], ['I', 2, 7], ['Q', 2], ['Q', 1], ['Q', 7], ['Q', 5]]) === [ '0', '1', '1', '0' ];
binary_simulation("1011110111", [['I', 1, 10], ['I', 2, 7], ['Q', 2], ['Q', 1], ['Q', 7], ['Q', 5]]) === [ '0', '0', '0', '1' ];
binary_simulation("1011110111", [['I', 1, 10], ['I', 2, 7]]) === [];
binary_simulation("0000000000", [['I', 1, 10], ['Q', 2]]) ===  ['1'];
```
## Note
* All inputs are valid.
* Please optimize your algorithm to avoid time out.


Solve in Python:
# Task

Given a square `matrix`, your task is to reverse the order of elements on both of its longest diagonals.

The longest diagonals of a square matrix are defined as follows:
* the first longest diagonal goes from the top left corner to the bottom right one;
* the second longest diagonal goes from the top right corner to the bottom left one.

# Example

For the matrix
```
1, 2, 3
4, 5, 6
7, 8, 9
```
the output should be:
```
9, 2, 7
4, 5, 6
3, 8, 1
```

# Input/Output

- `[input]` 2D integer array `matrix`

   Constraints: `1 ≤ matrix.length ≤ 10, matrix.length = matrix[i].length, 1 ≤ matrix[i][j] ≤ 1000`

- `[output]` 2D integer array

   Matrix with the order of elements on its longest diagonals reversed.

def reverse_on_diagonals(matrix):
    # Modifies the matrix in place. Only way to get O(n)
    diag1 = [matrix[i][i] for i in range(len(matrix))]
    diag2 = [matrix[i][~i] for i in range(len(matrix))]
    for i, n in enumerate(reversed(diag1)):
        matrix[i][i] = n
    for i, n in enumerate(reversed(diag2)):
        matrix[i][~i] = n
    return matrix


Solve in Python:
# Task

Given an array of integers, sum consecutive even numbers and consecutive odd numbers. Repeat the process while it can be done and return the length of the final array.

# Example

For `arr = [2, 1, 2, 2, 6, 5, 0, 2, 0, 5, 5, 7, 7, 4, 3, 3, 9]`

The result should be `6`.

```
[2, 1, 2, 2, 6, 5, 0, 2, 0, 5, 5, 7, 7, 4, 3, 3, 9]  -->
         2+2+6       0+2+0     5+5+7+7       3+3+9
[2, 1,   10,    5,    2,        24,     4,   15   ] -->
                               2+24+4
[2, 1,   10,    5,             30,           15   ]
The length of final array is 6
```

# Input/Output

- `[input]` integer array `arr`

  A non-empty array,

  `1 ≤ arr.length ≤ 1000`

  `0 ≤ arr[i] ≤ 1000`

- `[output]` an integer

  The length of the final array

from itertools import groupby

def sum_groups(arr):
    while True:
        n = len(arr)
        arr = [sum(grp) for key, grp in groupby(arr, key=lambda x: x % 2)]
        if len(arr) == n:
            return n


Solve in Python:
# Task

Given an array of roots of a polynomial equation, you should reconstruct this equation.

___

## Output details:

* If the power equals `1`, omit it: `x = 0` instead of `x^1 = 0`
* If the power equals `0`, omit the `x`: `x - 2 = 0` instead of `x - 2x^0 = 0`
* There should be no 2 signs in a row: `x - 1 = 0` instead of `x + -1 = 0`
* If the coefficient equals `0`, skip it: `x^2 - 1 = 0` instead of `x^2 + 0x - 1 = 0`
* Repeating roots should not be filtered out: `x^2 - 4x + 4 = 0` instead of `x - 2 = 0`
* The coefficient before `q^n` is always `1`: `x^n + ... = 0` instead of `Ax^n + ... = 0`

___

## Example:

```
polynomialize([0])        =>  "x = 0"
polynomialize([1])        =>  "x - 1 = 0"
polynomialize([1, -1])    =>  "x^2 - 1 = 0"
polynomialize([0, 2, 3])  =>  "x^3 - 5x^2 + 6x = 0"
```

___

## Tests:

```python
      Main suite:                  Edge cases:
 (Reference - 4000 ms)         (Reference - 30 ms)

N of roots | N of tests      N of roots | N of tests
-----------------------      -----------------------
    1-10   |   100              20-40   |    125
 700-750   |    25               2-20   |    125
```

def polynomialize(roots):
    def add_root(poly, root):
        # Multiply poly * (x - root)
        poly1 = poly + [0] # Increase order (multiply by x)
        poly2 = [0] + [-root * coef for coef in poly] # Multiply by -root
        poly = [coef1 + coef2 for coef1, coef2 in zip(poly1, poly2)] # Add
        return poly
    def poly2str(poly):
        spoly = ""
        for i, coef in enumerate(poly):
            if i == 0:
                signum = ""
            elif coef > 0:
                signum = " + "
            elif coef < 0:
                signum = " - "
            else:
                continue

            if abs(coef) == 1:
                scoef = ""
            else:
                scoef = str(abs(coef))

            exp = len(poly)-i-1
            if exp == 1:
                sexp = "x"
            elif exp == 0:
                if scoef == "":
                    sexp = "1"
                else:
                    sexp = ""
            else:
                sexp = "x^"+str(exp)
            spoly += signum + scoef + sexp
        spoly += " = 0"
        return spoly

    poly = [1, -roots[0]]
    for root in roots[1:]:
        poly = add_root(poly, root)

    return poly2str(poly)


Solve in Python:
# Task

Given the birthdates of two people, find the date when the younger one is exactly half the age of the other.

# Notes

* The dates are given in the format YYYY-MM-DD and are not sorted in any particular order
* Round **down** to the nearest day
* Return the result as a string, like the input dates

from datetime import date
def half_life(person1, person2):
    p1 = list(map(int,person1.split("-")))
    p1_date = date(p1[0],p1[1],p1[2])
    p2 = list(map(int,person2.split("-")))
    p2_date = date(p2[0],p2[1],p2[2])
    if p1[0]>p2[0]:
        diff = p1_date-p2_date
        b = p1_date+diff
        return str(b)
    else:
        diff = p2_date-p1_date
        a = p2_date+diff
        return str(a)


Solve in Python:
# Task

In the city, a bus named Fibonacci runs on the road every day.

There are `n` stations on the route. The Bus runs from station1 to stationn.

At the departure station(station1), `k` passengers get on the bus.

At the second station(station2), a certain number of passengers get on and the same number get off. There are still `k` passengers on the bus.

From station3 to stationn-1, the number of boarding and alighting passengers follows the following rule:

- At stationi, the number of people getting on is the sum of the number of people getting on at the two previous stations(stationi-1 and stationi-2)
- The number of people getting off is equal to the number of people getting on at the previous station(stationi-1).

At stationn, all the passengers get off the bus.

Now, The numbers we know are: `k` passengers get on the bus at station1, `n` stations in total, `m` passengers get off the bus at stationn.

We want to know: How many passengers on the bus when the bus runs out stationx.

# Input

- `k`: The number of passengers get on the bus at station1.
  - `1 <= k <= 100`

- `n`: The total number of stations(1-based).
  - `6 <= n <= 30`

- `m`: The number of passengers get off the bus at stationn.
  - `1 <= m <= 10^10`

- `x`: Stationx(1-based). The station we need to calculate.
  - `3 <= m <= n-1`

- All inputs are valid integers.

# Output

An integer. The number of passengers on the bus when the bus runs out stationx.


Solve in Python:
# Task

In the field, two beggars A and B found some gold at the same time. They all wanted the gold, and they decided to use simple rules to distribute gold:
```
They divided gold into n piles and be in line.
The amount of each pile and the order of piles all are randomly.

They took turns to take away a pile of gold from the
far left or the far right.

They always choose the bigger pile. That is to say,
if the left is 1, the right is 2, then choose to take 2.

If the both sides are equal, take the left pile.
```

Given an integer array `golds`, and assume that A always takes first. Please calculate the final amount of gold obtained by A and B. returns a two-element array `[amount of A, amount of B]`.

# Example

For `golds = [4,2,9,5,2,7]`, the output should be `[14,15]`.
```
The pile of most left is 4,
The pile of most right is 7,
A choose the largest one -- > take 7

The pile of most left is 4,
The pile of most right is 2,
B choose the largest one -- > take 4

The pile of most left is 2,
The pile of most left is 2,
A choose the most left one -- > take 2

The pile of most left is 9,
The pile of most right is 2,
B choose the largest one -- > take 9

The pile of most left is 5,
The pile of most left is 2,
A choose the largest one -- > take 5

Tehn, only 1 pile left,
B  -- > take 2

A: 7 + 2 + 5 = 14
B: 4 + 9 + 2 = 15
```

For `golds = [10,1000,2,1]`, the output should be `[12,1001]`.
```
A take 10
B take 1000
A take 2
B take 1

A: 10 + 2 = 12
B: 1000 + 1 = 1001
```

def distribution_of(golds):
    ind, beggars = [0, len(golds)-1], [0, 0]
    for n in range(len(golds)):
        i = golds[ind[0]] < golds[ind[1]]
        beggars[n%2] += golds[ind[i]]
        ind[i] += (-1)**i
    return beggars


Solve in Python:
# Task

John and Alice have an appointment today.

In the morning, John starts from (`0,0`) and goes to the place (`a,b`) where he is dating. Unfortunately, John had no sense of direction at all, so he moved 1 step in a random direction(up, down, left or right) each time. For example, if John at (x,y), next step he may move to `(x+1,y), (x-1,y),(x,y+1) or (x,y-1)`.

Obviously, when he arrived at the destination, it was already too late and Alice had already left. It's a sadly story :(

The second day, Alice asked John why he didn't go to the dating place. John said he took `s` steps to his date yesterday.

Alice wants to know whether John is lying. Please help Alice to judge.

Given two coordinates `a, b` and the step `s`, return `true` if John tells the truth, `false` otherwise.

# Input/Output

`[input]` integer `a`

The x-coordinates of the dating site.

`-10^7 <= a <= 10^7`

`[input]` integer `b`

The y-coordinates of the dating site.

`-10^7 <= b <= 10^7`

`[input]` integer `s`

A positive integer.  The steps John using.

`0 < s <= 10^9`

`[output]` a boolean value

return `true` if John tells the truth, `false` otherwise.

# Example

For `a = 3, b = 3, s = 6`, the output should be `true`.

A possible path is:

`(0,0) -> (0,1) -> (0,2) -> (0,3) -> (1,3) -> (2,3) -> (3,3)`

For `a = 3, b = 3, s = 8`, the output should be `true`.

A possible path is:

`(0,0) -> (0,1) -> (1,1) -> (1,2) -> (2,2) -> (2,1) -> (3,1) -> (3,2) -> (3,3)`

For `a = 4, b = 5, s = 10`, the output should be `false`.

John can't reach coordinates (a, b) using 10 steps, he's lying ;-)

def is_john_lying(a,b,s):
    return abs(a)+abs(b) - s <= 0 and (abs(a)+abs(b) - s) % 2 == 0


Solve in Python:
# Task

John has an important number, and he doesn't want others to see it.

He decided to encrypt the number, using the following steps:
```
His number is always a non strict increasing sequence
ie. "123"

He converted each digit into English words.
ie. "123"--> "ONETWOTHREE"

And then, rearrange the letters randomly.
ie. "ONETWOTHREE" --> "TTONWOHREEE"
```

John felt that his number were safe in doing so. In fact, such encryption can be easily decrypted :(

Given the encrypted string `s`, your task is to decrypt it, return the original number in string format.

Note, You can assume that the input string `s` is always valid; It contains only uppercase Letters; The decrypted numbers are arranged in ascending order; The leading zeros are allowed.

# Example

For `s = "ONE"`, the output should be `1`.

For `s = "EON"`, the output should be `1` too.

For `s = "ONETWO"`, the output should be `12`.

For `s = "OONETW"`, the output should be `12` too.

For `s = "ONETWOTHREE"`, the output should be `123`.

For `s = "TTONWOHREEE"`, the output should be `123` too.

import re;original_number=lambda s:''.join(n*str(i)for i,n in enumerate(eval(re.sub('([A-Z])',r's.count("\1")','[Z,O-W-U-Z,W,H-G,U,F-U,X,S-X,G,I-G-F+U-X]'))))


Solve in Python:
# Task

John is a programmer. He treasures his time very much. He lives on the `n` floor of a building. Every morning he will go downstairs as quickly as possible to begin his great work today.

There are two ways he goes downstairs: walking or taking the elevator.

When John uses the elevator, he will go through the following steps:
```
1. Waiting the elevator from m floor to n floor;
2. Waiting the elevator open the door and go in;
3. Waiting the elevator close the door;
4. Waiting the elevator down to 1 floor;
5. Waiting the elevator open the door and go out;
(the time of go in/go out the elevator will be ignored)
```

Given the following arguments:
```
n: An integer. The floor of John(1-based).
m: An integer. The floor of the elevator(1-based).
speeds: An array of integer. It contains four integer [a,b,c,d]
        a: The seconds required when the elevator rises or falls 1 floor
        b: The seconds required when the elevator open the door
        c: The seconds required when the elevator close the door
        d: The seconds required when John walks to n-1 floor
```

Please help John to calculate the shortest time to go downstairs.

# Example

For `n = 5, m = 6 and speeds = [1,2,3,10]`, the output should be `12`.

John go downstairs by using the elevator:

`1 + 2 + 3 + 4 + 2 = 12`

For `n = 1, m = 6 and speeds = [1,2,3,10]`, the output should be `0`.

John is already at 1 floor, so the output is `0`.

For `n = 5, m = 4 and speeds = [2,3,4,5]`, the output should be `20`.

John go downstairs by walking:

`5 x 4 = 20`

def shortest_time(n, m, speeds):
    a, b, c, d = speeds
    return min(d * (n - 1), (abs(m - n) + n - 1) * a + 2 * b + c)


Solve in Python:
# Task

John is playing a RPG game. The initial attack value of the player is `x`. The player will face a crowd of monsters. Each monster has different defense value.

If the monster's defense value is less than or equal to the player's attack value, the player can easily defeat the monster, and the player's attack value will increase. The amount increased is equal to the monster's defense value.

If the monster's defense value is greater than the player's attack value, the player can still defeat monsters, but the player's attack value can only be increased little, equal to the `greatest common divisor` of the monster's defense value and the player's current attack value.

The defense values for all monsters are provided by `monsterList/monster_list`. The player will fight with the monsters from left to right.

Please help John calculate the player's final attack value.

# Example

For `x = 50, monsterList=[50,105,200]`, the output should be `110`.

The attack value increased: `50 --> 100 --> 105 --> 110`

For `x = 20, monsterList=[30,20,15,40,100]`, the output should be `205`.

The attack value increased:

`20 --> 30 --> 50 --> 65 --> 105 --> 205`

from math import gcd

def final_attack_value(attack, monsters):
    for monster in monsters:
        attack += gcd(attack, monster) if attack < monster else monster
    return attack


Solve in Python:
# Task

John won the championship of a TV show. He can get some bonuses.

He needs to play a game to determine the amount of his bonus.

Here are `n` rows and `m` columns of cards were placed on the ground. A non-negative number is written on each card.

The rules of the game are:

- Player starts from the top-left coner, walk to the bottom-right coner.

- Players can only walk downward or right.

- The sum of the numbers collected by the players will be used as the bonus.

John has two chances to play this game on a game map. Specifically, when John finishes the game, the card on his path will be removed, and then he can walk again.

Your task is to help John calculate the maximum amount of bonuses he can get.

# Input

- `gameMap/gamemap`: A `n` x `m` integer array. Each element represents the number on the card.
  - `4 <= n,m <= 40(Pyhon)/100(JS)`

- All inputs are valid.

# Output

An integer. the maximum amount of bonuses John can get.

# Eaxmple

For
```
gameMap=
[
[1, 3, 9],
[2, 8, 5],
[5, 7, 4]
]
```
The output should be `39`.

One of the possible solution is:
```
1st game:
[
[>, >, v],
[2, 8, v],
[5, 7, v]
]
1+3+9+5+4=22

2nd game:
[
[v, 0, 0],
[>, v, 0],
[5, >, >]
]
0+2+8+7+0=17

Final bonus = 22 + 17 = 39
```


Solve in Python:
# Task

John won the championship of a TV show. He can get some bonuses.

He needs to play a game to determine the amount of his bonus.

Here are some cards in a row. A number is written on each card.

In each turn, John can take a card, but only from the beginning or the end of the row. Then multiply the number on the card by an coefficient 2^(i)(i means the ith turn). The product is John's bonus of current turn.

After all the cards are taken away, the game is over. John's final bonus is the sum of all rounds of bonuses.

Obviously, the order in which John takes the cards will affect the amount of John's final bonus.

Your task is to help John calculate the maximum amount of bonuses he can get.

# Input

- `cards`: An integer array. Each element represents the number on the card.
  - `1 <= cards.length <= 30`
  - `1 <= cards[i] <= 100`

- All inputs are valid.

# Output

An integer. the maximum amount of bonuses John can get.

# Eaxmple

For `cards=[1,2,5]`, the output should be `50`.

```
All possible orders are:
1->2->5   bonus:1x2+2*4+5*8=50
1->5->2   bonus:1x2+5*4+2*8=38
5->1->2   bonus:5*2+1*4+2*8=30
5->2->1   bonus:5*2+2*4+1*8=26
The maximum amount of bonus is 50.
```

VISITED = dict()

def calc(cards, idx = 0):
    if idx == 0:
        VISITED.clear()

    if len(cards) == 0:
        return 0

    tpl = tuple(cards)
    m_value = VISITED.get(tpl, None)
    if m_value:
        return m_value

    res = max(cards[0]*(2<<idx) + calc(cards[1:], idx+1), cards[-1]*(2<<idx) + calc(cards[:-1], idx+1))
    VISITED[tpl] = res
    return res


def fold_cube(number_list):
    print(number_list)
    connections = 0
    number_list.sort()

    for i in range(len(number_list)):
        if ((number_list[i] - 1) in number_list) and (number_list[i] not in [6, 11, 16, 21]): connections += 1
    for j in range(len(number_list)):
        if ((number_list[j] - 5) in number_list): connections += 1

    # in cube 6 faces are connected by 5 edges
    if connections != 5: return False

    horizontal = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]]
    vertical = [[1, 6, 11, 16, 21], [2, 7, 12, 17, 22], [3, 8, 13, 18, 23], [4, 9, 14, 19, 24], [5, 10, 15, 20, 25]]

    lenghts_horizontal = []
    height = 0

    for h in horizontal:
        lh = 1
        any_in_row = False
        for i in range(len(number_list)):
            if number_list[i] in h:
                any_in_row = True
            if ((number_list[i] - 1) in number_list) and (number_list[i] in h) and (
                    number_list[i] not in [6, 11, 16, 21]):
                lh += 1
        if lh > 1:
            lenghts_horizontal.append(lh)
        elif any_in_row:
            lenghts_horizontal.append(1)
        if any_in_row:
            height += 1

    if lenghts_horizontal[0] == 4 or lenghts_horizontal[-1] == 4:
        return False

    is_3_horizontal_fist = False
    if lenghts_horizontal[0] == 3 or lenghts_horizontal[-1] == 3:
        is_3_horizontal_fist = True

    lenghts_horizontal.sort(reverse=True)

    if lenghts_horizontal[0] > 4: return False

    width = 0
    lenghts_vertical = []

    for v in vertical:
        lv = 1
        any_in_row = False
        for i in range(len(number_list)):
            if number_list[i] in v:
                any_in_row = True
            if ((number_list[i] - 5) in number_list) and (number_list[i] in v):
                lv += 1
        if lv > 1:
            lenghts_vertical.append(lv)
        elif any_in_row:
            lenghts_vertical.append(1)
        if any_in_row:
            width +=...


Solve in Python:
# Task

The game starts with `n` people standing in a circle. The presenter counts `m` people starting with the first one, and gives `1` coin to each of them. The rest of the players receive `2` coins each. After that, the last person who received `1` coin leaves the circle, giving everything he had to the next participant (who will also be considered "the first in the circle" in the next round). This process continues until only 1 person remains.

Determine the `number` of this person and how many `coins` he has at the end of the game.

The result should be a pair of values in the format: `[person, coins]`.

## Example:

```
n = 8, m = 3

People
1 2 3      1 2 ∙      1 2 ∙      ∙ 2 ∙       ∙  2 ∙       ∙ ∙  ∙       ∙ ∙  ∙
8   4  =>  8   4  =>  8   4  =>  8   4  =>   8    4  =>   8    4  =>   ∙    4  =>  7
7 6 5      7 6 5      7 ∙ 5      7 ∙ 5       7  ∙ ∙       7 ∙  ∙       7 ∙  ∙

Coins
0 0 0      1 1 ∙      3 3 ∙      ∙ 9 ∙       ∙ 10 ∙       ∙ ∙  ∙       ∙ ∙  ∙
0   0  =>  2   3  =>  4   4  =>  5   6  =>   7    7  =>   8   20  =>   ∙   30  =>  51
0 0 0      2 2 2      7 ∙ 3      8 ∙ 5      16 ∙  ∙      17 ∙  ∙      18 ∙  ∙
```

## Notes:

* The presenter can do several full circles during one counting.
* In this case, the same person will receive `1` coin multiple times, i.e. no matter how many people are left in the circle, at least `m` coins will always be distributed among the participants during the round.
* If a person had already received `1` coin (possibly multiple times), he won't receive any additional `2` coins **at once(!)** during that round.
* People are counted starting with `1`.
* `m` can be **bigger** than `n` at start

def find_last(n, m):
    num, i, L = 0, 0, [0]*n
    ni = lambda i: (i+1)%len(L)
    pi = lambda i: (i-1)%len(L)
    for v in range(2, n+1):
        num = (num + m) % v
        seen = set(range(len(L)))
        for _ in range(m):
            L[i] += 1
            seen.discard(i)
            i = ni(i)
        for x in seen: L[x] += 2
        j = pi(i)
        L[i] += L[j]
        del L[j]
        i = pi(i)
    return num+1, L[0]


Solve in Python:
# Task

There are `n` bears in the orchard and they picked a lot of apples.

They distribute apples like this:

```
The first bear divided the apple into n piles, each with the same number. leaving an apple at last, and the apple was thrown away. Then he took 1 pile and left the n-1 pile.

The second bear divided the apple into n piles, each with the same number. leaving an apple at last, and the apple was thrown away. Then he took 1 pile and left the n-1 pile.

and so on..
```

Hmm.. your task is coming, please calculate the minimum possible number of these apples (before they start distributing)

# Input/Output

`[input]` integer `n`

The number of bears.

`2 <= n <= 9` (JS, Crystal and C)
`2 <= n <= 50` (Ruby and Python)

`[output]` an integer

The minimum possible number of apples.

# Example

For `n = 5`, the output should be `3121`.

```
5 bears distribute apples:

1st bear divided the apples into 5 piles, each pile has 624 apples, and 1 apple was thrown away.
3121 - 1 = 624 x 5
1st bear took 1 pile of apples, 2496 apples left.
3121 - 1 - 624 = 2496

2nd bear divided the apples into 5 piles, each pile has 499 apples, and 1 apple was thrown away.
2496 - 1 = 499 x 5
2nd bear took 1 pile of apples, 1996 apples left.
2496 - 1 - 499 = 1996

3rd bear divided the apples into 5 piles, each pile has 399 apples, and 1 apple was thrown away.
1996 - 1 = 399 x 5
3rd bear took 1 pile of apples, 1596 apples left.
1996 - 1 - 399 = 1596

4th bear divided the apples into 5 piles, each pile has 319 apples, and 1 apple was thrown away.
1596 - 1 = 319 x 5
4th bear took 1 pile of apples, 1276 apples left.
1596 - 1 - 319 = 1276

5th bear divided the apples into 5 piles, each pile has 255 apples, and 1 apple was thrown away.
1276 - 1 = 255 x 5
5th bear took 1 pile of apples, 1020 apples left.
1276 - 1 - 255 = 1020
```

how_many_apples=lambda n:n>2and n**n-n+1or 7


Solve in Python:
# Task

Write a function `deNico`/`de_nico()` that accepts two parameters:
- `key`/`$key` - string consists of unique letters and digits
- `message`/`$message` - string with encoded message

and decodes the `message` using the `key`.

First create a numeric key basing on the provided `key` by assigning each letter position in which it is located after setting the letters from `key` in an alphabetical order.

For example, for the key `crazy` we will get `23154` because of `acryz` (sorted letters from the key).
Let's decode  `cseerntiofarmit on  ` using our `crazy` key.

```
1 2 3 4 5
---------
c s e e r
n t i o f
a r m i t
  o n
```

After using the key:
```
2 3 1 5 4
---------
s e c r e
t i n f o
r m a t i
o n
```

# Notes

- The `message` is never shorter than the `key`.
- Don't forget to remove trailing whitespace after decoding the message

# Examples

Check the test cases for more examples.

# Related Kata

[Basic Nico - encode](https://www.codewars.com/kata/5968bb83c307f0bb86000015)

import itertools
def de_nico(key,msg):
    pack =[list(range(len(key)))]+list(list(msg[i:i+len(key)]) for i in range(0,len(msg),len(key)))
    sor = [sorted(key).index(i) for i in key]
    sorting = sorted(itertools.zip_longest(*pack,fillvalue=""), key=lambda col: sor.index(col[0]))
    return "".join(["".join(j) for i,j in enumerate(itertools.zip_longest(*sorting,fillvalue=" ")) if i>0]).strip(" ")


Solve in Python:
# Task

Write a function named `sumEvenNumbers`, taking a sequence of numbers as single parameter. Your function must return the sum of **the even values** of this sequence.

Only numbers without decimals like `4` or `4.0` can be even.

## Input
* sequence of numbers: those numbers could be integers and/or floats.

For example, considering this input value : `[4,3,1,2,5,10,6,7,9,8]`, then your function should return `30` (because `4 + 2 + 10 + 6 + 8 = 30`).

def sum_even_numbers(seq):
    to_sum = [num for num in seq if num % 2 == 0]
    return sum(to_sum)


Solve in Python:
# Task

Write a function that accepts `msg` string and returns local tops of string from the highest to the lowest.
The string's tops are from displaying the string in the below way:

```

                                         7891012
                             TUWvXY      6     3
                   ABCDE     S    Z      5
           lmno    z   F     R    1      4
     abc   k  p    v   G     Q    2      3
.34..9 d...j  q....x   H.....P    3......2
125678 efghi  rstuwy   IJKLMNO    45678901

```
The next top is always 1 character higher than the previous one.
For the above example, the solution for the `123456789abcdefghijklmnopqrstuwyxvzABCDEFGHIJKLMNOPQRSTUWvXYZ123456789012345678910123` input string is `7891012TUWvXYABCDElmnoabc34`.

- When the `msg` string is empty, return an empty string.
- The input strings may be very long. Make sure your solution has good performance.
- The (.)dots on the sample dispaly of string are only there to help you to understand the pattern

Check the test cases for more samples.

# Series

- [String tops](https://www.codewars.com/kata/59b7571bbf10a48c75000070)
- [Square string tops](https://www.codewars.com/kata/5aa3e2b0373c2e4b420009af)

def tops(msg):
    if msg:
        step = int(((2 * len(msg) - 1)**0.5 + 3) / 2)
        result = [msg[n*(2*n+1)-1:2*n*(n+1)] for n in range(1, step)]
        return "".join(reversed(result))
    return ""


Solve in Python:
# Task

Write a function that accepts `msg` string and returns local tops of string from the highest to the lowest.
The string's tops are from displaying the string in the below way:

```
                                                      3
                              p                     2   4
            g               o   q                 1
  b       f   h           n       r             z
a   c   e       i       m          s          y
      d           j   l             t       x
                    k                 u   w
                                        v

```
The next top is always 1 character higher than the previous one.
For the above example, the solution for the `abcdefghijklmnopqrstuvwxyz1234` input string is `3pgb`.

- When the `msg` string is empty, return an empty string.
- The input strings may be very long. Make sure your solution has good performance.

Check the test cases for more samples.

# **Note** for C++

Do not post an issue in my solution without checking if your returned string doesn't have some invisible characters. You read most probably outside of `msg` string.

def tops(msg):
    if len(msg) < 2:
        return ''
    g = 2
    k = ''
    ni = 0
    k += msg[1]
    for i in msg[1:]:
        if ni == g * 2 + 1:
            k += i
            g += 2
            ni = 0
        ni += 1
    return k[::-1]


Solve in Python:
# Task

You are a lonely frog.

You live on an integer array.

The meaning of your life is to jump and jump..

Now, here comes your new task.

You are given an integer array `arr` and a positive integer `n`.

You will jump following the rules below:

- Your initial position at `arr[0]`. arr[0] will always be `0`.

- You will jump according to the number of current position(arr[i])
  - That is, if the number is a positive integer, let say 3, you will jump forward 3 steps; If the number is a negative integer, let say -3, you will jump backward 3 steps; If the number is 0, you will stay here for a little rest.

- The number of current position(arr[i]) will increase decrease by 1 after each turn (jump or stay).
  - That is, if the number of current position(arr[i]) is greater than or equal to `n`, the number will decrease 1; if the number at current position(arr[i]) is less than `n`, the number will increase 1.

You will stop jumping when you reach the exit (your position greater than or equal to arr.length). Please tell me, at the moment, how many elements in `arr` are equal to `n`?

# Note

- `3 <= arr.length <= 1000`, `1 <= n <= 9`

- Frog will never jump backward out of `arr`.

# Example

For `arr = [0,3,0,1,-3], n = 3`, the output should be `2`.
```
 Let us jump softly:

 [0,3,0,1,-3]
  ^--You are here, current number is 0, you stay here.
     currect number 0 < n, so 0 -> 1
 [1,3,0,1,-3]
  ^--You are here, current number is 1, you will jump forward
     to position 1. current number 1 < n, so 1 -> 2
 [2,3,0,1,-3]
    ^--You are here, current number is 3, you will jump forward
       to position 4. current number 3 >= n, so 3 -> 2
 [2,2,0,1,-3]
           ^--You are here, current number is -3, you will jump backward
              to position 1. current number -3 < n, so -3 -> -2
 [2,2,0,1,-2]
    ^--You are here, current number is 2, you will jump forward
       to position 3. current number 2 < n, so 2 -> 3
 [2,3,0,1,-2]
        ^--You are here, current number is 1, you will jump forward
          ...

def jumping(arr, n):
    ind = 0
    add = 0
    while ind < len(arr):
        if arr[ind] >= n:
            add = -1
        else:
            add = 1
        arr[ind] += add
        ind += arr[ind] - add
    return arr.count(n)


Solve in Python:
# Task

You are given a `chessBoard`, a 2d integer array that contains only `0` or `1`. `0` represents a chess piece and `1` represents a empty grid. It's always square shape.

Your task is to count the number of squares made of empty grids.

The smallest size of the square is `2 x 2`. The biggest size of the square is `n x n`, where `n` is the size of chess board.

A square can overlap the part of other squares. For example:

If

```
chessBoard=[
  [1,1,1],
  [1,1,1],
  [1,1,1]
]
```

...there are four 2 x 2 squares in the chess board:

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

And one 3 x 3 square:
```
[1,1,1]
[1,1,1]
[1,1,1]
```

Your output should be an object/dict. Each item in it should be: `size:number`, where size is the square's size, and number is the number of squares.

For example, if there are four `2 x 2` squares and one `3 x 3` square in the chess board, the output should be: `{2:4,3:1}` (or any equivalent hash structure in your language). The order of items is not important, `{3:1,2:4}` is also a valid output.

If there is no square in the chess board, just return `{}`.

# Note

```if:javascript
- `2 <= chessBoard.length <= 400`
```
```if:python
- `2 <= chessBoard.length <= 120`
```
```if:ruby
- `2 <= chessBoard.length <= 130`
```
```if:java
- `2 <= chessBoard.length <= 250`
```
```if:haskell
- `2 <= chessBoard.length <= 120`
```
```if:csharp
- `2 <= chessBoard.Length <= 220`
```

- `5` fixed testcases

- `100` random testcases, testing for correctness of solution

- `100` random testcases, testing for performance of code

- All inputs are valid.

- Pay attention to code performance.

- If my reference solution gives the wrong result in the random tests, please let me know(post an issue).

# Example

For
```
chessBoard = [
  [1,1],
  [1,1]
]
```

the output should be `{2:1}`.

For
```
chessBoard = [
  [0,1],
  [1,1]
]
```

the output should be `{}`.

For
```
chessBoard = [
  [1,1,1],
  [1,1,1],
  [1,1,1]
]
```

the...

import time
def count(board):
    N = len(board)
    dp = board

    size_cnt = {}
    for row in range(1, N):
        for col in range(1, N):
            if board[row][col] == 1:
                size = 1 + min(dp[row-1][col-1], min(dp[row-1][col], dp[row][col-1]))
                dp[row][col] = size
                if size > 1:
                    size_cnt[size] = size_cnt.get(size, 0) + 1

    res = {}
    for k in size_cnt:
        for s in range(2, k + 1):
            res[s] = res.get(s, 0) + size_cnt[k]
    return res


Solve in Python:
# Task

You are given a function that should insert an asterisk (`*`) between every pair of **even digits** in the given input, and return it as a string. If the input is a sequence, concat the elements first as a string.

## Input

The input can be an integer, a string of digits or a sequence containing integers only.

## Output

Return a string.

## Examples
```
5312708     -->  "531270*8"
"0000"      -->  "0*0*0*0"
[1, 4, 64]  -->  "14*6*4"
```

Have fun!

def asterisc_it(n):
    n = x(n)
    h = n[1:]
    return n[0] + ''.join([[e,'*'+e][all((not int(e)%2,not int(n[i-1])%2))] for i,e in enumerate(h,1)])

x = lambda c: str(c) if not type(c) is list else ''.join(map(str,c))


Solve in Python:
# Task

You are given a positive integer `n`. We intend to make some ascending sequences according to the following rules:

 1. Make a sequence of length 1: [ n ]

 2. Or, insert a number to the left side of the sequence. But this number can not exceed half of the first number of the sequence.

 3. Follow rule 2, continue insert number to the left side of the sequence.

Your task is to count the number of all possible sequences, and return it.

If you do not understand the task, please read the rewritten version below:

You are given a positive integer `n`. Your task is to count the number of such sequences:

- It should be an ascending sequence;

- It should end with number `n`.

- Each number in the sequence should smaller or equals to the half of its right, except for the last number `n`.

- We define that a sequence containing only a number `n` is a valid ascending sequence.

# Examples

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

All sequences we made are:

```
[6]

insert a number to the left:

[1,6]
[2,6]
[3,6]

continue insert number:

[1,2,6]
[1,3,6]
```
There are 6 sequences in total.

For `n = 10`, the output should be `14`.

All sequences we made are:

```
[10]

insert a number to the left:

[1,10]
[2,10]
[3,10]
[4,10]
[5,10]

continue insert number:

[1,2,10]
[1,3,10]
[1,4,10]
[2,4,10]
[1,5,10]
[2,5,10]

continue insert number:

[1,2,4,10]
[1,2,5,10]

```
There are 14 sequences in total.

# Note

- `1 <= n <= 1000`

- `3` fixed testcases

- `100` random testcases, testing for correctness of solution

- All inputs are valid.

- If my reference solution gives the wrong result in the random tests, please let me know(post an issue).

from functools import lru_cache

@lru_cache(maxsize=None)
def make_sequences(n):
    if n<2: return n
    n&=~1
    return make_sequences(n>>1)+make_sequences(n-1)


Solve in Python:
# Task

You are given an array `a` of positive integers a. You may choose some integer `X` and update `a` several times, where to update means to perform the following operations:
```
pick a contiguous subarray of length not greater than the given k;
replace all elements in the picked subarray with the chosen X.
```
What is the minimum number of updates required to make all the elements of the array the same?

# Example

For `a = [1, 2, 2, 1, 2, 1, 2, 2, 2, 1, 1, 1] and k = 2`, the output should be `4`.

Here's how a will look like after each update:
```
[1, 2, 2, 1, 2, 1, 2, 2, 2, 1, 1, 1] ->
[1, 1, 1, 1, 2, 1, 2, 2, 2, 1, 1, 1] ->
[1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1] ->
[1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1] ->
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
```

# Input/Output

 - `[input]` integer array `a`

  An array of positive integers.

  Constraints:

  `10 ≤ a.length ≤ 50,`

  `1 ≤ a[i] ≤ 10.`

 - `[input]` integer `k`

  A positive integer, the maximum length of a subarray.

  Constraints: `2 ≤ k ≤ 9.`

 - `[output]` an integer

  The minimum number of updates.

def array_equalization(a, k):
    n, r = len(a), len(a)
    for x in set(a):
        i, t = 0, 0
        while i < n:
            if a[i] != x:
                t += 1
                i += k
            else:
                i += 1
        r = min(r, t)
    return r


Solve in Python:
# Task

You got a `scratch lottery`, you want to know how much money you win.

There are `6` sets of characters on the lottery. Each set of characters represents a chance to win. The text has a coating on it. When you buy the lottery ticket and then blow it off, you can see the text information below the coating.

Each set of characters contains three animal names and a number, like this: `"tiger tiger tiger 100"`. If the three animal names are the same, Congratulations, you won the prize. You will win the same bonus as the last number.

Given the `lottery`, returns the total amount of the bonus.

# Input/Output

`[input]` string array `lottery`

A string array that contains six sets of characters.

`[output]` an integer

the total amount of the bonus.

# Example

For
```
lottery = [
"tiger tiger tiger 100",
"rabbit dragon snake 100",
"rat ox pig 1000",
"dog cock sheep 10",
"horse monkey rat 5",
"dog dog dog 1000"
]```

the output should be `1100`.

`"tiger tiger tiger 100"` win $100, and `"dog dog dog 1000"` win $1000.

`100 + 1000 = 1100`

def scratch(lottery):
    return sum(int(s.split()[-1]) for s in lottery if len(set(s.split()[:-1])) == 1)


Solve in Python:
# Task

Your task is to sort the characters in a string according to the following rules:
```
- Rule1: English alphabets are arranged from A to Z, case insensitive.
  ie. "Type" --> "epTy"
- Rule2: If the uppercase and lowercase of an English alphabet exist
  at the same time, they are arranged in the order of oringal input.
  ie. "BabA" --> "aABb"
- Rule3: non English alphabet remain in their original position.
  ie. "By?e" --> "Be?y"
```

# Input/Output

`[input]` string `s`

A non empty string contains any characters(English alphabets or non English alphabets).

`[output]` a string

A sorted string according to the rules above.

# Example

For `s = "cba"`, the output should be `"abc"`.

For `s = "Cba"`, the output should be `"abC"`.

For `s = "cCBbAa"`, the output should be `"AaBbcC"`.

For `s = "c b a"`, the output should be `"a b c"`.

For `s = "-c--b--a-"`, the output should be `"-a--b--c-"`.

For `s = "Codewars"`, the output should be `"aCdeorsw"`.

from string import ascii_letters

sortable = frozenset(ascii_letters)

def sort_string(s):
    sorted_chars = iter(sorted((c for c in s if c in sortable), key=str.lower))
    return ''.join(next(sorted_chars) if c in sortable else c for c in s)


Solve in Python:
# Task

Your task is to write a function for calculating the score of a 10 pin bowling game. The input for the function is a list of pins knocked down per roll for one player. Output is the player's total score.

# Rules

## General rules
Rules of bowling in a nutshell:

* A game consists of 10 frames. In each frame the player rolls 1 or 2 balls, except for the 10th frame, where the player rolls 2 or 3 balls.

* The total score is the sum of your scores for the 10 frames

* If you knock down fewer than 10 pins with 2 balls, your frame score is the number of pins knocked down

* If you knock down all 10 pins with 2 balls (spare), you score the amount of pins knocked down plus a bonus - amount of pins knocked down with the next ball

* If you knock down all 10 pins with 1 ball (strike), you score the amount of pins knocked down plus a bonus - amount of pins knocked down with the next 2 balls

## Rules for 10th frame
As the 10th frame is the last one, in case of spare or strike there will be no next balls for the bonus. To account for that:

* if the last frame is a spare, player rolls 1 bonus ball.
* if the last frame is a strike, player rolls 2 bonus balls.

These bonus balls on 10th frame are only counted as a bonus to the respective spare or strike.

# More information
http://en.wikipedia.org/wiki/Ten-pin_bowling#Scoring

# Input
You may assume that the input is always valid. This means:

* input list length is correct
* number of pins knocked out per roll is valid

def bowling_score(rolls):
  tot,i = 0,0
  for frm in range(10):
      fscr,i = rolls[i],i+1
      if fscr == 10:
          tot += fscr + rolls[i] + rolls[i+1]
          continue
      fscr += rolls[i]
      i += 1
      if fscr >= 10:
          tot += rolls[i]
      tot += fscr
  return tot


Solve in Python:
# Task
  You are given `N` ropes, where the length of each rope is a positive integer. At each step, you have to reduce all the ropes by the length of the smallest rope.

 The step will be repeated until no ropes are left. Given the length of N ropes, print the number of ropes that are left before each step.

# Example

 For `a = [3, 3, 2, 9, 7]`, the result should be `[5, 4, 2, 1]`
 ```
You have 5 ropes:
                   3 3 2 9 7   ( 5 left)
step 1:          1 1 0 7 5   ( 4 left)
step 2:          0 0 0 6 4   ( 2 left)
step 3:          0 0 0 0 2   ( 1 left)
step 4:          0 0 0 0 0
Hence the result is [5, 4, 2, 1]```

# Input/Output

 - `[input]` integer array `a`

  length of each rope.

  `3 <= a.length <= 2000`

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

 - `[output]` an integer array

  number of ropes before each step.

def cut_the_ropes(arr):
    ans = []
    while arr:
        ans.append(len(arr))
        minRope = min(arr)
        arr = [elt - minRope for elt in arr if elt > minRope]
    return ans


Solve in Python:
# Task
 "AL-AHLY" and "Zamalek" are the best teams in Egypt, but "AL-AHLY" always wins the matches between them. "Zamalek" managers want to know what is the best match they've played so far.

 The best match is the match they lost with the minimum goal difference. If there is more than one match with the same difference, choose the one "Zamalek" scored more goals in.

 Given the information about all matches they played, return the `index` of the best match (`0-based`). If more than one valid result, return the smallest index.

# Example

 For `ALAHLYGoals = [6,4] and zamalekGoals = [1,2]`, the output should be 1.

 Because `4 - 2` is less than `6 - 1`

 For `ALAHLYGoals = [1,2,3,4,5] and zamalekGoals = [0,1,2,3,4]`, the output should be 4.

 The goal difference of all matches are 1, but at 4th match "Zamalek" scored more goals in. So the result is `4`.

# Input/Output

 -  `[input]` integer array `ALAHLYGoals`

  The number of goals "AL-AHLY" scored in each match.

 - `[input]` integer array `zamalekGoals`

  The number of goals "Zamalek" scored in each match. It is guaranteed that zamalekGoals[i] < ALAHLYGoals[i] for each element.

 - `[output]` an integer

  Index of the best match.

def best_match(goals1, goals2):
    l = [(i - j, -j) for i, j in zip(goals1, goals2)]
    return l.index(min(l))


Solve in Python:
# Task
 A boy is walking a long way from school to his home. To make the walk more fun he decides to add up all the numbers of the houses that he passes by during his walk. Unfortunately, not all of the houses have numbers written on them, and on top of that the boy is regularly taking turns to change streets, so the numbers don't appear to him in any particular order.

 At some point during the walk the boy encounters a house with number `0` written on it, which surprises him so much that he stops adding numbers to his total right after seeing that house.

 For the given sequence of houses determine the sum that the boy will get. It is guaranteed that there will always be at least one 0 house on the path.

# Example

 For `inputArray = [5, 1, 2, 3, 0, 1, 5, 0, 2]`, the output should be `11`.

 The answer was obtained as `5 + 1 + 2 + 3 = 11`.

# Input/Output

 - `[input]` integer array `inputArray`

    Constraints: `5 ≤ inputArray.length ≤ 50, 0 ≤ inputArray[i] ≤ 10.`

 - `[output]` an integer

def house_numbers_sum(inp):
    lst = []
    for i in inp:
        lst.append(i)
        if i == 0:
            break
    return sum(lst)


Solve in Python:
# Task
 A ciphertext alphabet is obtained from the plaintext alphabet by means of rearranging some characters. For example "bacdef...xyz" will be a simple ciphertext alphabet where a and b are rearranged.

 A substitution cipher is a method of encoding where each letter of the plaintext alphabet is replaced with the corresponding (i.e. having the same index) letter of some ciphertext alphabet.

 Given two strings, check whether it is possible to obtain them from each other using some (possibly, different) substitution ciphers.

# Example

 For `string1 = "aacb" and string2 = "aabc"`, the output should be `true`

 Any ciphertext alphabet that starts with acb... would make this transformation possible.

 For `string1 = "aa" and string2 = "bc"`, the output should be `false`

# Input/Output

 - `[input]` string `string1`

    A string consisting of lowercase characters.

    Constraints: `1 ≤ string1.length ≤ 10`.

 - `[input]` string `string2`

    A string consisting of lowercase characters of the same length as string1.

    Constraints: `string2.length = string1.length`.

 - `[output]` a boolean value

def is_substitution_cipher(s1, s2):
    return len(set(s1)) == len(set(s2)) == len( set((a,b) for a,b in zip(s1, s2)) )


Solve in Python:
# Task
 A common way for prisoners to communicate secret messages with each other is to encrypt them. One such encryption algorithm goes as follows.

 You take the message and place it inside an `nx6` matrix (adjust the number of rows depending on the message length) going from top left to bottom right (one row at a time) while replacing spaces with dots (.) and adding dots at the end of the last row (if necessary) to complete the matrix.

 Once the message is in the matrix you read again from top left to bottom right but this time going one column at a time and treating each column as one word.

# Example

 The following message `"Attack at noon or we are done for"` is placed in a `6 * 6` matrix :
```
Attack
.at.no
on.or.
we.are
.done.
for...```
Reading it one column at a time we get:

 `A.ow.f tanedo tt..or a.oan. cnrre. ko.e..`

# Input/Output

 - `[input]` string `msg`

  a regular english sentance representing the original message

 - `[output]` a string

  encrypted message

def six_column_encryption(msg):
    msg = msg.replace(" ", ".") + "." * (6 - len(msg) % 6 if len(msg) % 6 != 0 else 0)
    return " ".join([msg[i::6] for i in range(6)])


Solve in Python:
# Task
 A lock has `n` buttons in it, numbered from `1 to n`. To open the lock, you have to press all buttons in some order, i.e. a key to the lock is a permutation of the first `n` integers. If you push the right button in the right order, it will be pressed into the lock. Otherwise all pressed buttons will pop out. When all buttons are pressed into the lock, it opens.

 Your task is to calculate the number of times you've got to push buttons in order to open the lock in the `worst-case scenario`.

# Example

 For `n = 3`, the result should be `7`.
 ```
 Let's assume the right order is 3-2-1.
 In the worst-case scenario, we press the buttons:
 Press 1, wrong, button 1 pop out
 Press 2, wrong, button 2 pop out
 Press 3, right, button 3 pressed in
 Press 1, wrong, button 1,3 pop out
 Press 3, right, button 3 pressed in
 Press 2, right, button 2 pressed in
 Press 1, right, button 1 pressed in
 We pressed button total 7 times.```

 For `n = 4`, the result should be `14`.
 ```
 Let's assume the right order is 4-3-2-1.
 In the worst-case scenario, we press the buttons:
 Press 1, wrong, button 1 pop out
 Press 2, wrong, button 2 pop out
 Press 3, wrong, button 3 pop out
 Press 4, right, button 4 pressed in
 Press 1, wrong, button 1,4 pop out
 Press 4, right, button 4 pressed in
 Press 2, wrong, button 2,4 pop out
 Press 4, right, button 4 pressed in
 Press 3, right, button 3 pressed in
 Press 1, wrong, button 1,3,4 pop out
 Press 4, right, button 4 pressed in
 Press 3, right, button 3 pressed in
 Press 2, right, button 2 pressed in
 Press 1, right, button 1 pressed in
 We pressed button total 14 times.```

# Input/Output

 - `[input]` integer `n`

  The number of buttons in the lock.

  `0 < n ≤ 2000`

 - `[output]` an integer

 The number of times you've got to push buttons in the `worst-case scenario`.

def press_button(n):
    return n*(n*n+5)/6


Solve in Python:
# Task
 A media access control address (MAC address) is a unique identifier assigned to network interfaces for communications on the physical network segment.

 The standard (IEEE 802) format for printing MAC-48 addresses in human-friendly form is six groups of two hexadecimal digits (0 to 9 or A to F), separated by hyphens (e.g. 01-23-45-67-89-AB).

# Example

 For `inputString = "00-1B-63-84-45-E6"`, the output should be `true`;

 For `inputString = "Z1-1B-63-84-45-E6"`, the output should be `false`;

 For `inputString = "not a MAC-48 address"`, the output should be `false`.

# Input/Output

 - `[input]` string `inputString`

 - `[output]` a boolean value

    `true` if inputString corresponds to MAC-48 address naming rules, `false` otherwise.

is_mac_48_address = lambda address: bool( __import__("re").match('-'.join(['[0-9A-F]{2}']*6) + '$', address) )


Solve in Python:
# Task
 A noob programmer was given two simple tasks: sum and sort the elements of the given array `arr` = [a1, a2, ..., an].

 He started with summing and did it easily, but decided to store the sum he found in some random position of the original array which was a bad idea. Now he needs to cope with the second task, sorting the original array arr, and it's giving him trouble since he modified it.

 Given the array `shuffled`, consisting of elements a1, a2, ..., an, and their sumvalue in random order, return the sorted array of original elements a1, a2, ..., an.

# Example

 For `shuffled = [1, 12, 3, 6, 2]`, the output should be `[1, 2, 3, 6]`.

 `1 + 3 + 6 + 2 = 12`, which means that 1, 3, 6 and 2 are original elements of the array.

 For `shuffled = [1, -3, -5, 7, 2]`, the output should be `[-5, -3, 2, 7]`.

# Input/Output

 - `[input]` integer array `shuffled`

    Array of at least two integers. It is guaranteed that there is an index i such that shuffled[i] = shuffled[0] + ... + shuffled[i - 1] + shuffled[i + 1] + ... + shuffled[n].

    Constraints:

    `2 ≤ shuffled.length ≤ 30,`

    `-300 ≤ shuffled[i] ≤ 300.`

 - `[output]` an integer array

    A `sorted` array of shuffled.length - 1 elements.

def shuffled_array(a):
    a.remove(sum(a) / 2)
    return sorted(a)


Solve in Python:
# Task
 A range-collapse representation of an array of integers looks like this: `"1,3-6,8"`, where `3-6` denotes the range from `3-6`, i.e. `[3,4,5,6]`.

 Hence `"1,3-6,8"` = `[1,3,4,5,6,8]`. Some other range-collapse representations of `[1,3,4,5,6,8]` include `"1,3-5,6,8", "1,3,4,5,6,8", etc`.

 Each range is written in the following format `"a-b"`, where `a < b`, and the whole range must belong to the array in an increasing order.

 You are given an array `arr`. Your task is to find the number of different range-collapse representations of the given array.

# Example

 For `arr = [1,3,4,5,6,8]`, the result should be `8`.
 ```
 "1,3-4,5,6,8"
 "1,3-4,5-6,8"
 "1,3-5,6,8"
 "1,3-6,8"
 "1,3,4-5,6,8"
 "1,3,4-6,8"
 "1,3,4,5-6,8"
 "1,3,4,5,6,8"```

# Input/OutPut

 - `[input]` integer array `arr`

  sorted array of different positive integers.

 - `[output]` an integer

  the number of different range-collapse representations of the given array.

descriptions=lambda arr:2**sum(arr[i]+1==arr[i+1] for i in range(len(arr)-1))


Solve in Python:
# Task
 A rectangle with sides equal to even integers a and b is drawn on the Cartesian plane. Its center (the intersection point of its diagonals) coincides with the point (0, 0), but the sides of the rectangle are not parallel to the axes; instead, they are forming `45 degree` angles with the axes.

 How many points with integer coordinates are located inside the given rectangle (including on its sides)?

# Example

 For `a = 6 and b = 4`, the output should be `23`

 The following picture illustrates the example, and the 23 points are marked green.

 ![](https://files.gitter.im/myjinxin2015/raYf/blob)

# Input/Output

 - `[input]` integer `a`

    A positive `even` integer.

    Constraints: `2 ≤ a ≤ 10000`.

 - `[input]` integer `b`

    A positive `even` integer.

    Constraints: `2 ≤ b ≤ 10000`.

 - `[output]` an integer

    The number of inner points with integer coordinates.

def rectangle_rotation(a, b):
    x, y = int(a / 2**0.5), int(b / 2**0.5)
    return 2*x*y + x + y + (x&1 == y&1)


Solve in Python:
# Task
 A robot is standing at the `(0, 0)` point of the Cartesian plane and is oriented towards the vertical (y) axis in the direction of increasing y values (in other words, he's facing up, or north). The robot executes several commands each of which is a single positive integer. When the robot is given a positive integer K it moves K squares forward and then turns 90 degrees clockwise.

 The commands are such that both of the robot's coordinates stay non-negative.

 Your task is to determine if there is a square that the robot visits at least twice after executing all the commands.

# Example

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

 The path of the robot looks like this:

 ![](https://codefightsuserpics.s3.amazonaws.com/tasks/robotWalk/img/path.png?_tm=1486563151922)

 The point `(4, 3)` is visited twice, so the answer is `true`.

# Input/Output

 - `[input]` integer array a

  An array of positive integers, each number representing a command.

  Constraints:

  `3 ≤ a.length ≤ 100`

  `1 ≤ a[i] ≤ 10000`

 - `[output]` a boolean value

  `true` if there is a square that the robot visits at least twice, `false` otherwise.

from math import gcd
from functools import reduce
from itertools import cycle

def robot_walk(a):
    g = reduce(gcd, a)
    a = [x//g for x in a]
    it = cycle([1j, 1, -1j, -1])
    seen = {0}
    pos = 0
    for x in a:
        d = next(it)
        for i in range(x):
            pos += d
            if pos in seen:
                return True
            seen.add(pos)
    return False


Solve in Python:
# Task
 Alireza and Ali have a `3×3 table` and playing on that. they have 4 table(2×2) A,B,C and D in this table.

 At beginning all of 9 numbers in 3×3 table is zero.

 Alireza in each move choose a 2×2 table from A, B, C and D and increase all of 4 numbers in that by one.

 He asks Ali, how much he increase table A, B, C and D. (if he cheats you should return `[-1]`)

 Your task is to help Ali.

# Example

 For
 ```
 table=
[[1,2,1],
[2,4,2],
[1,2,1]]```
The result should be `[1,1,1,1]`

 For:
 ```
Table=
[[3,7,4],
[5,16,11],
[2,9,7]]```
The result should be `[3,4,2,7]`

# Input/Output

 - `[input]` 2D integer array `table`

 `3×3` table.

 - `[output]` an integer array


Solve in Python:
# Task
 An `amazon` (also known as a queen+knight compound) is an imaginary chess piece that can move like a `queen` or a `knight` (or, equivalently, like a `rook`, `bishop`, or `knight`). The diagram below shows all squares which the amazon attacks from e4 (circles represent knight-like moves while crosses correspond to queen-like moves).

 ![](https://codefightsuserpics.s3.amazonaws.com/tasks/amazonCheckmate/img/amazon.png?_tm=1473934566013)

 Recently you've come across a diagram with only three pieces left on the board: a `white amazon`, `white king` and `black king`.

 It's black's move. You don't have time to determine whether the game is over or not, but you'd like to figure it out in your head.

 Unfortunately, the diagram is smudged and you can't see the position of the `black king`, so it looks like you'll have to check them all.

 Given the positions of white pieces on a standard chessboard, determine the number of possible black king's positions such that:

* It's a checkmate (i.e. black's king is under amazon's
 attack and it cannot make a valid move);

* It's a check (i.e. black's king is under amazon's attack
 but it can reach a safe square in one move);

* It's a stalemate (i.e. black's king is on a safe square
 but it cannot make a valid move);

* Black's king is on a safe square and it can make a valid move.

Note that two kings cannot be placed on two adjacent squares (including two diagonally adjacent ones).

# Example

 For `king = "d3" and amazon = "e4"`, the output should be `[5, 21, 0, 29]`.

 ![](https://codefightsuserpics.s3.amazonaws.com/tasks/amazonCheckmate/img/example1.png?_tm=1473934566299)

 `Red crosses` correspond to the `checkmate` positions, `orange pluses` refer to `checks` and `green circles` denote `safe squares`.

 For `king = "a1" and amazon = "g5"`, the output should be `[0, 29, 1, 29]`.

 ![](https://codefightsuserpics.s3.amazonaws.com/tasks/amazonCheckmate/img/example2.png?_tm=1473934566670)

 `Stalemate` position is marked by a `blue square`.

# Input

 -...

def amazon_check_mate(king, amazon):
    if king == amazon:
        return []
    king_pos = [ ord(king[1])-ord('1'), ord(king[0])-ord('a') ]
    amazon_pos = [ ord(amazon[1])-ord('1'), ord(amazon[0])-ord('a') ]
    board = [[' '] * 8, [' '] * 8, [' '] * 8, [' '] * 8, [' '] * 8, [' '] * 8, [' '] * 8, [' '] * 8]
    board[king_pos[0]][king_pos[1]] = "K"
    board[amazon_pos[0]][amazon_pos[1]] = 'A'
    dirs = [[1,0],[0,1],[-1,0],[0,-1],[1,-1],[-1,1],[1,1],[-1,-1],[1,2],[2,1],[1,-2],[2,-1],[-1,2],[-2,1],[-2,-1],[-1,-2]]
    # king
    for i in range(8):
        row, col = king_pos[0]+dirs[i][0], king_pos[1]+dirs[i][1]
        if (0 <= row < 8) and (0 <= col < 8):
            board[row][col] = 'B' if (board[row][col] == ' ') else 'C'
    # amazon
    for i in range(16):
        row, col = amazon_pos[0]+dirs[i][0], amazon_pos[1]+dirs[i][1]
        while (0 <= row < 8) and (0 <= col < 8) and board[row][col] in [' ','B']:
            if board[row][col] == ' ':
                board[row][col] = 'X'
            if 8 <= i:
                break
            row, col = row+dirs[i][0], col+dirs[i][1]
    # count
    res = [0,0,0,0]
    for row in range(8):
        for col in range(8):
            if board[row][col] not in ['K','B','A','C']:
                check = (board[row][col] == 'X')
                valid_around = 0
                for i in range(8):
                    row_, col_ = row+dirs[i][0], col+dirs[i][1]
                    if (0 <= row_ < 8) and (0 <= col_ < 8) and board[row_][col_] in [' ','A']:
                        valid_around += 1
                if check:
                    res[0 if (valid_around == 0) else 1] += 1
                elif valid_around == 0:
                    res[2] += 1
                else:
                    res[3] += 1
    return res


Solve in Python:
# Task
 Below we will define what and n-interesting polygon is and your task is to find its area for a given n.

 A 1-interesting polygon is just a square with a side of length 1. An n-interesting polygon is obtained by taking the n - 1-interesting polygon and appending 1-interesting polygons to its rim side by side. You can see the 1-, 2- and 3-interesting polygons in the picture below.

 ![](https://files.gitter.im/myjinxin2015/Gwsw/blob)

# Example

 For `n = 1`, the output should be `1`;

 For `n = 2`, the output should be `5`;

 For `n = 3`, the output should be `13`.

# Input/Output

 - `[input]` integer `n`

    Constraints: `1 ≤ n < 10000.`

 - `[output]` an integer

   The area of the n-interesting polygon.

def shape_area(n):
    return n**2 + (n - 1) ** 2


Solve in Python:
# Task
 Call two arms equally strong if the heaviest weights they each are able to lift are equal.

 Call two people equally strong if their strongest arms are equally strong (the strongest arm can be both the right and the left), and so are their weakest arms.

 Given your and your friend's arms' lifting capabilities find out if you two are equally strong.

# Example

 For `yourLeft = 10, yourRight = 15, friendsLeft = 15 and friendsRight = 10`, the output should be `true`;

 For `yourLeft = 15, yourRight = 10, friendsLeft = 15 and friendsRight = 10`, the output should be `true`;

 For `yourLeft = 15, yourRight = 10, friendsLeft = 15 and friendsRight = 9,` the output should be `false`.

# Input/Output

 - `[input]` integer `yourLeft`

    A non-negative integer representing the heaviest weight you can lift with your left arm.

 - `[input]` integer `yourRight`

    A non-negative integer representing the heaviest weight you can lift with your right arm.

 - `[input]` integer `friendsLeft`

    A non-negative integer representing the heaviest weight your friend can lift with his or her left arm.

 - `[input]` integer `friendsRight`

    A non-negative integer representing the heaviest weight your friend can lift with his or her right arm.

 - `[output]` a boolean value

def are_equally_strong(yl, yr, fl, fr):
    return sorted([yl, yr]) == sorted([fl, fr])


Solve in Python:
# Task
 Changu and Mangu are great buddies. Once they found an infinite paper which had 1,2,3,4,5,6,7,8,......... till infinity, written on it.

 Both of them did not like the sequence and started deleting some numbers in the following way.
 ```
First they deleted every 2nd number.
So remaining numbers on the paper: 1,3,5,7,9,11..........till infinity.
Then they deleted every 3rd number.
So remaining numbers on the paper: 1,3,7,9,13,15..........till infinity..
Then they deleted every 4th number.
So remaining numbers on the paper: 1,3,7,13,15..........till infinity.```
Then kept on doing this (deleting every 5th, then every 6th ...) untill they got old and died.

 It is obvious that some of the numbers will never get deleted(E.g. 1,3,7,13..) and hence are know to us as survivor numbers.

 Given a number `n`, check whether its a survivor number or not.

# Input/Output

 - `[input]` integer `n`

  `0 < n <= 10^8`

 - `[output]` a boolean value

  `true` if the number is a survivor else `false`.

def survivor(m):
    i = 2
    while  i <= m:
        q, r = divmod(m, i)
        if r == 0: return False
        m, i = m - q, i + 1
    return True


Solve in Python:
# Task
 CodeBots decided to make a gift for CodeMaster's birthday. They got a pack of candies of various sizes from the store, but instead of giving the whole pack they are trying to make the biggest possible candy from them. On each turn it is possible:

 ```
 to pick any two candies of the same size and merge
 them into a candy which will be two times bigger;

 to pick a single candy of an even size and split it
 into two equal candies half of this size each.```
What is the size of the biggest candy they can make as a gift?

# Example

 For `arr = [2, 4, 8, 1, 1, 15]`, the output should be 16.
```
[2, 4, 8, 1, 1, 15] --> [2, 4, 8, 2, 15]
-->[4, 4, 8, 15] --> [8, 8, 15] --> [16, 15] -->choose 16
```

# Input/Output

 - [input] integer array `arr`

    Array of positive integers.

    Constraints:

    `5 ≤ inputArray.length ≤ 50,`

    `1 ≤ inputArray[i] ≤ 100.`

 - `[output]` an integer

def obtain_max_number(arr):
    last_len = 0
    while len(arr) != last_len:
        last_len = len(arr)
        for n in arr:
            if arr.count(n) > 1:
                arr.remove(n)
                arr.remove(n)
                arr.append(n*2)

    return max(arr)


Solve in Python:
# Task
 Consider a `bishop`, a `knight` and a `rook` on an `n × m` chessboard. They are said to form a `triangle` if each piece attacks exactly one other piece and is attacked by exactly one piece.

 Calculate the number of ways to choose positions of the pieces to form a triangle.

 Note that the bishop attacks pieces sharing the common diagonal with it; the rook attacks in horizontal and vertical directions; and, finally, the knight attacks squares which are two squares horizontally and one square vertically, or two squares vertically and one square horizontally away from its position.

 ![](https://codefightsuserpics.s3.amazonaws.com/tasks/chessTriangle/img/moves.png?_tm=1473934712872)

# Example

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

 ![](https://codefightsuserpics.s3.amazonaws.com/tasks/chessTriangle/img/combinations.png?_tm=1473934713038)

# Input/Output

- `[input]` integer `n`

    Constraints: `1 ≤ n ≤ 40.`

 - `[input]` integer `m`

    Constraints: `1 ≤ m ≤ 40, 3 ≤ n x m`.

 - `[output]` an integer


Solve in Python:
# Task
 Consider a string of lowercase Latin letters and space characters (" ").

 First, rearrange the letters in each word `alphabetically`.

 And then rearrange the words in ascending order of the sum of their characters' `ASCII` values.

 If two or more words have the same `ASCII` value, rearrange them by their length in ascending order; If their length still equals to each other, rearrange them `alphabetically`.

 Finally, return the result.

# Example

 For `s = "batman is bruce wayne"`, the result should be `"is bceru aenwy aamntb"`.
```
After rearranging the letters the string turns into
"aamntb is bceru aenwy".
The ASCII values of each word are: [627, 220, 529, 548].
After sorting the words the following string is obtained:
"is bceru aenwy aamntb" (with ASCII values of [220, 529, 548, 627]).```

 For `s = "peter parker is spiderman"`, the result should be `"is eeprt aekprr adeimnprs"`

 `(ASCII values: [220, 554, 645, 963])`

# Input/Output

 - `[input]` string `s`

  A string of lowercase words. Each word is separated by exactly one space character.

 - `[output]` a string

revamp = lambda s: ' '.join(sorted( map(lambda x: ''.join(sorted(x)), s.split()), key = lambda w: (sum(map(ord,w)), len(w), w)  ))


Solve in Python:
# Task
 Consider the following algorithm for constructing 26 strings S(1) .. S(26):
```
S(1) = "a";
For i in [2, 3, ..., 26]:
S(i) = S(i - 1) + character(i) + S(i - 1).```

 For example:
```
S(1) = "a"
S(2) = S(1) + "b" + S(1) = "a" + "b" + "a" = "aba"
S(3) = S(2) + "c" + S(2) = "aba" + "c" +"aba" = "abacaba"
...
S(26) = S(25) + "z" + S(25)```
Finally, we got a long string S(26). Your task is to find the `k`th symbol (indexing from 1) in the string S(26). All strings consist of lowercase letters only.

# Input / Output

 - `[input]` integer `k`

  1 ≤ k < 2^(26)

 - `[output]` a string(char in C#)

  the `k`th symbol of S(26)

def abacaba(k):
    return chr(96 + (k & -k).bit_length())


Solve in Python:
# Task
 Consider the following ciphering algorithm:
```
For each character replace it with its code.
Concatenate all of the obtained numbers.
```
Given a ciphered string, return the initial one if it is known that it consists only of lowercase letters.

 Note: here the character's code means its `decimal ASCII code`, the numerical representation of a character used by most modern programming languages.

# Example

 For `cipher = "10197115121"`, the output should be `"easy"`.

 Explanation:
 ```
 charCode('e') = 101,
 charCode('a') = 97,
 charCode('s') = 115
 charCode('y') = 121.
```
# Input/Output

 - `[input]` string `cipher`

   A non-empty string which is guaranteed to be a cipher for some other string of lowercase letters.

 - `[output]` a string

from re import findall
def decipher(cipher):
    return "".join(chr(int(d)) for d in findall("9\d|1[01]\d|12[012]",cipher))


Solve in Python:
# Task
 Consider the following operation:

 We take a positive integer `n` and replace it with the sum of its `prime factors` (if a prime number is presented multiple times in the factorization of `n`, then it's counted the same number of times in the sum).

 This operation is applied sequentially first to the given number, then to the first result, then to the second result and so on.., until the result remains the same.

  Given number `n`, find the final result of the operation.

# Example

  For `n = 24`, the output should be `5`.
```
24 -> (2 + 2 + 2 + 3) = 9 -> (3 + 3) = 6 -> (2 + 3) = 5 -> 5.
So the answer for n = 24 is 5.```

# Input/Output

 - `[input]` integer `n`

  Constraints: `2 ≤ n ≤ 10000.`

 - `[output]` an integer

def prime_factors(n):
    factors = []
    for k in (2, 3):
        while n % k == 0:
            n //= k
            factors.append(k)
    k = 5
    step = 2
    while k * k <= n:
        if n % k:
            k += step
            step = 6 - step
        else:
            n //= k
            factors.append(k)
    if n > 1:
        factors.append(n)
    return factors

def factor_sum(n):
    while True:
        fs = sum(prime_factors(n))
        if fs == n:
            return fs
        n = fs


Solve in Python:
# Task
 Define crossover operation over two equal-length strings A and B as follows:

 the result of that operation is a string of the same length as the input strings result[i] is chosen at random between A[i] and B[i].

 Given array of strings `arr` and a string result, find for how many pairs of strings from `arr` the result of the crossover operation over them may be equal to result.

 Note that (A, B) and (B, A) are the same pair. Also note that the pair cannot include the same element of the array twice (however, if there are two equal elements in the array, they can form a pair).

# Example

 For `arr = ["abc", "aaa", "aba", "bab"]` and `result = "bbb"`, the output should be `2`.

 ```
"abc" and "bab" can crossover to "bbb"
"aba" and "bab" can crossover to "bbb"
```
# Input/Output

 - `[input]` string array `arr`

   A non-empty array of equal-length strings.

   Constraints: `2 ≤ arr.length ≤ 10, 1 ≤ arr[i].length ≤ 10.`

 - `[input]` string `result`

   A string of the same length as each of the arr elements.

   Constraints: `result.length = arr[i].length.`

 - `[output]` an integer

from collections import Counter

def strings_crossover(arr, result):
    lstBit = [ int(''.join(['01'[x==y] for x,y in zip(result, w)]), 2) for w in arr ]
    target = 2**len(result) - 1
    c      = Counter(lstBit)

    v1 = sum( v*w for k,v in list(c.items()) for l,w in list(c.items()) if k|l == target and k!=target and l!=target) // 2
    v2 = 0 if target not in c else (sum(c.values())-c[target]) * c[target]
    v3 = 0 if c[target] < 2 else c[target] * (c[target]-1) // 2

    return v1+v2+v3


Solve in Python:
# Task
 Dudka has `n` details. He must keep exactly 3 of them.

 To do this, he performs the following operations until he has only 3 details left:
```
He numbers them.
He keeps those with either odd or even numbers and throws the others away.```

 Dudka wants to know how many ways there are to get exactly 3 details. Your task is  to help him calculate it.

# Example

 For `n = 6`, the output should be `2`.
 ```
Dudka has 6 details, numbered 1 2 3 4 5 6.
He can keep either details with numbers 1, 3, 5,
or with numbers 2, 4, 6.
Both options leave him with 3 details,
so the answer is 2.```

 For `n = 7`, the output should be `1`.
 ```
Dudka has 7 details, numbered 1 2 3 4 5 6 7.
He can keep either details 1 3 5 7, or details 2 4 6.
If he keeps details 1 3 5 7 ,
he won't be able to get 3 details in the future,
because at the next step he will number them 1 2 3 4
and will have to keep either details 1 3, or 2 4,
only two details anyway.
That's why he must keep details 2 4 6 at the first step,
so the answer is 1.```

# Input/Output

 - `[input]` integer `n`

  `3 ≤ n ≤ 10^9`

 - `[output]` an integer

  The number of ways to get exactly 3 details.


Solve in Python:
# Task
 Four men, `a, b, c and d` are standing in a line, one behind another.

 There's a wall between the first three people (a, b and c) and the last one (d).

 a, b and c are lined up in order of height, so that person a can see the backs of b and c, person b can see the back of c, and c can see just the wall.

 There are 4 hats, 2 black and 2 white. Each person is given a hat. None of them can see their own hat, but person a can see the hats of b and c, while person b can see the hat of person c. Neither c nor d can see any hats.

 Once a person figures out their hat's color, they shouts it.

 ![](http://stuffbox.in/wp-content/uploads/2016/08/Guess-hat-colour-604x270.png)

 Your task is to return the person who will guess their hat first. You can assume that they will speak only when they reach a correct conclusion.

# Input/Output

 - `[input]` string `a`

  a's hat color ("white" or "black").

 - `[input]` string `b`

  b's hat color ("white" or "black").

 - `[input]` string `c`

  c's hat color ("white" or "black").

 - `[input]` string `d`

  d's hat color ("white" or "black").

 - `[output]` an integer

 The person to guess his hat's color first, `1 for a, 2 for b, 3 for c and 4 for d`.


Solve in Python:
# Task
 Fred Mapper is considering purchasing some land in Louisiana to build his house on. In the process of investigating the land, he learned that the state of Louisiana is actually shrinking by 50 square miles each year, due to erosion caused by the Mississippi River. Since Fred is hoping to live in this house the rest of his life, he needs to know if his land is going to be lost to erosion.

 After doing more research, Fred has learned that the land that is being lost forms a semicircle. This semicircle is part of a circle centered at (0,0), with the line that bisects the circle being the `x` axis. Locations below the `x` axis are in the water. The semicircle has an area of 0 at the beginning of year 1. (Semicircle illustrated in the Figure.)

 ![](http://media.openjudge.cn/images/1005/semicircle.GIF)

 Given two coordinates `x` and `y`, your task is to calculate that Fred Mapper's house will begin eroding in how many years.

 Note:

 1. No property will appear exactly on the semicircle boundary: it will either be inside or outside.

 2. All locations are given in miles.

 3. (0,0) will not be given.

# Example

 For `x = 1, y = 1`, the result should be `1`.

 After 1 year, Fred Mapper's house will begin eroding.

 For `x = 25, y = 0`, the result should be `20`.

 After 20 year, Fred Mapper's house will begin eroding.

# Input/Output

 - `[input]` integer `x`

  The X coordinates of the land Fred is considering. It will be an integer  point numbers measured in miles.

  `-100 <= x <= 100`

 - `[input]` integer `y`

  The Y coordinates of the land Fred is considering. It will be an integer point numbers measured in miles.

  `0 <= y <= 100`

 - `[output]` an integer

 The first year (start from 1) this point will be within the semicircle AT THE END OF YEAR.

from math import pi, sqrt, hypot
from itertools import count

def radius(year):
    return sqrt(100 * year / pi)

def does_fred_need_houseboat(x,y):
    return next(year for year in count(1) if hypot(x, y) < radius(year))


Solve in Python:
# Task
 Given a `sequence` of integers, check whether it is possible to obtain a strictly increasing sequence by erasing no more than one element from it.

# Example

 For `sequence = [1, 3, 2, 1]`, the output should be `false`;

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

# Input/Output

 - `[input]` integer array `sequence`

    Constraints: `2 ≤ sequence.length ≤ 1000, -10000 ≤ sequence[i] ≤ 10000.`

 - `[output]` a boolean value

    `true` if it is possible, `false` otherwise.

almost_increasing_sequence=lambda a:sum((y>=z)*(2-(x<z))for x,y,z in zip([a[1]-1]+a[:-3]+[a[-1]-1],a,a[1:]))<2


Solve in Python:
# Task
 Given a position of a knight on the standard chessboard, find the number of different moves the knight can perform.

 The knight can move to a square that is two squares horizontally and one square vertically, or two squares vertically and one square horizontally away from it. The complete move therefore looks like the letter L. Check out the image below to see all valid moves for a knight piece that is placed on one of the central squares.

 ![](https://codefightsuserpics.s3.amazonaws.com/tasks/chessKnight/img/knight.jpg?_tm=1473533979951)

# Example

 For `cell = "a1"`, the output should be `2`.

 ![](https://codefightsuserpics.s3.amazonaws.com/tasks/chessKnight/img/ex_1.jpg?_tm=1473533980197)

 For `cell = "c2"`, the output should be `6`.

 ![](https://codefightsuserpics.s3.amazonaws.com/tasks/chessKnight/img/ex_2.jpg?_tm=1473533980368)

# Input/Output

 - `[input]` string `cell`

    String consisting of letter+number - coordinates of the knight on an 8 × 8 chessboard in chess notation.

 - `[output]` an integer

result = (2, 3, 4, 3, 4, 6, 4, 6, 8)

def chess_knight(cell):
    x, y = ord(cell[0])-97, int(cell[1])-1
    x, y = min(2, x, 7-x), min(2, y, 7-y)
    return result[3*x + y]


Solve in Python:
# Task
 Given a rectangular `matrix` and integers `a` and `b`, consider the union of the ath row and the bth (both 0-based) column of the `matrix`. Return sum of all elements of that union.

# Example

 For
```
matrix = [[1, 1, 1, 1],
          [2, 2, 2, 2],
          [3, 3, 3, 3]]
a = 1 and b = 3 ```
the output should be `12`.

 Here `(2 + 2 + 2 + 2) + (1 + 3) = 12`.

# Input/Output

 - `[input]` 2D integer array `matrix`

    2-dimensional array of integers representing a rectangular matrix.

    Constraints: `1 ≤ matrix.length ≤ 5, 1 ≤ matrix[0].length ≤ 5, 1 ≤ matrix[i][j] ≤ 100.`

 - `[input]` integer `a`

  A non-negative integer less than the number of matrix rows.

   Constraints: `0 ≤ a < matrix.length.`

 - `[input]` integer `b`

   A non-negative integer less than the number of matrix columns.

   Constraints: `0 ≤ b < matrix[i].length. `

 - `[output]` an integer

def crossing_sum(matrix, row, col):
    a = matrix[row]
    b = [i[col] for num,i in enumerate(matrix) if num!=row]
    return sum(a) + sum(b)


Solve in Python:
# Task
 Given a rectangular matrix containing only digits, calculate the number of different `2 × 2` squares in it.

# Example

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

 Here are all 6 different 2 × 2 squares:

 ```
 1 2
 2 2

 2 1
 2 2

 2 2
 2 2

 2 2
 1 2

 2 2
 2 3

 2 3
 2 1
 ```

# Input/Output

 - `[input]` 2D integer array `matrix`

    Constraints:

    `1 ≤ matrix.length ≤ 100,`

    `1 ≤ matrix[i].length ≤ 100,`

    `0 ≤ matrix[i][j] ≤ 9.`

 - `[output]` an integer

    The number of different `2 × 2` squares in matrix.

def different_squares(matrix):
    result = []
    for i in range(len(matrix) - 1):
        for j in range(len(matrix[0]) - 1):
            one = [
                matrix[i][j:j + 2],
                matrix[i + 1][j:j + 2]
            ]
            if one not in result:
                result.append(one)
    return len(result)


Solve in Python:
# Task
 Given a sequence of 0s and 1s, determine if it is a prefix of Thue-Morse sequence.

 The infinite Thue-Morse sequence is obtained by first taking a sequence containing a single 0 and then repeatedly concatenating the current sequence with its binary complement.

 A binary complement of a sequence X is a sequence Y of the same length such that the sum of elements X_i and Y_i on the same positions is equal to 1 for each i.

 Thus the first few iterations to obtain Thue-Morse sequence are:
```
0
0 1
0 1 1 0
0 1 1 0 1 0 0 1
...
```

# Examples

 For `seq=[0, 1, 1, 0, 1]`, the result should be `true`.

 For `seq=[0, 1, 0, 0]`, the result should be `false`.

# Inputs & Output

 - `[input]` integer array `seq`

  An non-empty array.

  Constraints:

  `1 <= seq.length <= 1000`

  `seq[i] ∈ [0,1]`

 - `[output]` a boolean value

  `true` if it is a prefix of Thue-Morse sequence. `false` otherwise.


Solve in Python:
# Task
 Given a sorted array of integers `A`, find such an integer x that the value of `abs(A[0] - x) + abs(A[1] - x) + ... + abs(A[A.length - 1] - x)`
is the smallest possible (here abs denotes the `absolute value`).

 If there are several possible answers, output the smallest one.

# Example

 For `A = [2, 4, 7]`, the output should be `4`.

# Input/Output

 - `[input]` integer array `A`

    A non-empty array of integers, sorted in ascending order.

    Constraints:

    `1 ≤ A.length ≤ 200,`

    `-1000000 ≤ A[i] ≤ 1000000.`

 - `[output]` an integer

def absolute_values_sum_minimization(A):
    lst = [[sum([abs(j-i) for j in A]), i] for i in A]
    return sorted(lst)[0][-1]


Solve in Python:
# Task
 Given a string `s`, find out if its characters can be rearranged to form a palindrome.

# Example

 For `s = "aabb"`, the output should be `true`.

 We can rearrange `"aabb"` to make `"abba"`, which is a palindrome.

# Input/Output

 - `[input]` string `s`

    A string consisting of lowercase English letters.

    Constraints:

    `4 ≤ inputString.length ≤ 50.`

 - `[output]` a boolean value

    `true` if the characters of the inputString can be rearranged to form a palindrome, `false` otherwise.

from collections import Counter
def palindrome_rearranging(s):
    return len([v for v in Counter(s).values() if v%2]) < 2


Solve in Python:
# Task
 Given a string `str`, find the shortest possible string which can be achieved by adding characters to the end of initial string to make it a palindrome.

# Example

 For `str = "abcdc"`, the output should be `"abcdcba"`.

# Input/Output

 - `[input]` string `str`

    A string consisting of lowercase latin letters.

    Constraints: `3 ≤ str.length ≤ 10`.

 - `[output]` a string

def build_palindrome(str):
    suf = ""
    for c in str:
        pal = str + suf
        if pal == pal[::-1]:
            return pal
        suf = c + suf