Solve in Python:
Consider the following operations on a triple of integers. In one operation, you should:
- Choose an integer $d$ and an arithmetic operation ― either addition or multiplication.
- Choose a subset of elements of the triple.
- Apply the arithmetic operation to each of the chosen elements, i.e. either add $d$ to each of them or multiply each of them by $d$.
For example, if we have a triple $(3, 5, 7)$, we may choose to add $3$ to the first and third element, and we get $(6, 5, 10)$ using one operation.
You are given an initial triple $(p, q, r)$ and a target triple $(a, b, c)$. Find the minimum number of operations needed to transform $(p, q, r)$ into $(a, b, c)$.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains three space-separated integers $p$, $q$ and $r$.
- The second line contains three space-separated integers $a$, $b$ and $c$.

-----Output-----
For each test case, print a single line containing one integer ― the minimum required number of operations.

-----Constraints-----
- $1 \le T \le 1,000$
- $|p|, |q|, |r|, |a|, |b|, |c| \le 10^9$

-----Subtasks-----
Subtask #1 (10 points): $|p|, |q|, |r|, |a|, |b|, |c| \le 10$
Subtask #2 (90 points): original constraints

-----Example Input-----
2
3 5 7
6 5 10
8 6 3
9 7 8

-----Example Output-----
1
2

-----Explanation-----
Example case 1: We add $3$ to the first and third element of $(3, 5, 7)$ to form $(6, 5, 10)$.
Example case 2: We can add $1$ to each element to form $(9, 7, 4)$ and then multiply the third element by $2$.

def eq_solve(v0, v1, u0, u1):
    den = u0 - v0
    num = u1 - v1
    if den != 0:
        return num / den
    return 1

def solve(p, q, r, a, b, c, rs):
    if p == a and q == b and r == c:
        return rs
    if rs >= 2:
        return 3
    res = 3
    adds = [a - p, b - q, c - r]
    muls = []
    if p != 0:
        muls.append(a / p)
    if q != 0:
        muls.append(b / q)
    if r != 0:
        muls.append(c / r)
    muls.append(eq_solve(p, a, q, b))
    muls.append(eq_solve(p, a, r, c))
    muls.append(eq_solve(q, b, r, c))
    msks = 2 ** 3
    for msk in range(msks):
        for add in adds:
            np = p
            nq = q
            nr = r
            if (msk & 1) > 0:
                np += add
            if (msk & 2) > 0:
                nq += add
            if (msk & 4) > 0:
                nr += add
            res = min(res, solve(np, nq, nr, a, b, c, rs + 1))
        for mul in muls:
            np = p
            nq = q
            nr = r
            if (msk & 1) > 0:
                np *= mul
            if (msk & 2) > 0:
                nq *= mul
            if (msk & 4) > 0:
                nr *= mul
            res = min(res, solve(np, nq, nr, a, b, c, rs + 1))
    return res

t = int(input())

while t > 0:
    p, q, r = map(int, input().split())
    a, b, c = map(int, input().split())
    z = solve(p, q, r, a, b, c, 0)
    print(z)
    t -= 1


Solve in Python:
Consider the following process. You have a binary string (a string where each character is either 0 or 1) $w$ of length $n$ and an integer $x$. You build a new binary string $s$ consisting of $n$ characters. The $i$-th character of $s$ is chosen as follows:

  if the character $w_{i-x}$ exists and is equal to 1, then $s_i$ is 1 (formally, if $i > x$ and $w_{i-x} = $ 1, then $s_i = $ 1);  if the character $w_{i+x}$ exists and is equal to 1, then $s_i$ is 1 (formally, if $i + x \le n$ and $w_{i+x} = $ 1, then $s_i = $ 1);  if both of the aforementioned conditions are false, then $s_i$ is 0.

You are given the integer $x$ and the resulting string $s$. Reconstruct the original string $w$.

-----Input-----

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

Each test case consists of two lines. The first line contains the resulting string $s$ ($2 \le |s| \le 10^5$, each character of $s$ is either 0 or 1). The second line contains one integer $x$ ($1 \le x \le |s| - 1$).

The total length of all strings $s$ in the input does not exceed $10^5$.

-----Output-----

For each test case, print the answer on a separate line as follows:

  if no string $w$ can produce the string $s$ at the end of the process, print $-1$;  otherwise, print the binary string $w$ consisting of $|s|$ characters. If there are multiple answers, print any of them.

-----Example-----
Input
3
101110
2
01
1
110
1

Output
111011
10
-1

import sys

input=sys.stdin.readline

for _ in range(int(input())):
    s=input().rstrip()
    x=int(input())
    n=len(s)
    ans=["1" for i in range(n)]
    for i in range(n):
        if s[i]=="0":
            if i-x>=0:
                ans[i-x]="0"
            if i+x<n:
                ans[i+x]="0"
    for i in range(n):
        if s[i]=="1":
            check=False
            if i-x>=0:
                check|=(ans[i-x]=="1")
            if i+x<n:
                check|=(ans[i+x]=="1")
            if not check:
                print(-1)
                break
    else:
        print("".join(ans))


Solve in Python:
Consider the following series:

`0,1,2,3,4,5,6,7,8,9,10,22,11,20,13,24...`There is nothing special between numbers `0` and `10`.

Let's start with the number `10` and derive the sequence. `10` has digits `1` and `0`. The next possible number that does not have a `1` or a `0` is `22`. All other numbers between `10` and `22` have a `1` or a `0`.

From `22`, the next number that does not have a `2` is `11`. Note that `30` is also a possibility because it is the next *higher* number that does not have a `2`, but we must select  the *lowest* number that fits and **is not already in the sequence**.

From `11`, the next lowest number that does not have a `1` is `20`.

From `20`, the next lowest number that does not have a `2` or a `0` is `13`, then `24` , then `15` and so on.

Once a number appers in the series, it cannot appear again.

You will be given an index number and your task will be return the element at that position. See test cases for more examples.

Note that the test range is `n <= 500`.

Good luck!

If you like this Kata, please try:

[Sequence convergence](https://www.codewars.com/kata/59971e64bfccc70748000068)

[https://www.codewars.com/kata/unique-digit-sequence-ii-optimization-problem](https://www.codewars.com/kata/unique-digit-sequence-ii-optimization-problem)

def find_num(n):
    c = 0
    k = -1
    mas = []
    while len(mas) <= n:
        k += 1
        if  k > 10:
            c = set(str(mas[len(mas)-1]))
            if len(c) == len(set(str(mas[len(mas)-1]))-set(str(k))) and k not in mas:
                mas.append(k)
                k = 10
        else:
            mas.append(k)
    return mas[len(mas)-1]


Solve in Python:
Consider the following series:

`1, 2, 4, 8, 16, 22, 26, 38, 62, 74, 102, 104, 108, 116, 122`

It is generated as follows:

* For single digit integers, add the number to itself to get the next element.
* For other integers, multiply all the non-zero digits and add the result to the original number to get the next element.

For example: `16 + (6 * 1) = 22` and `104 + (4 * 1) = 108`.

Let's begin the same series with a seed value of `3` instead of `1`:

`3, 6, 12, 14, 18, 26, 38, 62, 74, 102, 104, 108, 116, 122`

Notice that the two sequences converge at `26` and are identical therefter. We will call the series seeded by a value of `1` the "base series" and the other series the "test series".

You will be given a seed value for the test series and your task will be to return the number of integers that have to be generated in the test series before it converges to the base series. In the case above:
```Python
convergence(3) = 5, the length of [3, 6, 12, 14, 18].
```

Good luck!

If you like this Kata, please try:

[Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3)

[Unique digit sequence](https://www.codewars.com/kata/599688d0e2800dda4e0001b0)

[Divisor harmony](https://www.codewars.com/kata/59bf97cd4f98a8b1cd00007e)

def sumIntegers(n):
    mod=10
    lst=[]
    while n>0:
        lst.append(n%mod)
        n-=n%mod
        n//=10
    result = 1
    for i in lst:
        if i!=0:
            result*=i
    return result
def convergence(n):
    ntest=1
    i=0
    while True:
        if ntest == n:
            return i
        elif n>ntest:
            ntest = ntest + sumIntegers(ntest)
        else:
            n=n+sumIntegers(n)
            i+=1


Solve in Python:
Consider the following well known rules:

- A number is divisible by 3 if the sum of its digits is divisible by 3. Let's call '3' a "1-sum" prime
- For 37, we take numbers in groups of threes from the right and check if the sum of these groups is divisible by 37.
  Example: 37 * 123456787 = 4567901119 => 4 + 567 + 901 + 119 = 1591 = 37 * 43. Let's call this a "3-sum" prime because we use groups of 3.
- For 41, we take numbers in groups of fives from the right and check if the sum of these groups is divisible by 41. This is a "5-sum" prime.
- Other examples: 239 is a "7-sum" prime (groups of 7), while 199 is a "99-sum" prime (groups of 99).

Let's look at another type of prime:
- For 11, we need to add all digits by alternating their signs from the right.
  Example: 11 * 123456 = 1358016 => 6-1+0-8+5-3+1 = 0, which is divible by 11. Let's call this a "1-altsum" prime
- For 7, we need to group the digits into threes from the right and add all groups by alternating their signs.
  Example: 7 * 1234567891234 = 8641975238638 => 638 - 238 + 975 - 641 + 8 = 742/7 = 106.
- 7 is a "3-altsum" prime because we use groups of threes. 47 is a "23-altsum" (groups of 23), while 73 is a "4-altsum" prime (groups of 4).

You will be given a prime number `p` and your task is to find the smallest positive integer `n` such that `p’s` divisibility testing is `n-sum` or `n-altsum`.

For example:
```
solve(3) = "1-sum"
solve(7) = "3-altsum"
```
Primes will not exceed `50,000,000`. More examples in test cases.

You can get some insight from [Fermat's little theorem](https://en.wikipedia.org/wiki/Fermat%27s_little_theorem).

Good luck!

def solve(p):
    i, ans = 1, 0
    while i * i <= p - 1:
        if (p - 1) % i == 0:
            j = (p - 1) // i
            if pow(10, i, p) == 1:
                ans = i
                break
            if pow(10, j, p) == 1:  ans = j
        i += 1
    if pow(10, ans // 2, p) == p - 1: ans = str(ans // 2) + '-altsum'
    else: ans = str(ans) + '-sum'
    return ans


Solve in Python:
Consider the fraction, $a/b$, where $a$ and $b$ are positive integers. If $a < b$ and $GCD(a,b) = 1$, it is called a reduced proper fraction.
If we list the set of a reduced proper fraction for $d \leq 8$, (where $d$ is the denominator) in ascending order of size, we get:
$1/8$, $1/7$, $1/6$, $1/5$, $1/4$, $2/7$, $1/3$, $3/8$, $2/5$ , $3/7$, $1/2$, $4/7$, $3/5$, $5/8$, $2/3$, $5/7$, $3/4$, $4/5$,  $5/6$, $6/7$, $7/8$
It can be seen that $2/5$ is the fraction immediately to the left of $3/7$.
By listing the set of reduced proper fractions for $d \leq N$ in ascending order of value, find the numerator and denominator of the fraction immediately to the left of $a/b$ when $a$ and $b$ are given.

-----Input:-----
- First line of input contains an integer $T$, number of test cases
- Next $T$ lines contain $a$ $b$ $N$ separated by space

-----Output:-----
Print the numerator and denominator separated by a space corresponding to each test case on a new line

-----Constraints-----
- $1 \leq T \leq 50$
- $1 \leq a < b \leq 10^9$
- $GCD(a,b) = 1$
- $b < N \leq 10^{15}$

-----Subtasks-----
- 10 points: $1 \leq N \leq 100$
- 30 points : $1 \leq N \leq 10^6$
- 60 points : $1 \leq N \leq 10^{15}$

-----Sample Input:-----
5
3 7 8
3 5 8
4 5 8
6 7 8
1 5 8

-----Sample Output:-----
2 5
4 7
3 4
5 6
1 6

from sys import stdin
from fractions import Fraction

input = stdin.readline

for _ in range(int(input())):
    a, b, n = list(map(int, input().split()))
    ab = Fraction(a, b)

    p = set()

    for i in range(1, n+1):
        for j in range(n, 0, -1):
            x = Fraction(i, j)

            if x > ab:
                break

            p.add(x)

    x = sorted(p)[-2]

    print(x.numerator, x.denominator)


Solve in Python:
Consider the infinite sequence $s$ of positive integers, created by repeating the following steps:

  Find the lexicographically smallest triple of positive integers $(a, b, c)$ such that   $a \oplus b \oplus c = 0$, where $\oplus$ denotes the bitwise XOR operation.  $a$, $b$, $c$ are not in $s$.  Here triple of integers $(a_1, b_1, c_1)$ is considered to be lexicographically smaller than triple $(a_2, b_2, c_2)$ if sequence $[a_1, b_1, c_1]$ is lexicographically smaller than sequence $[a_2, b_2, c_2]$.  Append $a$, $b$, $c$ to $s$ in this order.  Go back to the first step.

You have integer $n$. Find the $n$-th element of $s$.

You have to answer $t$ independent test cases.

A sequence $a$ is lexicographically smaller than a sequence $b$ if in the first position where $a$ and $b$ differ, the sequence $a$ has a smaller element than the corresponding element in $b$.

-----Input-----

The first line contains a single integer $t$ ($1 \le t \le 10^5$) — the number of test cases.

Each of the next $t$ lines contains a single integer $n$ ($1\le n \le 10^{16}$) — the position of the element you want to know.

-----Output-----

In each of the $t$ lines, output the answer to the corresponding test case.

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

Output
1
2
3
4
8
12
5
10
15

-----Note-----

The first elements of $s$ are $1, 2, 3, 4, 8, 12, 5, 10, 15, \dots $


Solve in Python:
Consider the infinite x$x$ axis. There are N$N$ impacts on this X-axis at integral points (X1$X_1$,X2$X_2$,....XN$X_N$)  (all distinct) . An impact at a point X$X$i propagates such that at a point X$X$0, the effect of the impact is K|Xi−X0|$K^{|X_i - X_0|}$. Given the point X0$X_0$, N$N$ and K$K$. Assume the total impact on X0$X_0$ is M$M$, find if it is possible to do so.Note: You are not required to find the set X

Formally print "yes" if this is possible and "no" if not possible.

-----Input:-----
- First line will contain T$T$, number of testcases. Then the testcases follow.
-  Each testcase contains of a single line of input, four integers N$N$,K$K$,M$M$,X$X$0

-----Output:-----
-  The output of each test case is either "yes" or "no"

-----Constraints -----
-  1≤T≤1000$1\leq T \leq 1000$
-  1≤N≤100$1\leq N \leq 100$
-  1≤K≤1000$1\leq K \leq 1000$
-  1≤M≤1018$1\leq M \leq 10^{18}$
-  −109≤X0≤109$-10^9 \leq X_0 \leq 10^9$

-----Sample Input:-----
	2

4 3 10 10

2 3 10 10

-----Sample Output:-----
	no

yes

T = int(input())
for i in range(T):
    l = list(map(int, input().split()))
    n, k, m, x = l[0], l[1], l[2], l[3]
    if k == 1:
        if n == m:
            print("yes")
        else:
            print("no")
    elif m % k > 1:
        print("no")
    elif k == 2:
        stack = []
        var = 0
        while m != 0:
            var += m % k
            stack.append(m % k)
            m //= k
        if var > n:
            print("no")
        elif var == n:
            print("yes")
        else:
            for p in range(1000):
                for q in range(2, len(stack)):
                    if stack[q - 1] == 0 and stack[q] >= 1:
                        stack[q-1] = 2
                        stack[q] -= 1
                        var += 1
                        if var == n:
                            print("yes")
            if var < n:
                print("no")
    else:
        temp = 0
        rog = 1
        while m != 0:
            if m % k > 2:
                rog = 0
                print("no")
            temp += m % k
            m //= k
        if rog:
            if temp == n:
                print("yes")
            else:
                print("no")


Solve in Python:
Consider the number `1176` and its square (`1176 * 1176) = 1382976`. Notice that:

* the first two digits of `1176` form a prime.
* the first two digits of the square `1382976` also form a prime.
* the last two digits of `1176` and `1382976` are the same.

Given two numbers representing a range (`a, b`), how many numbers satisfy this property within that range? (`a <= n < b`)

## Example

`solve(2, 1200) = 1`, because only `1176` satisfies this property within the range `2 <= n < 1200`. See test cases for more examples. The upper bound for the range will not exceed `1,000,000`.

Good luck!

If you like this Kata, please try:

[Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3)

[Alphabet symmetry](https://www.codewars.com/kata/59d9ff9f7905dfeed50000b0)

[Upside down numbers](https://www.codewars.com/kata/59f7597716049833200001eb)


Solve in Python:
Consider the number triangle below, in which each number is equal to the number above plus the number to the left. If there is no number above, assume it's a `0`.

The triangle has `5` rows and the sum of the last row is `sum([1,4,9,14,14]) = 42`.

You will be given an integer `n` and your task will be to return the sum of the last row of a triangle of `n` rows.

In the example above:
More examples in test cases. Good luck!

```if:javascript
### Note

This kata uses native arbitrary precision integer numbers ( `BigInt`, `1n` ).
Unfortunately, the testing framework and even native `JSON` do not fully support them yet.
`console.log(1n)` and `(1n).toString()` work and can be used for debugging.

We apologise for the inconvenience.
```

from math import factorial
def solve(n):
    return factorial(2*n)//(factorial(n)*factorial(n+1))


Solve in Python:
Consider the numbers `6969` and `9116`. When you rotate them `180 degrees` (upside down), these numbers remain the same. To clarify, if we write them down on a paper and turn the paper upside down, the numbers will be the same. Try it and see! Some numbers such as `2` or `5` don't yield numbers when rotated.

Given a range, return the count of upside down numbers within that range.  For example, `solve(0,10) = 3`, because there are only `3` upside down numbers `>= 0 and < 10`. They are `0, 1, 8`.

More examples in the test cases.

Good luck!

If you like this Kata, please try

[Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3)

[Life without primes](https://www.codewars.com/kata/59f8750ac374cba8f0000033)

Please also try the performance version of this kata at [Upside down numbers - Challenge Edition ](https://www.codewars.com/kata/59f98052120be4abfa000304)

def solve(a, b):
    count = 0
    for num in range(a, b):
        num = str(num)
        if num == num.translate(str.maketrans('1234567890', '1xxxx9x860'))[::-1]:
            count += 1
    return count


Solve in Python:
Consider the prime number `23`. If we sum the square of its digits we get:
`2^2 + 3^2 = 13`, then for `13: 1^2 + 3^2 = 10`, and finally for `10: 1^2 + 0^2 = 1`.

Similarly, if we start with prime number `7`, the sequence is: `7->49->97->130->10->1`.

Given a range, how many primes within that range will eventually end up being `1`?

The upperbound for the range is `50,000`. A range of `(2,25)` means that: `2 <= n < 25`.

Good luck!

If you like this Kata, please try:

[Prime reversion](https://www.codewars.com/kata/59b46276afcda204ed000094)

[Domainant primes](https://www.codewars.com/kata/59ce11ea9f0cbc8a390000ed)

def isprime(n):
    if n<2: return False
    for i in range(2,int(n**0.5)+1):
        if n%i==0:
            return False
    return True

def solve(a,b):
    count = 0
    for i in range(a,b):
        if isprime(i):
            c = 0
            while i!=1 and c!= 10:
                i = sum(int(j)**2 for j in list(str(i)))
                c += 1
            if i==1:
                count += 1
    return count


Solve in Python:
Consider the range `0` to `10`. The primes in this range are: `2, 3, 5, 7`, and thus the prime pairs are: `(2,2), (2,3), (2,5), (2,7), (3,3), (3,5), (3,7),(5,5), (5,7), (7,7)`.

Let's take one pair `(2,7)` as an example and get the product, then sum the digits of the result as follows:  `2 * 7 = 14`, and `1 + 4 = 5`. We see that `5` is a prime number. Similarly, for the pair `(7,7)`, we get: `7 * 7 = 49`, and `4 + 9 = 13`, which is a prime number.

You will be given a range and your task is to return the number of pairs that revert to prime as shown above. In the range `(0,10)`, there are only `4` prime pairs that end up being primes in a similar way: `(2,7), (3,7), (5,5), (7,7)`. Therefore, `solve(0,10) = 4)`

Note that the upperbound of the range will not exceed `10000`. A range of `(0,10)` means that: `0 <= n < 10`.

Good luck!

If you like this Kata, please try

[Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3)

[Prime reduction](https://www.codewars.com/kata/59aa6567485a4d03ff0000ca)

[Dominant primes](https://www.codewars.com/kata/59ce11ea9f0cbc8a390000ed)

from itertools import compress, combinations_with_replacement
import numpy as np

s = np.ones(10001)
s[:2] = s[4::2] = 0
for i in range(3, int(len(s)**0.5)+1, 2):
    if s[i]:
        s[i*i::i] = 0
PRIMES = list(compress(list(range(len(s))), s))

def solve(a, b):
    i, j = np.searchsorted(PRIMES, a), np.searchsorted(PRIMES, b)
    return sum(s[sum(map(int, str(x * y)))] for x, y in combinations_with_replacement(PRIMES[i:j], 2))


Solve in Python:
Consider the sequence `S(n, z) = (1 - z)(z + z**2 + z**3 + ... + z**n)` where `z` is a complex number
 and `n` a positive integer (n > 0).

When `n` goes to infinity and `z` has a correct value (ie `z` is in its domain of convergence `D`), `S(n, z)` goes to a finite limit
 `lim` depending on `z`.

Experiment with `S(n, z)` to guess the domain of convergence `D`of `S` and `lim` value when `z` is in `D`.

 Then determine the smallest integer `n` such that `abs(S(n, z) - lim) < eps`
 where `eps` is a given small real number and `abs(Z)` is the modulus or norm of the complex number Z.

 Call `f` the function `f(z, eps)` which returns `n`.
 If `z` is such that `S(n, z)` has no finite limit (when `z` is outside of `D`) `f` will return -1.

# Examples:
I is a complex number such as I * I = -1 (sometimes written `i` or `j`).

 `f(0.3 + 0.5 * I, 1e-4) returns 17`

 `f(30 + 5 * I, 1e-4) returns -1`

# Remark:
For languages that don't have complex numbers or "easy" complex numbers, a complex number `z` is represented by two real numbers `x` (real part) and `y` (imaginary part).

`f(0.3, 0.5, 1e-4) returns 17`

 `f(30, 5, 1e-4) returns -1`
# Note:
You pass the tests if `abs(actual - exoected) <= 1`

import math
def f(z, eps):
    tmp = math.log(eps, abs(z))
    return math.trunc(tmp) if tmp>0 else -1


Solve in Python:
Consider the sequence `a(1) = 7, a(n) = a(n-1) + gcd(n, a(n-1)) for n >= 2`:

`7, 8, 9, 10, 15, 18, 19, 20, 21, 22, 33, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 69, 72, 73...`.

Let us take the differences between successive elements of the sequence and
get a second sequence `g: 1, 1, 1, 5, 3, 1, 1, 1, 1, 11, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 23, 3, 1...`.

For the sake of uniformity of the lengths of sequences **we add** a `1` at the head of g:

`g: 1, 1, 1, 1, 5, 3, 1, 1, 1, 1, 11, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 23, 3, 1...`

Removing the 1s gives a third sequence:
`p: 5, 3, 11, 3, 23, 3...`
where you can see prime numbers.

#Task:
Write functions:
```
1: an(n) with parameter n: returns the first n terms of the series a(n) (not tested)

2: gn(n) with parameter n: returns the first n terms of the series g(n) (not tested)

3: countOnes(n) with parameter n: returns the number of 1 in g(n)
    (don't forget to add a `1` at the head) # (tested)

4: p(n) with parameter n: returns an array of n unique prime numbers (not tested)

5: maxp(n) with parameter n: returns the biggest prime number of the sequence pn(n) # (tested)

6: anOver(n) with parameter n: returns an array (n terms) of the a(i)/i for every i such g(i) != 1 (not tested but interesting result)

7: anOverAverage(n) with parameter n: returns as an *integer* the average of anOver(n)  (tested)
```

#Note:
You can write directly functions `3:`, `5:` and `7:`. There is no need to write functions `1:`, `2:`, `4:` `6:`
except out of pure curiosity.

from math import gcd

a, res1, res2, memo = 6, [0], [1], {1}
for i in range(1, 1000000):
    x = a + gcd(i, a)
    a, g = x, x-a
    res1.append(res1[-1] + (g == 1))
    if g not in memo:
        res2.append(max(res2[-1], g))
        memo.add(g)

count_ones = res1.__getitem__
max_pn     = res2.__getitem__
an_over_average = lambda _: 3


Solve in Python:
Consider the string `"1 2 36 4 8"`. Lets take pairs of these numbers, concatenate each pair and determine how many of them of divisible by `k`.

```Pearl
If k = 3, we get following numbers ['12', '18', '21', '24', '42', '48', '81', '84'], all divisible by 3.
Note:
-- 21 and 12 are different pairs.
-- Elements must be from different indices, so '3636` is not a valid.
```

Given a string of numbers and an integer `k`, return the number of pairs that when concatenated, are divisible by `k`.

```
solve("1 2 36 4 8", 3) = 8, because they are ['12', '18', '21', '24', '42', '48', '81', '84']
solve("1 3 6 3", 3) = 6. They are ['36', '33', '63', '63', '33', '36']
```

More examples in test cases. Good luck!

Please also try [Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7)

from itertools import permutations

def solve(s,k):
    return sum(not v%k for v in map(int, map(''.join, permutations(s.split(),2))))


Solve in Python:
Consider the string `"adfa"` and the following rules:
```Pearl
a) each character MUST be changed either to the one before or the one after in alphabet.
b) "a" can only be changed to "b" and "z" to "y".
```
From our string, we get:
```Pearl
"adfa" -> ["begb","beeb","bcgb","bceb"]
Another example: "bd" -> ["ae","ac","ce","cc"]
--We see that in each example, one of the possibilities is a palindrome.
```
I was working on the code for this but I couldn't quite figure it out. So far I have:

```python
def solve(st):
    return [all(ord(x) - ord(y) in ["FIX"] for x, y in zip(st, st[::-1]))][0]
```
I'm not sure what three numbers go into the array labelled `["FIX"]`. This is the only thing missing.

You will be given a lowercase string and your task is to return `True` if at least one of the possiblities is a palindrome or `False` otherwise. You can use your own code or fix mine.

More examples in test cases. Good luck!

def solve(st):
    print(st)
    return all(ord(x) - ord(y) in [-2,0,2] for x, y in zip(st, st[::-1]))


Solve in Python:
Consider the string s to be the infinite wraparound string of "abcdefghijklmnopqrstuvwxyz", so s will look like this: "...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....".

Now we have another string p. Your job is to find out how many unique non-empty substrings of p are present in s. In particular, your input is the string p and you need to output the number of different non-empty substrings of p in the string s.

Note: p consists of only lowercase English letters and the size of p might be over 10000.

Example 1:

Input: "a"
Output: 1

Explanation: Only the substring "a" of string "a" is in the string s.

Example 2:

Input: "cac"
Output: 2
Explanation: There are two substrings "a", "c" of string "cac" in the string s.

Example 3:

Input: "zab"
Output: 6
Explanation: There are six substrings "z", "a", "b", "za", "ab", "zab" of string "zab" in the string s.

class Solution:
     def findSubstringInWraproundString(self, p):
         """
         :type p: str
         :rtype: int
         """
         pc = None
         sl = 0
         ll = {}

         for c in p:
             if pc and (ord(pc) + 1 == ord(c) or (pc == 'z' and c == 'a')):
                 sl += 1
             else:
                 sl = 1
             ll[c] = max([ll[c], sl]) if c in ll else sl
             pc = c
         s = 0
         for key, value in list(ll.items()):
             s += value
         return s

 # def unique(p):
 #   pc = None
 #   sl = 0
 #   ll = {}
 #   for c in p:
 #     if pc != None and (ord(pc) + 1 == ord(c) or (pc == 'z' and c == 'a')):
 #       sl += 1
 #     else:
 #       sl = 1
 #     ll[c] = max([ll[c], sl]) if c in ll else sl
 #     pc = c
 #   s = 0
 #   for _, v in ll.items():
 #       s += v
 #   return s

 # with open('/dev/stdin', 'rt') as f:
 #   line = f.readline()
 #   while line:
 #     print unique(line.rstrip())
 #     line = f.readline()


Solve in Python:
Consider the word `"abode"`. We can see that the letter `a` is in position `1` and `b` is in position `2`. In the alphabet, `a` and `b` are also in positions `1` and `2`. Notice also that `d` and `e` in `abode` occupy the positions they would occupy in the alphabet, which are positions `4` and `5`.

Given an array of words, return an array of the number of letters that occupy their positions in the alphabet for each word. For example,
```
solve(["abode","ABc","xyzD"]) = [4, 3, 1]
```
See test cases for more examples.

Input will consist of alphabet characters, both uppercase and lowercase. No spaces.

Good luck!

If you like this Kata, please try:

[Last digit symmetry](https://www.codewars.com/kata/59a9466f589d2af4c50001d8)

[Alternate capitalization](https://www.codewars.com/kata/59cfc000aeb2844d16000075)

~~~if:fortran
## Fortran-Specific Notes

Due to how strings and arrays work in Fortran, some of the strings in the input array will inevitably contain trailing whitespace.  **For this reason, please [trim](https://gcc.gnu.org/onlinedocs/gcc-4.3.4/gfortran/TRIM.html) your input strings before processing them.**
~~~

import string
def solve(arr):
    return list([sum([1 for i in range(len(x)) if i<26 and x[i].lower() == string.ascii_lowercase[i]]) for x in arr])


Solve in Python:
Construct a function 'coordinates', that will return the distance between two points on a cartesian plane, given the x and y coordinates of each point.

There are two parameters in the function, ```p1``` and ```p2```. ```p1``` is a list ```[x1,y1]``` where ```x1``` and ```y1``` are the x and y coordinates of the first point. ```p2``` is a list ```[x2,y2]``` where ```x2``` and ```y2``` are the x and y coordinates of the second point.

The distance between the two points should be rounded to the `precision` decimal if provided, otherwise to the nearest integer.

import math

def coordinates(p1, p2, precision=0):
    return round(math.hypot(p1[0] - p2[0], p1[1] - p2[1]), precision)


Solve in Python:
Construct a function that, when given a string containing an expression in infix notation, will return an identical expression in postfix notation.

The operators used will be `+`, `-`, `*`, `/`, and `^` with standard precedence rules and left-associativity of all operators but `^`.

The operands will be single-digit integers between 0 and 9, inclusive.

Parentheses may be included in the input, and are guaranteed to be in correct pairs.

```javascript
toPostfix("2+7*5"); // Should return "275*+"
toPostfix("3*3/(7+1)"); // Should return "33*71+/"
toPostfix("5+(6-2)*9+3^(7-1)"); // Should return "562-9*+371-^+"
```
```python
to_postfix("2+7*5") # Should return "275*+"
to_postfix("3*3/(7+1)") # Should return "33*71+/"
to_postfix("5+(6-2)*9+3^(7-1)") # Should return "562-9*+371-^+"
```

You may read more about postfix notation, also called Reverse Polish notation, here:
http://en.wikipedia.org/wiki/Reverse_Polish_notation

#Infix to Postfix Converter: Implements Dijkstra's Shunting-yard algorithm

#simple stack class to be used by the conversion from infix to postfix
class Stack(object):
    def __init__(self):
        self.stack = []

    def getStack(self):
        return ''.join(self.stack)

    def peek(self):
        try:
            return self.stack[0]
        except IndexError as e:
            raise ValueError(e)

    def isEmpty(self):
        return len(self.stack)==0

    def pop(self):
        try:
            return self.stack.pop(0)
        except IndexError as e:
            raise ValueError(e)

    def push(self, v):
        self.stack.insert(0, v)
#end stack class

#Implements the Shunting-yard algorithm
class Ifix2PfixConverter():
    __EXP_OP = '^'
    __MUL_OP = '*'
    __DIV_OP = '/'
    __ADD_OP = '+'
    __SUB_OP = '-'
    __L_PAREN = '('
    __R_PAREN = ')'

    __precidenceTable = { __EXP_OP : 4,
                          __MUL_OP : 3, __DIV_OP : 3,
                          __ADD_OP : 2, __SUB_OP : 2 }

    __associativityTable  = { __EXP_OP : 'right',
                              __MUL_OP : 'left', __DIV_OP : 'left',
                              __ADD_OP : 'left', __SUB_OP : 'left' }

    def __init__(self, eqn):
        self.infixEqn = eqn
        self.postfixEqn = []
        self.stack = Stack()
        self.convertToPostfix()

    def isLeftAssociative(self, k):
        return 'left' == self.__associativityTable[k]

    def getPostfixEquation(self):
        return ''.join(self.postfixEqn)

    def isOperator(self, k):
        return  (k in self.__precidenceTable)

    def precidence(self,k):
        return self.__precidenceTable[k]

    def isOperand(self, k):
        return k.isalnum()

    def isLeftParen(self,k):
        return k==self.__L_PAREN

    def isRightParen(self,k):
        return k==self.__R_PAREN

    #Implementation of Dijkstra's Shunting-yard algorithm
    def convertToPostfix(self):

        for c in self.infixEqn:
            if self.isOperand(c):
              ...


Solve in Python:
Convert DD (decimal degrees) position to DMS (degrees, minutes, seconds).

##### Inputs:
`dd_lat` and `dd_lon` 2 strings representing the latitude and the longitude in degree -i.e. 2 floats included in [-90, 90] and [-180, 180]. Note that latitude 0 is north, longitude 0 is east.

##### Outputs:
A tuple of DMS latitudes formated as follows:
`DDD*mm'ss.sss"C`

With:
- `DDD`: degrees
- `mm`: minutes
- `ss.sss`: seconds rounded to 3 decimals
- `C`: first letter uppercase of the cardinal direction

##### ressources
about WGS 84 on [Wikipedia](https://en.wikipedia.org/wiki/World_Geodetic_System#WGS84)

def convert_to_dms(dd_lat, dd_lon):
    def convert(dd, c):
        d = abs(dd)
        m = d % 1 * 60
        s = m % 1 * 60
        return '{:03}*{:02}\'{:06.3f}"{}'.format(int(d), int(m), s, c[dd >= 0])
    return convert(float(dd_lat), 'SN'), convert(float(dd_lon), 'WE')


Solve in Python:
Convert a hash into an array. Nothing more, Nothing less.

```
{name: 'Jeremy', age: 24, role: 'Software Engineer'}
```
should be converted into

```
[["name", "Jeremy"], ["age", 24], ["role", "Software Engineer"]]
```

```if:python,javascript,crystal
**Note**: The output array should be sorted alphabetically.
```

Good Luck!

def convert_hash_to_array(d):
    return [ [k,v] for k,v in sorted(d.items()) ]


Solve in Python:
Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.

Example 1:

Input: 123
Output: "One Hundred Twenty Three"

Example 2:

Input: 12345
Output: "Twelve Thousand Three Hundred Forty Five"

Example 3:

Input: 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

Example 4:

Input: 1234567891
Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"

class Solution:

     digit = {
         0: '',
         1: 'One',
         2: 'Two',
         3: 'Three',
         4: 'Four',
         5: 'Five',
         6: 'Six',
         7: 'Seven',
         8: 'Eight',
         9: 'Nine'
         }

     teen = {
         10: 'Ten',
         11: 'Eleven',
         12: 'Twelve',
         13: 'Thirteen',
         14: 'Fourteen',
         15: 'Fifteen',
         16: 'Sixteen',
         17: 'Seventeen',
         18: 'Eighteen',
         19: 'Nineteen'
     }

     ten = {
         2: 'Twenty',
         3: 'Thirty',
         4: 'Forty',
         5: 'Fifty',
         6: 'Sixty',
         7: 'Seventy',
         8: 'Eighty',
         9: 'Ninety'
     }

     idx = {
         0: '',
         1: 'Thousand',
         2: 'Million',
         3: 'Billion',
         4: 'Trillion',
         5: 'Quadrillion'
     }
     def helper(self,num):
         result = ""
         while len(num) < 3:
             num = '0' + num

         if num[0] is not '0':
             result = self.digit[int(num[0])] + ' Hundred'
         if num[1] is not '0':
             if num[1] == '1':
                 return result + " " + self.teen[int(num[1]+num[2])]
             else:
                 return result + " " + self.ten[int(num[1])] + " " + self.digit[int(num[2])]
         if num[2] is not '0':
             result = result + " " + self.digit[int(num[2])]
         return result

     def numberToWords(self, num):
         """
         :type num: int
         :rtype: str
         """
         if num == 0:
             return 'Zero'
         result = ""
         rev = str(num)[::-1]
         slices = [rev[i:i+3] for i in range(0,len(str(num)),3)]

         for idx, slice in enumerate((slices)):
             if slice == '000':
                 continue
             else:
                 result = self.helper(str(slice[::-1])) + " " + self.idx[idx] + " "+ result
         result = result.split(' ')
         result = [ x for x in result if x is not ""]
        ...


Solve in Python:
Convert integers to binary as simple as that. You would be given an integer as a argument and you have to return its binary form.
To get an idea about how to convert a decimal number into a binary number, visit here.

**Notes**: negative numbers should be handled as two's complement; assume all numbers are integers stored using 4 bytes (or 32 bits) in any language.

Your output should ignore leading 0s.

So, for example:
```python
to_binary(3)=="11"
to_binary(-3)=="11111111111111111111111111111101"
```

*Be Ready for Large Numbers. Happy Coding ^_^*

def to_binary(n):
    return '{:b}'.format(n & 4294967295)


GLYPHS = " .,:;xyYX"

def quantize(value, max_value, max_quantum):
    if  value == max_value:
        return max_quantum
    return int(value//32)

def generate_lut(max_value, max_quantum):
    return[quantize(v, max_value, max_quantum) for v in range(max_value+1)]

def transform(image,lut):
    return [[lut[v] for v in row] for row in image]

def render(image, glyphs):
    return '\n'.join(''.join(glyphs[v] for v in row) for row in image)

def image2ascii(image):
    lut=generate_lut(255,len(GLYPHS)-1)
    image = transform(image, lut)

    return render(image, GLYPHS)


Solve in Python:
Converting a 24-hour time like "0830" or "2030" to a 12-hour time (like "8:30 am" or "8:30 pm") sounds easy enough, right?  Well, let's see if you can do it!

You will have to define a function named "to12hourtime", and you will be given a four digit time string (in "hhmm" format) as input.

Your task is to return a 12-hour time string in the form of "h:mm am" or "h:mm pm".  (Of course, the "h" part will be two digits if the hour is greater than 9.)

If you like this kata, try converting 12-hour time to 24-hour time:

https://www.codewars.com/kata/converting-12-hour-time-to-24-hour-time/train/python

def to12hourtime(timestring):
    print(timestring)
    hour = int(timestring[:2])
    mins = timestring[2:]
    if hour >= 12:
        noon = "pm"
        hour -= 12
    else:
        noon = "am"
    if hour == 0:
        hour = 12
    return "{}:{} {}".format(hour, mins, noon)


Solve in Python:
Converting a normal (12-hour) time like "8:30 am" or "8:30 pm" to 24-hour time (like "0830" or "2030") sounds easy enough, right?  Well, let's see if you can do it!

You will have to define a function named "to24hourtime", and you will be given an hour (always in the range of 1 to 12, inclusive), a minute (always in the range of 0 to 59, inclusive), and a period (either "am" or "pm") as input.

Your task is to return a four-digit string that encodes that time in 24-hour time.

from datetime import datetime

def to24hourtime(h, m, p):
    return datetime.strptime('%02d%02d%s' % (h, m, p.upper()), '%I%M%p').strftime('%H%M')


Solve in Python:
Correct this code so that it takes one argument, `x`, and returns "`x` is more than zero" if `x` is positive (and nonzero), and otherwise, returns "`x` is equal to or less than zero." In both cases, replace `x` with the actual value of `x`.

def corrections(x):
    return "%d is %s than zero." % (x, ["equal to or less", "more"][x > 0])


Solve in Python:
Corruption is on the rise in the country of Freedonia, Gru's home. Gru wants to end this for good and for that he needs the help of his beloved minions.
This corruption network can be represented in the form of a tree having N$N$ nodes and N−1$N-1$ edges. The nodes are numbered from 1$1$ to N$N$, and the tree is rooted at node 1$1$. These nodes represent the corrupt officials and each corrupt official works under some other corrupt official except the Boss who is represented by node 1$1$.
Gru believes in divide and conquer and thinks that this network needs to be divided into as many sub-networks as possible.
He commands the minions to kill some of the corrupt officials in order to break the network into maximum sub-networks. But as you know, these corrupt officials are very sharp, and hence these assassinations need to be done very smartly and silently, without leaving any traces.  To achieve this Gru devises a strategy, in which he designs an operation, and that operation can be applied by the minions any number of times (even 0).
In one operation the minions can select any one leaf node official [that is an official who does not have any other official beneath him] in the graph and kill him along with all his ancestors$ancestors$ officials till the root$root$ of the tree in which the operation is applied (this is done to wipe all traces of the operation). This deleted all those nodes from the graph, and also, while doing so, all the associated edges/connections$edges/connections$ of the leaf node and its ancestors are also destroyed. Hence after applying this operation on any tree, it breaks into some connected components which are also trees, which are the new sub-networks.
Now the minions are a bit lazy and will do the task someday, but they need to submit a report to Gru containing the number of the maximum$maximum$ connected$connected$ components$components$ that they could achieve by applying the operation any number of times. To do this, the minions require your help. So help the minions by finding...

from sys import stdin,stdout
input=stdin.readline
n=int(input())
a=[[] for i in range(n)]
for i in range(n-1):
    u,v=map(int,input().split())
    a[u-1].append(v-1)
    a[v-1].append(u-1)
b=[0]*n
vis=[0]*n
st=[(0,0)]
vis[0]=1
pa=[0]*n
while st:
    x,y=st.pop()
    b[x]=y
    for i in a[x]:
        if vis[i]==0:
            pa[i]=x
            vis[i]=1
            if x==0:
                st.append((i,y+len(a[x])-1))
            else:
                st.append((i,y+len(a[x])-2))
c=[]
for i in range(1,n):
    if len(a[i])==1:
        c.append((b[i],i))
c.sort()
ans=0
while c:
    x,y=c.pop()
    m=y
    p=0
    while y!=0 and pa[y]!=-1:
        y=pa[y]
        if pa[y]==-1:
            break
        if y!=0:
            p+=(len(a[y])-2)
        else:
            p+=(len(a[y])-1)
    if p>=1:
        p=0
        while m!=0 and pa[m]!=-1:
            x=m
            if pa[m]==-1:
                break
            m=pa[m]
            pa[x]=-1
            if m!=0:
                p+=(len(a[m])-2)
            else:
                p+=(len(a[m])-1)
        if y==0:
            pa[0]=-1
for i in range(n):
    if pa[i]!=-1:
        st=[i]
        pa[i]=-1
        while st:
            x=st.pop()
            for j in a[x]:
                if pa[j]!=-1:
                    pa[j]=-1
                    st.append(j)
        ans+=1
print(ans)


Solve in Python:
Count how often sign changes in array.

### result
number from `0` to ... . Empty array returns `0`

### example

def catch_sign_change(lst):
    count = 0
    countNumber = 0
    i=0
    for n in lst:
        if countNumber >= 0 and n < 0 and i != 0:
            count = count+1
        elif countNumber < 0 and n >= 0 and i != 0:
            count = count+1
        countNumber = n
        i = i+1
    return count


Solve in Python:
Count the number of divisors of a positive integer `n`.

Random tests go up to `n = 500000`.

## Examples
```python
divisors(4)  == 3  # 1, 2, 4
divisors(5)  == 2  # 1, 5
divisors(12) == 6  # 1, 2, 3, 4, 6, 12
divisors(30) == 8  # 1, 2, 3, 5, 6, 10, 15, 30
```

def divisors(n):
    temp = []
    for i in range(1, 600000):
        if n % i == 0:
            temp.append(i)
    return len(temp)


Solve in Python:
Count the number of prime numbers less than a non-negative number, n.

Example:

Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.

class Solution:
     def countPrimes(self, x):
         x = max(0, x - 1)
         if type(x) is not int: x = int(x)
         if x < 6: return [0, 0, 1, 2, 2, 3][x]

         def Phi(m, b):
             if not b:
                 return m
             if not m:
                 return 0
             if m >= 800:
                 return Phi(m, b - 1) - Phi(m // primes[b - 1], b - 1)
             t = b * 800 + m
             if not Phi_memo[t]:
                 Phi_memo[t] = Phi(m, b - 1) - Phi(m // primes[b - 1], b - 1)
             return Phi_memo[t]

         root2 = int(x**(1. / 2))
         root3 = int(x**(1. / 3))
         top = x // root3 + 1
         sieve = [0, 0] + [1] * (top - 2)
         pi = [0, 0]
         primes = []
         t = 0
         for i in range(2, top):
             if sieve[i] == 1:
                 t += 1
                 primes.append(i)
                 sieve[i::i] = [0] * len(sieve[i::i])
             pi.append(t)
         a, b = pi[root3 + 1], pi[root2 + 1]
         Phi_memo = [0] * ((a + 1) * 800)
         return Phi(x, a) + a - 1 - sum(pi[x // p] - pi[p] + 1 for p in primes[a:b])


Solve in Python:
Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.

Please note that the string does not contain any non-printable characters.

Example:

Input: "Hello, my name is John"
Output: 5

class Solution:
     def countSegments(self, s):
         """
         :type s: str
         :rtype: int
         """
         if len(s)==0:
             return 0
         seen_character = False
         count = 0
         for char in s:
             if seen_character and char == ' ':
                 count += 1
                 seen_character = False
             elif seen_character == False and char != " ":
                 seen_character = True
         if seen_character:
             count += 1
         return count


Solve in Python:
Create a __moreZeros__ function which will __receive a string__ for input, and __return an array__ (or null terminated string in C) containing only the characters from that string whose __binary representation of its ASCII value__ consists of _more zeros than ones_.

You should __remove any duplicate characters__, keeping the __first occurence__ of any such duplicates, so they are in the __same order__ in the final array as they first appeared in the input string.

Examples

All input will be valid strings of length > 0. Leading zeros in binary should not be counted.

def more_zeros(s):

    al = []

    for char in s:
        bn = bin(ord(char))[2:]
        lbn = len(bn)

        if bn.count('0') > lbn/2 and char not in al:
            al.append(char)

    return al


Solve in Python:
Create a `Vector` class with `x` and a `y` attributes that represent component magnitudes in the x and y directions.

Your vectors should handle vector additon with an `.add()` method that takes a second vector as an argument and returns a new vector equal to the sum of the vector you call `.add()` on and the vector you pass in.

For example:

```python
>>> a = Vector(3, 4)
>>> a.x
3
>>> a.y
4
>>> b = Vector(1, 2)
>>> c = a.add(b)
>>> c.x
4
>>> c.y
6
```

Adding vectors when you have their components is easy: just add the two x components together and the two y components together to get the x and y components for the vector sum.

class Vector(object):
    def __init__(self, x, y): self._x, self._y = x, y
    @property
    def x(self):              return self._x
    @property
    def y(self):              return self._y
    def add(self, b):         return Vector(self._x+b.x, self._y+b.y)


Solve in Python:
Create a class Vector that has simple (3D) vector operators.

In your class, you should support the following operations, given Vector ```a``` and Vector ```b```:

```python
a + b # returns a new Vector that is the resultant of adding them
a - b # same, but with subtraction
a == b # returns true if they have the same magnitude and direction
a.cross(b) # returns a new Vector that is the cross product of a and b
a.dot(b) # returns a number that is the dot product of a and b
a.to_tuple() # returns a tuple representation of the vector.
str(a) # returns a string representation of the vector in the form ""
a.magnitude # returns a number that is the magnitude (geometric length) of vector a.
a.x # gets x component
a.y # gets y component
a.z # gets z component
Vector([a,b,c]) # creates a new Vector from the supplied 3D array.
Vector(a,b,c) # same as above
```
The test cases will not mutate the produced Vector objects, so don't worry about that.

class Vector:
    def __init__(s,*A):
        s.x,s.y,s.z=len(A)!=1 and A or A[0]
        s.magnitude=(s.x**2+s.y**2+s.z**2)**.5
    __str__=lambda s:"<%d, %d, %d>"%(s.x,s.y,s.z)
    __eq__=lambda s,o:(s.x,s.y,s.z)==(o.x,o.y,o.z)
    __add__=lambda s,o:Vector([s.x+o.x,s.y+o.y,s.z+o.z])
    __sub__=lambda s,o:Vector([s.x-o.x,s.y-o.y,s.z-o.z])
    to_tuple=lambda s:(s.x,s.y,s.z)
    dot=lambda s,o:s.x*o.x+s.y*o.y+s.z*o.z
    cross=lambda s,o:Vector(s.y*o.z-s.z*o.y,s.z*o.x-s.x*o.z,s.x*o.y-s.y*o.x)


Solve in Python:
Create a combat function that takes the player's current health and the amount of damage recieved, and returns the player's new health.
Health can't be less than 0.

def combat(health, damage):
    health -= damage
    if health <= 0:
        return 0
    else:
        return health


Solve in Python:
Create a function

```python
has_two_cube_sums(n)
```

which checks if a given number `n` can be written as the sum of two cubes in two different ways: `n = a³+b³ = c³+d³`.
All the numbers `a`, `b`, `c` and `d` should be different and greater than `0`.

E.g. 1729 = 9³+10³ = 1³+12³.

```python
has_two_cube_sums(1729); // true
has_two_cube_sums(42);   // false
```

from itertools import combinations

s = {a**3 + b**3 for a, b in combinations(range(1, 1000), 2)}
s.discard(19**3 + 34**3)  # bug

def has_two_cube_sums(n):
    return n in s


Solve in Python:
Create a function ```sel_number()```, that will select numbers that fulfill the following constraints:

1) The numbers should have 2 digits at least.

2) They should have their respective digits in increasing order from left to right.
Examples: 789, 479, 12678, have these feature. But 617, 89927 are not of this type.
In general, if ```d1, d2, d3....``` are the digits of a certain number ```i```
Example:
```( i = d1d2d3d4d5) so, d1 < d2 < d3 < d4 < d5```

3) They cannot have digits that occurs twice or more. Example: 8991 should be discarded.

4) The difference between neighbouring pairs of digits cannot exceed certain value.
Example: If the difference between contiguous digits cannot excced 2, so 1345, 23568 and 234578 pass this test. Other numbers like 1456, 389, 157 don't belong to that group because in the first number(1456), the difference between second and first digit 4 - 1 > 2; in the next one(389), we have 8 - 3 > 2; and see by yourself why 157 should be discarded.
In general, taking the example above of ```i = d1d2d3d4d5```:
```
d2 - d1 <= d;

d3 - d2 <= d;

d4 - d3 <= d;

d5 - d4 <= d;
```
The function should accept two arguments n and d; n is the upper limit of the range to work with(all the numbers should be less or equal than n), and d is maximum difference  between every pair of its contiguous digits. It's clear that 1 <= d <= 8.

Here we have some cases:
```
sel_number(0,1) = 0 # n = 0, empty range
sel_number(3, 1) = 0 # n = 3, numbers should be higher or equal than 12
sel_number(13, 1) = 1 # only 12 fulfill the requirements
sel_number(20, 2) = 2 # 12 and 13 are the numbers
sel_number(30, 2) = 4 # 12, 13, 23 and 24 are the selected ones
sel_number(44, 2) = 6 # 12, 13, 23, 24, 34 and 35 are valid ones
sel_number(50, 3) = 12 # 12, 13, 14, 23, 24, 25, 34, 35, 36, 45, 46 and 47 are valid
```
Compare the last example with this one:
```
sel_number(47, 3) = 12 # 12, 13, 14, 23, 24, 25, 34, 35, 36, 45, 46 and 47 are valid
```
(because the instructions says the value of may be included if it...

def sel_number(n, d):
    # Longer, broken-up version
    iterator_count = lambda it: sum(1 for _ in it)
    check_constraints_1_and_3 = lambda a: len(set(a)) == len(a) > 1
    check_constraints_2_and_4 = lambda a: all(int(y) - int(x) <= d and y > x for x, y in zip(a[:-1], a[1:]))
    numbers_iterator = map(str, xrange(n + 1))

    numbers_iterator = filter(check_constraints_1_and_3, numbers_iterator)
    numbers_iterator = filter(check_constraints_2_and_4, numbers_iterator)
    return iterator_count(numbers_iterator)


Solve in Python:
Create a function `close_compare` that accepts 3 parameters: `a`, `b`, and an optional `margin`. The function should return whether `a` is lower than, close to, or higher than `b`. `a` is "close to" `b` if `margin` is higher than or equal to the difference between `a` and `b`.

When `a` is lower than `b`, return `-1`.

When `a` is higher than `b`, return `1`.

When `a` is close to `b`, return `0`.

If `margin` is not given, treat it as zero.

Example: if `a = 3`, `b = 5` and the `margin = 3`, since `a` and `b` are no more than 3 apart, `close_compare` should return `0`. Otherwise, if instead `margin = 0`, `a` is lower than `b` and `close_compare` should return `-1`.

Assume: `margin >= 0`

Tip: Some languages have a way to make arguments optional.

def close_compare(a, b, margin = 0):
    if a < b and a + margin < b: return -1
    if b < a and b + margin < a: return 1
    return 0


Solve in Python:
Create a function `isAlt()` that accepts a string as an argument and validates whether the vowels (a, e, i, o, u) and consonants are in alternate order.

```python
is_alt("amazon")
// true
is_alt("apple")
// false
is_alt("banana")
// true
```

Arguments consist of only lowercase letters.

import re
def is_alt(s):
    return bool(re.search(r'^([aeiou][^aeiou])*[aeiou]?$|^([^aeiou][aeiou])*[^aeiou]?$',s))


Solve in Python:
Create a function `longer` that accepts a string and sorts the words in it based on their respective lengths in an ascending order. If there are two words of the same lengths, sort them alphabetically. Look at the examples below for more details.

```python
longer("Another Green World") => Green World Another
longer("Darkness on the edge of Town") => of on the Town edge Darkness
longer("Have you ever Seen the Rain") => the you Have Rain Seen ever
```

Assume that only only Alphabets will be entered as the input.
Uppercase characters have priority over lowercase characters. That is,
```python
longer("hello Hello") => Hello hello
```

Don't forget to rate this kata and leave your feedback!!
Thanks

# Why not both? :)

def longer(s):
    return " ".join(sorted(list(s.split()), key=lambda x: (len(x), x)))

longer = lambda s: " ".join(sorted(list(s.split()), key=lambda x: (len(x), x)))


Solve in Python:
Create a function `sierpinski` to generate an ASCII representation of a Sierpinski triangle of order **N**.

Seperate each line with `\n`. You don't have to check the input value.

The output should look like this:

     sierpinski(4)
                   *
                  * *
                 *   *
                * * * *
               *       *
              * *     * *
             *   *   *   *
            * * * * * * * *
           *               *
          * *             * *
         *   *           *   *
        * * * *         * * * *
       *       *       *       *
      * *     * *     * *     * *
     *   *   *   *   *   *   *   *
    * * * * * * * * * * * * * * * *

def sierpinski(n):
    return '\n'.join(l.center(2**(n+1) - 1) for l in addrows(n, ['*']))

def addrows(n, t):
    for _ in range(n): t += [l.ljust(len(t[-1])) + " " + l for l in t]
    return t


Solve in Python:
Create a function finalGrade, which calculates the final grade of a student depending on two parameters: a grade for the exam and a number of completed projects.

This function should take two arguments:
exam - grade for exam (from 0 to 100);
projects - number of completed projects (from 0 and above);

This function should return a number (final grade).
There are four types of final grades:
- 100, if a grade for the exam is more than 90 or if a number of completed projects more than 10.
- 90, if a grade for the exam is more than 75 and if a number of completed projects is minimum 5.
- 75, if a grade for the exam is more than 50 and if a number of completed projects is minimum 2.
- 0, in other cases

Examples:

~~~if-not:nasm
```python
final_grade(100, 12)  # 100
final_grade(99, 0)    # 100
final_grade(10, 15)   # 100
final_grade(85, 5)    # 90
final_grade(55, 3)    # 75
final_grade(55, 0)    # 0
final_grade(20, 2)    # 0
```
~~~

*Use Comparison and Logical Operators.

def final_grade(exam, pr):
    if exam > 90 or pr > 10:
        return 100
    elif exam > 75 and pr >= 5:
        return 90
    elif exam > 50 and pr >= 2:
        return 75
    return 0


Solve in Python:
Create a function named `divisors`/`Divisors` that takes an integer `n > 1` and returns an array with all of the integer's divisors(except for 1 and the number itself), from smallest to largest. If the number is prime return the string '(integer) is prime' (`null` in C#) (use `Either String a` in Haskell and `Result, String>` in Rust).

#### Example:

```python
divisors(12); #should return [2,3,4,6]
divisors(25); #should return [5]
divisors(13); #should return "13 is prime"
```

from numpy import arange

def divisors(integer):
    # generate array of integers from 2 to integer/2 (rounded down)
    potential_divisors = arange(2, integer//2 + 1)
    # use boolean indexing to extract divisors
    divisors = potential_divisors[integer % potential_divisors == 0]
    # check divisors exist and if not return prime message
    if len(divisors):
        return list(divisors)
    else:
        return '{integer} is prime'.format(integer=integer)


Solve in Python:
Create a function taking a positive integer as its parameter and returning a string containing the Roman Numeral representation of that integer.

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

Example:
```python
solution(1000) # should return 'M'
```

Help:
```
Symbol  Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1,000
```

Remember that there can't be more than 3 identical symbols in a row.

More about roman numerals - http://en.wikipedia.org/wiki/Roman_numerals

def solution(n):
    roman_numerals = {1000:'M',
                      900: 'CM',
                      500: 'D',
                      400: 'CD',
                      100: 'C',
                      90: 'XC',
                      50: 'L',
                      40: 'XL',
                      10: 'X',
                      9: 'IX',
                      5: 'V',
                      4: 'IV',
                      1: 'I'
    }
    roman_string = ''
    for key in sorted(list(roman_numerals.keys()),reverse=True):
        while n >= key:
            roman_string += roman_numerals[key]
            n -= key
    return roman_string


Solve in Python:
Create a function that accepts 3 inputs, a string, a starting location, and a length.  The function needs to simulate the string endlessly repeating in both directions and return a substring beginning at the starting location and continues for length.

Example:
```python
endless_string('xyz', -23, 6) == 'yzxyzx'
```
To visualize:

           Negative                               Positive
    3         2         1         *         1         2         3
    0987654321098765432109876543210123456789012345678901234567890
    xyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzx
           ******
         -23 for a length of 6 == 'yzxyzx'

Some more examples:
```python
endless_string('xyz', 0, 4) == 'xyzx'
endless_string('xyz', 19, 2) == 'yz'
endless_string('xyz', -4, -4) == 'zxyz'
```

A negative length needs to include the starting postion and return the characters to the left of the starting position.

from itertools import cycle, islice

def endless_string(string, start, length):
    i = (start + (length + 1 if length < 0 else 0)) % len(string)
    return ''.join(islice(cycle(string), i, i + abs(length)))


Solve in Python:
Create a function that accepts dimensions, of Rows x Columns, as parameters in order to create a multiplication table sized according to the given dimensions.  **The return value of the function must be an array, and the numbers must be Fixnums, NOT strings.

Example:

multiplication_table(3,3)

1       2       3
2       4       6
3       6       9

-->[[1,2,3],[2,4,6],[3,6,9]]

Each value on the table should be equal to the value of multiplying the number in its first row times the number in its first column.

def multiplication_table(row,col):
    return [[(i+1)*(j+1) for i in range(col)] for j in range(row)]


Solve in Python:
Create a function that checks if a number `n` is divisible by two numbers `x` **AND** `y`. All inputs are positive, non-zero digits.

```JS
Examples:
1) n =   3, x = 1, y = 3 =>  true because   3 is divisible by 1 and 3
2) n =  12, x = 2, y = 6 =>  true because  12 is divisible by 2 and 6
3) n = 100, x = 5, y = 3 => false because 100 is not divisible by 3
4) n =  12, x = 7, y = 5 => false because  12 is neither divisible by 7 nor 5
```

def is_divisible(n,x,y):

  check = True

  if n % x == 0 and n % y == 0:

    check = True

    return check

  else:

    check = False

    return check


Solve in Python:
Create a function that differentiates a polynomial for a given value of `x`.

Your function will receive 2 arguments: a polynomial as a string, and a point to evaluate the equation as an integer.

## Assumptions:

* There will be a coefficient near each `x`, unless the coefficient equals `1` or `-1`.
* There will be an exponent near each `x`, unless the exponent equals `0` or `1`.
* All exponents will be greater or equal to zero

## Examples:

```python
differenatiate("12x+2", 3)      ==>   returns 12
differenatiate("x^2+3x+2", 3)   ==>   returns 9
```

def differentiate(equation, point):

    if equation[0] != '-': equation = '+' + equation

    equation = equation.replace('+x', '+1x').replace('-x', '-1x').replace('+', ' ').replace('-', ' -')

    terms = [[int(e) for e in (w + '^1' if '^' not in w else w).split('x^')] for w in equation.split() if 'x' in w]

    return sum(c * p * point ** (p - 1) for c, p in terms)


Solve in Python:
Create a function that finds the [integral](https://en.wikipedia.org/wiki/Integral) of the expression passed.

In order to find the integral all you need to do is add one to the `exponent` (the second argument), and divide the `coefficient` (the first argument) by that new number.

For example for `3x^2`, the integral would be `1x^3`: we added 1 to the exponent, and divided the coefficient by that new number).

Notes:
* The output should be a string.
* The coefficient and exponent is always a positive integer.

## Examples

```
 3, 2  -->  "1x^3"
12, 5  -->  "2x^6"
20, 1  -->  "10x^2"
40, 3  -->  "10x^4"
90, 2  -->  "30x^3"
```

def integrate(coefficient, exponent):
    new_exponent = exponent + 1
    new_coefficient = int(coefficient / new_exponent)

    return (str(new_coefficient) + "x^" + str(new_exponent))


Solve in Python:
Create a function that finds the largest palindromic number made from the product of **at least 2** of the given arguments.

### Notes

* Only non-negative numbers will be given in the argument
* You don't need to use all the digits of the products
* Single digit numbers are considered palindromes
* Optimization is needed: dealing with ones and zeros in a smart way will help a lot

## Examples

```
[937, 113] --> 81518
```
As `937 * 113 = 105881` and the largest palindromic number that can be arranged from the digits of result is: `81518`

Another one:

```
[57, 62, 23] --> 82128

             product     palindrome
57 * 62      = 3534   -->  353
57 * 23      = 1311   -->  131
62 * 23      = 1426   -->  6
57 * 62 * 23 = 81282  -->  82128
```

One more:
```
[15, 125, 8] --> 8

             product     palindrome
15 * 125     = 1875   -->  8
15 * 8       = 120    -->  2
125 * 8      = 1000   -->  1
15 * 125 * 8 = 15000  -->  5
```

from functools import reduce
from itertools import combinations
from collections import Counter

def max_palindrome(num):
    counter = Counter(str(num))
    one = [int(x) for x, v in list(counter.items()) if v % 2 == 1]
    if 0 < len(one):
        one = str(max(one))
    else:
        one = ""
    more = []
    for x in counter:
        while 2 <= counter[x]:
            more.append(x)
            counter[x] -= 2
    more.sort()
    if 0 < len(more) and more[-1] == '0':
        more = ""
    more = "".join(more)
    res = more[::-1] + one + more
    return int(res)

def numeric_palindrome(*args):
    palindromes = []
    one = args.count(1)
    args = [arg for arg in args if 1 < arg]
    if 0 < one:
        args.append(1)
    if 1 < one:
        args.append(1)

    for n in range(2, len(args)+1):
        comb = list(combinations(args, n))
        for c in comb:
            product = reduce(lambda a, b: a * b, c)
            palindromes.append(max_palindrome(product))
    return max(palindromes) if 0 < len(palindromes) else 0


Solve in Python:
Create a function that interprets code in the esoteric language **Poohbear**

## The Language

Poohbear is a stack-based language largely inspired by Brainfuck. It has a maximum integer value of 255, and 30,000 cells. The original intention of Poohbear was to be able to send messages that would, to most, be completely indecipherable:
Poohbear Wiki

* For the purposes of this kata, you will make a version of Poohbear that has **infinite** memory cells in **both directions** (so you do not need to limit cells to 30,000)
* Cells have a default value of 0
* Each cell can hold one byte of data.  Once a cell's value goes above 255, it wraps around to 0.  If a cell's value goes below 0, it wraps to 255.
* If the result of an operation isn't an int, round the result down to the nearest one.
* Your interpreter should ignore any non-command characters in the code.
* If you come to a `W` in the code and the current cell is equal to 0, jump to the corresponding `E`.
* If you come to an `E` in the code and the current cell is **not** 0, jump back to the corresponding `W`.

Here are the Poohbear commands:

| Command | Definition
|---| -------------------------
| + | Add 1 to the current cell
| - | Subtract 1 from the current cell
| > | Move the cell pointer 1 space to the right
| < | Move the cell pointer 1 space to the left
| c | "Copy" the current cell
| p | Paste the "copied" cell into the current cell
| W | While loop - While the current cell is not equal to 0
| E | Closing character for loops
| P | Output the current cell's value as ascii
| N | Output the current cell's value as an integer
| T | Multiply the current cell by 2
| Q | Square the current cell
| U | Square root the current cell's value
| L | Add 2 to the current cell
| I | Subtract 2 from the current cell
| V | Divide the current cell by 2
| A | Add the copied value to the current cell's value
| B | Subtract the copied value from the current cell's value
| Y | Multiply the current cell's value by the copied value
| D | Divide the current cell's value by...

def poohbear(s):
    st=[]
    loops=[]
    for i,c in enumerate(s):
        if c=='W':
            st.append(i)
        elif c=='E':
            loops.append((st.pop(),i))
    cells=[0]
    p=0
    m=0
    i=0
    output=''
    while(i<len(s)):
        c=s[i]
        if c=='+':
            cells[p]=(cells[p]+1)%256
        elif c=='-':
            cells[p]=(cells[p]-1)%256
        elif c=='>':
            p+=1
            if p==len(cells):
                cells.append(0)
        elif c=='<':
            if p==0:
                cells.insert(0,0)
            else:
                p-=1
        elif c=='c':
            m=cells[p]
        elif c=='p':
            cells[p]=m
        elif c=='W':
            if cells[p]==0:
                for w,e in loops:
                    if i==w:
                        i=e
                        break
        elif c=='E':
            if cells[p]!=0:
                for w,e in loops:
                    if i==e:
                        i=w
                        break
        elif c=='P':
            output+=chr(cells[p])
        elif c=='N':
            output+=str(cells[p])
        elif c=='T':
            cells[p]=(cells[p]*2)%256
        elif c=='Q':
            cells[p]=(cells[p]**2)%256
        elif c=='U':
            cells[p]=(int(cells[p]**0.5))%256
        elif c=='L':
            cells[p]=(cells[p]+2)%256
        elif c=='I':
            cells[p]=(cells[p]-2)%256
        elif c=='V':
            cells[p]=(cells[p]//2)%256
        elif c=='A':
            cells[p]=(cells[p]+m)%256
        elif c=='B':
            cells[p]=(cells[p]-m)%256
        elif c=='Y':
            cells[p]=(cells[p]*m)%256
        elif c=='D':
            cells[p]=(cells[p]//m)%256
        i+=1
    return output


Solve in Python:
Create a function that returns an array containing the first `l` digits from the `n`th diagonal of [Pascal's triangle](https://en.wikipedia.org/wiki/Pascal's_triangle).

`n = 0` should generate the first diagonal of the triangle (the 'ones'). The first number in each diagonal should be 1.

If `l = 0`, return an empty array. Assume that both `n` and `l` will be non-negative integers in all test cases.

def generate_diagonal(n, l):
    # return an array containing the numbers in the nth diagonal of Pascal's triangle, to the specified length
    if l == 0:
        return []
    diagonal = [1]
    for i in range(l)[1:]:
        diagonal.append(diagonal[-1] * (n + i) / i)
    return diagonal


Solve in Python:
Create a function that returns the average of an array of numbers ("scores"), rounded to the nearest whole number. You are not allowed to use any loops (including for, for/in, while, and do/while loops).

from numpy import mean
def average(array):
    return round(mean(array))


Solve in Python:
Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 positive integers. No floats or non-positive integers will be passed.

For example, when an array is passed like `[19, 5, 42, 2, 77]`, the output should be `7`.

`[10, 343445353, 3453445, 3453545353453]` should return `3453455`.

def sum_two_smallest_numbers(numbers):
    n1 = min(numbers)
    n2 = max(numbers)
    for n in numbers:
        if n1 < n < n2:
            n2 = n
    return n1 + n2


Solve in Python:
Create a function that returns the total of a meal including tip and tax. You should not tip on the tax.

You will be given the subtotal, the tax as a percentage and the tip as a percentage. Please round your result to two decimal places.

def calculate_total(subtotal, tax, tip):
    return round((1 + (tip + tax) / 100.0) * subtotal, 2)


Solve in Python:
Create a function that takes 2 positive integers in form of a string as an input, and outputs the sum (also as a string):

If either input is an empty string, consider it as zero.

from functools import reduce
def sum_str(a, b):
    if a=="" and b=="":
        return "0"
    elif a=="":
        return str(b)
    elif b=="":
        return str(a)
    else:
        return str(int(a)+int(b))


Solve in Python:
Create a function that takes a Number as its argument and returns a Chinese numeral string. You don't need to validate the input argument, it will always be a Number in the range `[-99999.999, 99999.999]`, rounded to 8 decimal places.

Simplified Chinese numerals have characters representing each number from 0 to 9 and additional numbers representing larger numbers like 10, 100, 1000, and 10000.

```
0 líng 零
1 yī 一
2 èr 二
3 sān 三
4 sì 四
5 wǔ 五
6 liù 六
7 qī 七
8 bā 八
9 jiǔ 九
10 shí 十
100 bǎi 百
1000 qiān 千
10000 wàn 万
```

Multiple-digit numbers are constructed by first the digit value (1 to 9) and then the place multiplier (such as 10, 100, 1000), starting with the most significant digit. A special case is made for 10 - 19 where the leading digit value (yī 一) is dropped. Note that this special case is only made for the actual values 10 - 19, not any larger values.

```
10 十
11 十一
18 十八
21 二十一
110 一百一十
123 一百二十三
24681 二万四千六百八十一
```

Trailing zeros are omitted, but interior zeros are grouped together and indicated by a single 零 character without giving the place multiplier.

```
10 十
20 二十
104 一百零四
1004 一千零四
10004 一万零四
10000 一万
```

Decimal numbers are constructed by first writing the whole number part, and then inserting a point (diǎn 点), followed by the decimal portion. The decimal portion is expressed using only the digits 0 to 9, without any positional characters and without grouping zeros.

```
0.1 零点一
123.45 一百二十三点四五
```

Negative numbers are the same as other numbers, but add a 负 (fù) before the number.

For more information, please see http://en.wikipedia.org/wiki/Chinese_numerals.

numerals = {
        "-":"负",
        ".":"点",
        0:"零",
        1:"一",
        2:"二",
        3:"三",
        4:"四",
        5:"五",
        6:"六",
        7:"七",
        8:"八",
        9:"九",
        10:"十",
        100:"百",
        1000:"千",
        10000:"万"
    }

def to_chinese_numeral(n, keep_ten=False, trailing_zero=False):
    if trailing_zero: return numerals[0] + to_chinese_numeral(n, keep_ten)
    if n < 0: return numerals['-'] + to_chinese_numeral(-n)
    if n % 1: return to_chinese_numeral(n // 1) + numerals['.'] + ''.join(numerals[int(d)] for d in str(n).split('.')[1])
    if n >= 10000: return to_chinese_numeral(n // 10000) + numerals[10000] + bool(n % 10000) * to_chinese_numeral(n % 10000, True, n % 10000 < 10000 // 10)
    if n >= 1000: return numerals[n // 1000] + numerals[1000] + bool(n % 1000) * to_chinese_numeral(n % 1000, True, n % 1000 < 1000 // 10)
    if n >= 100: return numerals[n // 100] + numerals[100] + bool(n % 100) * to_chinese_numeral(n % 100, True, n % 100 < 100 // 10)
    if n >= 10: return bool(keep_ten or n // 10 > 1) * numerals[n // 10] + numerals[10] + bool(n % 10) * to_chinese_numeral(n % 10, True)
    return numerals[n]


Solve in Python:
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral.

Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost digit and skipping any 0s. So 1990 is rendered "MCMXC" (1000 = M, 900 = CM, 90 = XC) and 2008 is rendered "MMVIII" (2000 = MM, 8 = VIII). The Roman numeral for 1666, "MDCLXVI", uses each letter in descending order.

Example:

```python
solution('XXI') # should return 21
```

```Elixir
Solution.decode("XXI") # should return 21
```

Help:
```
Symbol  Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1,000
```

*Courtesy of rosettacode.org*

def solution(roman):
    romanic={"M":1000,"D":500,"C":100,"L":50,"X":10,"V":5,"I":1}
    number=0
    prev_num=0
    for i in roman:
        number+=romanic[i]
        if romanic[i]>prev_num:
            number=number-(2*prev_num)
        prev_num=romanic[i]
    return number


Solve in Python:
Create a function that takes a list of one or more non-negative integers, and arranges them such that they form the largest possible number.

Examples:

`largestArrangement([4, 50, 8, 145])` returns 8504145 (8-50-4-145)

`largestArrangement([4, 40, 7])` returns 7440 (7-4-40)

`largestArrangement([4, 46, 7])` returns 7464 (7-46-4)

`largestArrangement([5, 60, 299, 56])` returns 60565299 (60-56-5-299)

`largestArrangement([5, 2, 1, 9, 50, 56])` returns 95655021 (9-56-5-50-21)


Solve in Python:
Create a function that takes a number and finds the factors of it, listing them in **descending** order in an **array**.

If the parameter is not an integer or less than 1, return `-1`. In C# return an empty array.

For Example:
`factors(54)` should return `[54, 27, 18, 9, 6, 3, 2, 1]`

def factors(n):
  from math import sqrt

  if not isinstance(n, int) or n < 1:
    return -1

  lim = int(sqrt(n))
  divisors = set([n, 1])

  start = 2 + n%2
  step = start - 1

  for i in range(start, lim+1, step):
    if n%i == 0:
      divisors.add(i)
      divisors.add(n//i)

  return sorted(divisors, reverse=True)


Solve in Python:
Create a function that takes a number as an argument and returns a grade based on that number.

Score                                    | Grade
-----------------------------------------|-----
Anything greater than 1 or less than 0.6 | "F"
0.9 or greater                           | "A"
0.8 or greater                           | "B"
0.7 or greater                           | "C"
0.6 or greater                           | "D"

Examples:
```
grader(0)   should be "F"
grader(1.1) should be "F"
grader(0.9) should be "A"
grader(0.8) should be "B"
grader(0.7) should be "C"
grader(0.6) should be "D"
```

def grader(score: int):
    if score > 1:
        return 'F'
    elif score >= .9:
        return 'A'
    elif score >= .8:
        return 'B'
    elif score >= .7:
        return 'C'
    elif score >= .6:
        return 'D'
    else:
        return 'F'


Solve in Python:
Create a function that takes a positive integer and returns the next bigger number that can be formed by rearranging its digits. For example:

```
12 ==> 21
513 ==> 531
2017 ==> 2071
```

If the digits can't be rearranged to form a bigger number, return `-1` (or `nil` in Swift):

```
9 ==> -1
111 ==> -1
531 ==> -1
```

def next_bigger(n):
    m = [d for d in str(n)]
    for d in range(len(m)-1, 0, -1):
        if max(m[d:]) > m[d-1]:
            i = min((x for x in range(d, len(m)) if m[x] > m[d-1]), key = lambda k : m[k])
            m[d-1], m[i] = m[i], m[d-1]
            m[d:] = sorted(m[d:])
            break
    else:
        return -1
    return int("".join(m))


Solve in Python:
Create a function that takes a string and an integer (`n`).

The function should return a string that repeats the input string `n` number of times.

If anything other than a string is passed in you should return `"Not a string"`

## Example

```
"Hi", 2 --> "HiHi"
1234, 5 --> "Not a string"
```

repeat_it=lambda string,n: string*n if type(string)==str else "Not a string"


Solve in Python:
Create a function that takes a string and returns that
string with the first half lowercased and the last half uppercased.

eg: foobar == fooBAR

If it is an odd number then 'round' it up to find which letters to uppercase. See example below.

    sillycase("brian")
    //         --^-- midpoint
    //         bri    first half (lower-cased)
    //            AN second half (upper-cased)

import math

def sillycase(silly):
    if len(silly) % 2 == 0:
        even_half = len(silly) // 2
        return silly[:even_half].lower() + silly[even_half:].upper()
    else:
        odd_half = math.ceil(len(silly) / 2)
        return silly[:odd_half].lower() + silly[odd_half:].upper()


Solve in Python:
Create a function that takes a string as a parameter and does the following, in this order:

1. replaces every letter with the letter following it in the alphabet (see note below)
2. makes any vowels capital
3. makes any consonants lower case

**Note:** the alphabet should wrap around, so `Z` becomes `A`

So, for example the string `"Cat30"` would return `"dbU30"` (`Cat30 --> Dbu30 --> dbU30`)

import re
def changer(st):
    st = st.lower().translate(st.maketrans('abcdefghijklmnopqrstuvwxyz','bcdefghijklmnopqrstuvwxyza'))
    return re.sub('[aeiou]',lambda m: m.group().upper(),st)


Solve in Python:
Create a function that takes an input String and returns a String, where all the uppercase words of the input String are in front and all the lowercase words at the end.
The order of the uppercase and lowercase words should be the order in which they occur.

If a word starts with a number or special character, skip the word and leave it out of the result.

Input String will not be empty.

For an input String: "hey You, Sort me Already!"
the function should return: "You, Sort Already! hey me"

def capitals_first(string):
    return ' '.join([word for word in string.split() if word[0].isupper()] + [word for word in string.split() if word[0].islower()])


Solve in Python:
Create a function that takes any sentence and redistributes the spaces (and adds additional spaces if needed) so that each word starts with a vowel. The letters should all be in the same order but every vowel in the sentence should be the start of a new word. The first word in the new sentence may start without a vowel. It should return a string in all lowercase with no punctuation (only alphanumeric characters).

EXAMPLES
'It is beautiful weather today!' becomes 'it isb e a ut if ulw e ath ert od ay'
'Coding is great' becomes 'c od ing isgr e at'
'my number is 0208-533-2325' becomes 'myn umb er is02085332325'

def vowel_start(st):
    return ''.join(f'{" " * (c in "aeiou")}{c}' for c in st.lower() if c.isalnum()).lstrip()


Solve in Python:
Create a function that takes in the sum and age difference of two people, calculates their individual ages, and returns a pair of values (oldest age first) if those exist or `null/None` if:

* `sum < 0`
* `difference < 0`
* Either of the calculated ages come out to be negative

def get_ages(a,b):
    x = (a+b)/2
    y = (a-b)/2
    return None if a<0 or b<0 or x<0 or y<0 else (x,y)


Solve in Python:
Create a function that transforms any positive number to a string representing the number in words.  The function should work for all numbers between 0 and 999999.

### Examples

```
number2words(0)  ==>  "zero"
number2words(1)  ==>  "one"
number2words(9)  ==>  "nine"
number2words(10)  ==>  "ten"
number2words(17)  ==>  "seventeen"
number2words(20)  ==>  "twenty"
number2words(21)  ==>  "twenty-one"
number2words(45)  ==>  "forty-five"
number2words(80)  ==>  "eighty"
number2words(99)  ==>  "ninety-nine"
number2words(100)  ==>  "one hundred"
number2words(301)  ==>  "three hundred one"
number2words(799)  ==>  "seven hundred ninety-nine"
number2words(800)  ==>  "eight hundred"
number2words(950)  ==>  "nine hundred fifty"
number2words(1000)  ==>  "one thousand"
number2words(1002)  ==>  "one thousand two"
number2words(3051)  ==>  "three thousand fifty-one"
number2words(7200)  ==>  "seven thousand two hundred"
number2words(7219)  ==>  "seven thousand two hundred nineteen"
number2words(8330)  ==>  "eight thousand three hundred thirty"
number2words(99999)  ==>  "ninety-nine thousand nine hundred ninety-nine"
number2words(888888)  ==>  "eight hundred eighty-eight thousand eight hundred eighty-eight"
```


Solve in Python:
Create a function that will return ```true``` if the input is in the following date time format ```01-09-2016 01:20``` and ```false``` if it is not.

This Kata has been inspired by the Regular Expressions chapter from the book Eloquent JavaScript.


Solve in Python:
Create a function that will return true if all numbers in the sequence follow the same counting pattern. If the sequence of numbers does not follow the same pattern, the function should return false.

Sequences will be presented in an array of varied length. Each array will have a minimum of 3 numbers in it.

The sequences are all simple and will not step up in varying increments such as a Fibonacci sequence.

JavaScript examples:

def validate_sequence(seq):
    return len({a - b for a, b in zip(seq, seq[1:])}) == 1


Solve in Python:
Create a function which accepts one arbitrary string as an argument, and return a string of length 26.

The objective is to set each of the 26 characters of the output string to either `'1'` or `'0'` based on the fact whether the Nth letter of the alphabet is present in the input (independent of its case).

So if an `'a'` or an `'A'` appears anywhere in the input string (any number of times), set the first character of the output string to `'1'`, otherwise to `'0'`. if `'b'` or `'B'` appears in the string, set the second character to `'1'`, and so on for the rest of the alphabet.

For instance:

```
"a   **&  cZ"  =>  "10100000000000000000000001"
```

def change(st):
    new = ""
    st = st.lower()
    for letter in "abcdefghijklmnopqrstuvwxyz":
        if letter in st:
            new += "1"
        else:
            new += "0"
    return new


Solve in Python:
Create a function which answers the question "Are you playing banjo?".
If your name starts with the letter "R" or lower case "r", you are playing banjo!

The function takes a name as its only argument, and returns one of the following strings:
```
name + " plays banjo"
name + " does not play banjo"
```
Names given are always valid strings.

def areYouPlayingBanjo(name):
    return ['%s plays banjo' % (name), '%s does not play banjo' % (name)][name[0].lower() != 'r']


Solve in Python:
Create a function which checks a number for three different properties.

- is the number prime?
- is the number even?
- is the number a multiple of 10?

Each should return either true or false, which should be given as an array. Remark: The Haskell variant uses `data Property`.

### Examples
```python
number_property(7)  # ==> [true,  false, false]
number_property(10) # ==> [false, true,  true]
```
The number will always be an integer, either positive or negative. Note that negative numbers cannot be primes, but they can be multiples of 10:

```python
number_property(-7)  # ==> [false, false, false]
number_property(-10) # ==> [false, true,  true]
```

def number_property(n):
    ans=[False,False,False]
    j=[]
    k=[]
    if n>1:
     for x in range(2,int(n ** 0.5)+ 1):
      j.append(x)
      if n%x:
        k.append(x)
     if k==j:
      ans[0]=True
    if n%2==0:
      ans[1]=True
    if n%10==0:
      ans[2]=True
    return ans


Solve in Python:
Create a function with two arguments that will return an array of the first (n) multiples of (x).

Assume both the given number and the number of times to count will be positive numbers greater than 0.

Return the results as an array (or list in Python, Haskell or Elixir).

Examples:

```python
count_by(1,10) #should return [1,2,3,4,5,6,7,8,9,10]
count_by(2,5) #should return [2,4,6,8,10]
```

def count_by(x, n):
    number = []
    for i in range(1,n+1):
        num = x*i
        number.append(num)
    return number


Solve in Python:
Create a function xMasTree(height) that returns a christmas tree of the correct height. The height is passed through to the function and the function should return a list containing each line of the tree.
```
xMasTree(5) should return : ['____#____', '___###___', '__#####__', '_#######_', '#########', '____#____', '____#____']
xMasTree(3) should return : ['__#__', '_###_', '#####', '__#__', '__#__']
```
The final idea is for the tree to look like this if you decide to print each element of the list:
```
xMasTree(5) will result in:
____#____              1
___###___              2
__#####__              3
_#######_              4
#########       -----> 5 - Height of Tree
____#____        1
____#____        2 - Trunk/Stem of Tree

xMasTree(3) will result in:
__#__                  1
_###_                  2
#####          ----->  3 - Height of Tree
__#__           1
__#__           2 - Trunk/Stem of Tree
```
Pad with underscores i.e _ so each line is the same length. The last line forming the tree having only hashtags, no spaces. Also remember the trunk/stem of the tree.


Solve in Python:
Create a method (**JS**: function) `every` which returns every nth element of an array.

### Usage

With no arguments, `array.every` it returns every element of the array.
With one argument, `array.every(interval)` it returns every `interval`th element.
With two arguments, `array.every(interval, start_index)` it returns every `interval`th element starting at index `start_index`

**Note**: due to fact JS translation ask for a function instead of an Array method the above uses will be :
```
javascript:                          ruby:
every(array)                         array.every
every(array, interval)               array.every(interval)
every(array, interval, start_index)  array.every(interval, start_index)

```

### Examples

### Notes
Test cases:

`interval` will always be a positive integer (but may be larger than the size of the array).
`start_index` will always be within the bounds of the array.

Once you have completed this kata, try the **advanced version** (http://www.codewars.com/kata/every-nth-array-element-advanced) which allows negative intervals and unbounded start\_indexes

### Translator notes
Ruby is the original language for this kata.

def every(array, ii=0, si=0):
    return array[si::] if ii==0 else array[si::ii]


Solve in Python:
Create a method `sayHello`/`say_hello`/`SayHello` that takes as input a name, city, and state to welcome a person. Note that `name` will be an array consisting of one or more values that should be joined together with one space between each, and the length of the `name` array in test cases will vary.

Example:

```python
say_hello(['John', 'Smith'], 'Phoenix', 'Arizona')
```

This example will return the string `Hello, John Smith! Welcome to Phoenix, Arizona!`

def say_hello(name, city, state):
    cunt = ' '.join(name)
    return f"Hello, {cunt}! Welcome to {city}, {state}!"


Solve in Python:
Create a program that will return whether an input value is a str, int, float, or bool. Return the name of the value.

### Examples
- Input = 23 --> Output = int
- Input = 2.3 --> Output = float
- Input = "Hello" --> Output = str
- Input = True --> Output = bool

def types(x):
    return str(type(x).__name__)


Solve in Python:
Create a program that will take in a string as input and, if there are duplicates of more than two alphabetical characters in the string, returns the string with all the extra characters in a bracket.

For example, the input "aaaabbcdefffffffg" should return  "aa[aa]bbcdeff[fffff]g"

Please also ensure that the input is a string, and return "Please enter a valid string" if it is not.

def string_parse(string):
    if not isinstance(string, str):
        return 'Please enter a valid string'
    res = []
    count = 0
    last_char = None
    for c in string:
        if c != last_char:
            if count > 2:
                res.append(']')
            count = 0
        elif count == 2:
            res.append('[')
        count += 1
        last_char = c
        res.append(c)
    if count > 2:
        res.append(']')
    return "".join(res)


Solve in Python:
Create a timebased key-value store class TimeMap, that supports two operations.
1. set(string key, string value, int timestamp)

Stores the key and value, along with the given timestamp.

2. get(string key, int timestamp)

Returns a value such that set(key, value, timestamp_prev) was called previously, with timestamp_prev <= timestamp.
If there are multiple such values, it returns the one with the largest timestamp_prev.
If there are no values, it returns the empty string ("").

Example 1:
Input: inputs = ["TimeMap","set","get","get","set","get","get"], inputs = [[],["foo","bar",1],["foo",1],["foo",3],["foo","bar2",4],["foo",4],["foo",5]]
Output: [null,null,"bar","bar",null,"bar2","bar2"]
Explanation:
TimeMap kv;
kv.set("foo", "bar", 1); // store the key "foo" and value "bar" along with timestamp = 1
kv.get("foo", 1);  // output "bar"
kv.get("foo", 3); // output "bar" since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 ie "bar"
kv.set("foo", "bar2", 4);
kv.get("foo", 4); // output "bar2"
kv.get("foo", 5); //output "bar2"

Example 2:
Input: inputs = ["TimeMap","set","set","get","get","get","get","get"], inputs = [[],["love","high",10],["love","low",20],["love",5],["love",10],["love",15],["love",20],["love",25]]
Output: [null,null,null,"","high","high","low","low"]

Note:

All key/value strings are lowercase.
All key/value strings have length in the range [1, 100]
The timestamps for all TimeMap.set operations are strictly increasing.
1 <= timestamp <= 10^7
TimeMap.set and TimeMap.get functions will be called a total of 120000 times (combined) per test case.

class TimeMap:

    def __init__(self):
        \"\"\"
        Initialize your data structure here.
        \"\"\"
        self.map = collections.defaultdict(list)

    def set(self, key: str, value: str, timestamp: int) -> None:
        self.map[key].append([timestamp, value])

    def get(self, key: str, timestamp: int) -> str:
        #print(timestamp)
        if key in self.map:
            low = 0
            high = len(self.map[key])-1
            while low <= high:
                middle = (low + high)//2
                if self.map[key][middle][0] == timestamp:
                    return self.map[key][middle][1]
                elif self.map[key][middle][0] < timestamp:
                    low = middle + 1
                else:
                    high = middle - 1

            if self.map[key][middle][0] > timestamp:
                if middle > 0:
                    return self.map[key][middle-1][1]
            else:
                    return self.map[key][middle][1]

        return \"\"

# Your TimeMap object will be instantiated and called as such:
# obj = TimeMap()
# obj.set(key,value,timestamp)
# param_2 = obj.get(key,timestamp)


Solve in Python:
Create an OR function, without use of the 'or' keyword, that takes an list of boolean values and runs OR against all of them.

Assume there will be between 1 and 6 variables, and return None for an empty list.

def alt_or(lst):
    return eval(str(lst).replace(',', '|'))[0] if lst else None


def get_matrix(n):
    return [[x==y for x in range(n)] for y in range(n)]


Solve in Python:
Create the function ```consecutive(arr)``` that takes an array of integers and return the minimum number of integers needed to make the contents of ```arr``` consecutive from the lowest number to the highest number.
For example:  If ```arr``` contains [4, 8, 6] then the output should be 2 because two numbers need to be added to the array (5 and 7) to make it a consecutive array of numbers from 4 to 8. Numbers in ```arr``` will be unique.

def consecutive(arr):
    return max(arr) - min(arr) + 1 - len(arr) if arr else 0


Solve in Python:
Create your own mechanical dartboard that gives back your score based on the coordinates of your dart.

Task:

Use the scoring rules for a standard dartboard:

Finish method:

```python
def get_score(x,y):
```

The coordinates are `(x, y)` are always relative to the center of the board (0, 0). The unit is millimeters. If you throw your dart 5 centimeters to the left and 3 centimeters below, it is written as:

```python
score = get_score(-50, -30)
```

Possible scores are:Outside of the board: `"X"`Bull's eye: `"DB"`Bull: `"SB"`A single number, example: `"10"`A triple number: `"T10"`A double number: `"D10"`
A throw that ends exactly on the border of two sections results in a bounce out. You can ignore this because all the given coordinates of the tests are within the sections.
The diameters of the circles on the dartboard are:Bull's eye: `12.70 mm`Bull: `31.8 mm`Triple ring inner circle: `198 mm`Triple ring outer circle: `214 mm`Double ring inner circle: `324 mm`Double ring outer circle: `340 mm`

If you liked this kata, you can continue with: Let's Play Darts: Beat The Power!

from math import atan2, degrees

def get_score(x, y):
    scores = [8, 16, 7, 19, 3, 17, 2, 15, 10, 6,
              13, 4, 18, 1, 20, 5, 12, 9, 14, 11]

    distance = (x*x + y*y) ** 0.5
    angle = degrees(atan2(y, x))
    mod = ''

    if distance > 340 / 2:
        return 'X'         # outside
    elif distance < 12.7 / 2:
        return 'DB'        # bull's eye
    elif distance < 31.8 / 2:
        return 'SB'        # bull
    elif 198 / 2 < distance < 214 / 2:
        mod = 'T'          # triple
    elif 324 / 2 < distance < 340 / 2:
        mod = 'D'          # double

    number = str( scores[int((angle + 180 + 9) / 18) - 1] )

    return mod + number