Solve in Python:
#Description

Everybody has probably heard of the animal heads and legs problem from the earlier years at school. It goes:

```“A farm contains chickens and cows. There are x heads and y legs. How many chickens and cows are there?” ```

Where x <= 1000 and y <=1000

#Task

Assuming there are no other types of animals, work out how many of each animal are there.

```Return a tuple in Python - (chickens, cows) and an array list - [chickens, cows]/{chickens, cows} in all other languages```

If either the heads & legs is negative, the result of your calculation is negative or the calculation is a float return "No solutions" (no valid cases).

In the form:
```python
(Heads, Legs) = (72, 200)

VALID - (72, 200) =>             (44 , 28)
                             (Chickens, Cows)

INVALID - (72, 201) => "No solutions"
```

However, ```if 0 heads and 0 legs are given always return [0, 0]``` since zero heads must give zero animals.

There are many different ways to solve this, but they all give the same answer.

You will only be given integers types - however negative values (edge cases) will be given.

Happy coding!

def animals(h,l):
    """
    Count cows and chickens
    """
    co = (l-2*h)//2
    ch = h - co
    return 'No solutions' if ch < 0 or co < 0 or h < 0 or l % 2 != 0 or l < 0  else (ch,co)


Solve in Python:
#Detail

[Countdown](https://en.wikipedia.org/wiki/Countdown_(game_show) is a British game show with number and word puzzles. The letters round consists of the contestant picking 9 shuffled letters - either picking from the vowel pile or the consonant pile. The contestants are given 30 seconds to try to come up with the longest English word they can think of with the available letters - letters can not be used more than once unless there is another of the same character.

#Task

Given an uppercase 9 letter string, ```letters```, find the longest word that can be made with some or all of the letters. The preloaded array ```words``` (or ```$words``` in Ruby) contains a bunch of uppercase words that you will have to loop through. Only return the longest word; if there is more than one, return the words of the same lengths in alphabetical order. If there are no words that can be made from the letters given, return ```None/nil/null```.

##Examples

```
letters = "ZZZZZZZZZ"
longest word = None

letters = "POVMERKIA",
longest word = ["VAMPIRE"]

letters = "DVAVPALEM"
longest word = ["VAMPED", "VALVED", "PALMED"]

```

def longest_word(letters):
    try:
        word_list = [w for w in words if all(w.count(c) <= letters.count(c) for c in w)]
        largest = sorted([w for w in word_list if len(w) == len(max(word_list, key=len))])
        return largest if largest else None
    except:
        return None


Solve in Python:
#Find the missing letter

Write a method that takes an array of consecutive (increasing) letters as input and that returns the missing letter in the array.

You will always get an valid array. And it will be always exactly one letter be missing. The length of the array will always be at least 2.
The array will always contain letters in only one case.

Example:
```if-not:swift
['a','b','c','d','f'] -> 'e'
['O','Q','R','S'] -> 'P'
```

(Use the English alphabet with 26 letters!)

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

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

def find_missing_letter(input):
    alphabet = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
    start = alphabet.index(input[0])
    for i in range(len(input)):
        if not input[i] == alphabet[start+i]:
            return alphabet[start+i]


Solve in Python:
#It's show time!
Archers have gathered from all around the world to participate in the Arrow Function Faire. But the faire will only start if there are archers signed and if they all have enough arrows in their quivers - at least 5 is the requirement! Are all the archers ready?

#Reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

#Argument
`archers` is an array of integers, in which each element corresponds to the number of arrows each archer has.

#Return
Your function must return `true` if the requirements are met or `false` otherwise.

#Examples
`archersReady([1, 2, 3, 4, 5, 6, 7, 8])` returns `false` because there are archers with not enough arrows.

`archersReady([5, 6, 7, 8])` returns `true`.

def archers_ready(archers):
    return archers != [] and all(x > 4 for x in archers)


Solve in Python:
#Permutation  position
In this kata you will have to permutate through a string of lowercase letters, each permutation will start at ```a``` and you must calculate how many iterations it takes to reach the current permutation.

##examples
```
input: 'a'
result: 1

input: 'c'
result: 3

input: 'z'
result: 26

input: 'foo'
result: 3759

input: 'aba'
result: 27

input: 'abb'
result: 28

```

def permutation_position(perm):
    return sum((ord(c) - 0x61) * (26 ** i) for i, c in enumerate(reversed(perm))) + 1


def skrzat(base, number):
    def to_binary(number):
        schroeppel2 = 0xAAAAAAAA
        return "From decimal: {} is {}".format(number, bin((int(number) + schroeppel2) ^ schroeppel2)[2:])
    def to_decimal(number):
        return "From binary: {} is {}".format(number, sum(int(d)*(-2)**i for i, d in enumerate(reversed(number))))

    if base == "b":
        return to_decimal(number)
    return to_binary(number)


Solve in Python:
#Sort the columns of a csv-file

You get a string with the content of a csv-file. The columns are separated by semicolons.
The first line contains the names of the columns.
Write a method that sorts the columns by the names of the columns alphabetically and incasesensitive.

An example:
```
Before sorting:
As table (only visualization):
|myjinxin2015|raulbc777|smile67|Dentzil|SteffenVogel_79|
|17945       |10091    |10088  |3907   |10132          |
|2           |12       |13     |48     |11             |

The csv-file:
myjinxin2015;raulbc777;smile67;Dentzil;SteffenVogel_79\n
17945;10091;10088;3907;10132\n
2;12;13;48;11

----------------------------------

After sorting:
As table (only visualization):
|Dentzil|myjinxin2015|raulbc777|smile67|SteffenVogel_79|
|3907   |17945       |10091    |10088  |10132          |
|48     |2           |12       |13     |11             |

The csv-file:
Dentzil;myjinxin2015;raulbc777;smile67;SteffenVogel_79\n
3907;17945;10091;10088;10132\n
48;2;12;13;11
```

There is no need for prechecks. You will always get a correct string with more than 1 line und more than 1 row. All columns will have different names.

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

I have created other katas. Have a look if you like coding and challenges.

import string
def sort_csv_columns(csv_file_content):
    orderby=' _0123456789'+string.ascii_lowercase
    l=list(zip(*[i.split(';') for i in csv_file_content.split('\n')]))
    l.sort(key=lambda a:[orderby.index(i) for i in a[0].lower()])
    return '\n'.join(';'.join(i) for i in zip(*l))


Solve in Python:
#Sorting on planet Twisted-3-7

There is a planet... in a galaxy far far away. It is exactly like our planet, but it has one difference:
#The values of the digits 3 and 7 are twisted.
Our 3 means 7 on the planet Twisted-3-7. And 7 means 3.

Your task is to create a method, that can sort an array the way it would be sorted on Twisted-3-7.

7 Examples from a friend from Twisted-3-7:
```
[1,2,3,4,5,6,7,8,9] -> [1,2,7,4,5,6,3,8,9]
[12,13,14] -> [12,14,13]
[9,2,4,7,3] -> [2,7,4,3,9]
```

There is no need for a precheck. The array will always be not null and will always contain at least one number.

You should not modify the input array!

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

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

def sort_twisted37(arr):
    str_arr = [str(i) for i in arr]
    swap1(str_arr)
    str_arr = sorted([int(i) for i in str_arr])
    str_arr = [str(i) for i in str_arr]
    swap1(str_arr)
    return [int(i) for i in str_arr]

def swap1(str_arr):
    for index, numstr in enumerate(str_arr):
        if '3' in numstr or '7' in numstr:
            str_arr[index] = numstr.replace('3','%temp%').replace('7','3').replace('%temp%','7')


Solve in Python:
#Split all even numbers to odd ones in different ways

Your task is to split all even numbers from an array to odd ones. So your method has to return a new array with only odd numbers.

For "splitting" the numbers there are four ways.

```
0 -> Split into two odd numbers, that are closest to each other.
     (e.g.: 8 -> 3,5)
1 -> Split into two odd numbers, that are most far from each other.
     (e.g.: 8 -> 1,7)
2 -> All new odd numbers from the splitting should be equal and the maximum possible number.
     (e.g.: 8 -> 1, 1, 1, 1, 1, 1, 1, 1)
3 -> Split into 1s.
     (e.g.: 8 -> 1, 1, 1, 1, 1, 1, 1, 1)
The new numbers (from the splitting) have always to be in ascending order.
So in the array every even number is replaced by the new odd numbers from the splitting.
```

Your method will get as parameters the input-array and the number of the way for splitting the even numbers.

Some Examples
```
[1,10,1,3],0 -> [1,5,5,1,3]
[1,10,1,3],1 -> [1,1,9,1,3]
[1,10,1,3],2 -> [1,5,5,1,3]
[1,10,1,3],3 -> [1,1,1,1,1,1,1,1,1,1,1,1,3]

[1,1,3,8],0 -> [1,1,3,3,5]
[1,1,3,8],1 -> [1,1,3,1,7]
[1,1,3,8],2 -> [1,1,3,1,1,1,1,1,1,1,1]
[1,1,3,8],3 -> [1,1,3,1,1,1,1,1,1,1,1]
```

The array will never be null and will always contain only integer numbers > 0. Also your result-array must contain only integer numbers > 0.
The way-parameter will always be between inclusive 0 and inclusive 3 (0,1,2,3).

You must not change the input-array!

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

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

ways = {
    0 : lambda n : [n//2]*2 if (n//2)%2 else [n//2-1,n//2+1],
    1 : lambda n : [1,n-1],
    2 : lambda n : [ [n//x]*x for x in range(2,n+1) if sum([n//x]*x)==n and (n//x)%2][0],
    3 : lambda n : [1]*n
}

def split_all_even_numbers(numbers, way):
  return [x for lists in [ways[way](x) if not x%2 else [x] for x in numbers] for x in lists]


Solve in Python:
#Task:
Write a function `get_member_since` which accepts a username from someone at Codewars and returns an string containing the month and year separated by a space that they joined CodeWars.

###If you want/don't want your username to be in the tests, ask me in the discourse area. There can't be too many though because the server may time out.

#Example:

```python
>>> get_member_since('dpleshkov')
Jul 2016
>>> get_member_since('jhoffner')
Oct 2012
```

#Libraries/Recommendations:

##Python:

* `urllib.request.urlopen`: Opens up a webpage.
* `re`: The RegEx library for Python.
* `bs4`([BeautifulSoup](https://www.crummy.com/software/BeautifulSoup/bs4/doc)): A tool for scraping HTML and XML.
* **Python 2 is not working for this kata. :(**

#Notes:

* Time out / server errors often happen with the test cases depending on the status of the codewars website. Try submitting your code a few times or at different hours of the day if needed.
* Feel free to voice your comments and concerns in the discourse area.

import requests
from bs4 import BeautifulSoup
import re

def get_member_since(username):
    soup = BeautifulSoup(requests.get("https://www.codewars.com/users/"+username).text, 'html.parser')
    return str(re.findall("Member Since:........
?", str(soup.body.div.div.main.section)))[19:27]


Solve in Python:
#Unflatten a list (Easy)

There are several katas like "Flatten a list".
These katas are done by so many warriors, that the count of available list to flattin goes down!

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

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

You get an array of integers and have to unflatten it by these rules:
```
- You start at the first number.
- If this number x is smaller than 3, take this number x direct
  for the new array and continue with the next number.
- If this number x is greater than 2, take the next x numbers (inclusive this number) as a
  sub-array in the new array. Continue with the next number AFTER this taken numbers.
- If there are too few numbers to take by number, take the last available numbers.
```

The given array will always contain numbers. There will only be numbers > 0.

Example:
```
 [1,4,5,2,1,2,4,5,2,6,2,3,3] -> [1,[4,5,2,1],2,[4,5,2,6],2,[3,3]]

Steps:
1. The 1 is added directly to the new array.
2. The next number is 4. So the next 4 numbers (4,5,2,1) are added as sub-array in the new array.
3. The 2 is added directly to the new array.
4. The next number is 4. So the next 4 numbers (4,5,2,6) are added as sub-array in the new array.
5. The 2 is added directly to the new array.
6. The next number is 3. So the next 3 numbers would be taken. There are only 2,
   so take these (3,3) as sub-array in the new array.
```

There is a harder version of this kata!
Unflatten a list (Harder than easy)

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

I have created other katas. Have a look if you like coding and challenges.

def unflatten(flat):
    a = []
    while flat:
        a, flat = (a + [flat[0]], flat[1:]) if flat[0] < 3 else (a + [flat[:flat[0]]], flat[flat[0]:])
    return a


Solve in Python:
$Gogi$, $Tapu$ and $Sonu$ are the elite members of $Tapu$ $Sena$. $Gogi$ is always stoned and asks absurd questions, But this time he asked a question which seems to be very serious and interesting. $Tapu$ wants to solve this question to impress $Sonu$. He  gave an array of length N to $Tapu$, $Tapu$ can perform the following operations exactly once:
- Remove any subarray from the given array given the resulting array formed after the removal is non-empty.
- Reverse the whole array.
Remember you can’t shuffle the elements of the array.
Tapu needs to find out the maximum possible GCD of all the numbers in the array after applying the given operations exactly once. Tapu is very weak at programming, he wants you to solve this problem so that he can impress $Sonu$.

-----Input:-----
- The first line contains $T$, the number of test cases.
- For each test case
-FIrst line contains $N$.
- Last line contains $N$ numbers of the array.

-----Output:-----
A single integer in a new line, maximum possible GCD.

-----Constraints-----
- $1 \leq T \leq 10^2$
- $1 \leq N \leq 10^4$
- $1 \leq a[i] \leq 10^9$

Summation of N for all testcases is less than $10^6$

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

-----Sample Output 1:-----
2

# cook your dish here
import math
T = int(input())

for _ in range(T):
    N = int(input())
    ar = input().split()
    m = int(ar[0])

    if int(ar[N-1]) > m:
        m = int(ar[N-1])

    print(m)


Solve in Python:
$Harshad$ $Mehta$ is planning  a new scam with the stocks he is given a stock of  integer price S and a number K . $harshad$ has got the power to change the number $S$ at most $K$ times
In order to raise the price of stock and now cash it for his benefits
Find the largest price at which $harshad$ can sell the stock in order to maximize his profit

-----Input:-----
- First line will contain $S$ and  $K$ , the price of the stock and the number K

-----Output:-----
Print the largest profit  he can make in a single line.

-----Constraints-----
- S can take value upto 10^18
NOTE: use 64 int number to fit range
- K can take value from [0.. 9]

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

-----Sample Output:-----
9983

-----EXPLANATION:-----
First two digits of the number are changed to get the required number.

a,b=[int(_) for _ in input().split()]
if b==0:
    print(a)
else:
    l=[]
    a=str(a)
    for i in range(len(a)):
        l.append(a[i])
    for i in range(len(l)):
        if b==0:
            break
        if l[i]=='9':
            continue
        else:
            l[i]='9'
            b-=1
    s=''
    for i in l:
        s+=i
    print(s)


Solve in Python:
$Jaggu$ monkey a friend of $Choota$ $Bheem$ a great warrior of $Dholakpur$. He gets everything he wants. Being a friend of $Choota$ $Bheem$ he never has to struggle for anything, because of this he is in a great debt of $Choota$ $Bheem$, he really wants to pay his debt off.
Finally the time has come to pay his debt off, $Jaggu$ is on a magical tree. He wants to collect apples from different branches but he is in a hurry. $Botakpur$ has attacked on $Dholakpur$ and $Bheem$ is severely injured, as been instructed by the village witch, $Bheem$ can only be saved by the apples of the magical tree. Each apple is placed in Tree Node structure and each apple has some sweetness. Now there's a problem as $Jaggu$ is also injured so he can only slide downwards and alse is collecting apples in his hand so he can't climb. You would be given $Q$ queries. Queries are of 2 type :-
-
Ending Node Node of $Jaggu$ is given. $format$ - type of query node -(1 2)
-
Sweetness of Apple on a given node is changed. $format$ - type of query node new sweetness(2 3 10)
$Note$: $Jaggu$ is always on the top of tree initially in each query.The sweetness is always positive.
Help $Jaggu$ in saving $Bheem$

-----Input:-----
- First line contains $N$ - (number of nodes).
- Next line contains $N$ integers with space giving sweetness of apple on Nodes $(1 to N)$
- Next $N-1$ lines contain  $N1$ $N2$ connected nodes.
- Next line contains single integer $Q$ Number of queries

-----Output:-----
- For each query of type 1, print total sweetness of apples.

-----Constraints-----
- $1 \leq N \leq 10^4$
- $2 \leq Q \leq 10^4$

-----Sample Input:-----
10
10 12 6 8 1 19 0 5 13 17
1 2
1 3
1 4
3 10
4 8
8 9
4 5
5 7
5 6
3
1 1
2 3 20
1 8

-----Sample Output:-----
10
23

-----EXPLANATION:-----
This sweetness array is :
$[10,2,6,8,1,19,0,5,13,17]$
The tree is:
1

/  |   \

2    3     4

/    /    \

10     8        5

/        /    \

9         7        6

counter = -1
def flattree(node):
    nonlocal counter
    if visited[node]==1:
        return
    else:
        visited[node]=1
        counter += 1
        i_c[node] = counter

        flat_tree[counter] = swt[node]

        for i in graph[node]:
            if visited[i]==0:
                flattree(i)
        counter += 1
        o_c[node] = counter
        flat_tree[counter] = -swt[node]
    return

def getsum(BITTree, i):
    s = 0  # initialize result
    i = i + 1
    while i > 0:
        s += BITTree[i]
        i -= i & (-i)
    return s

def upd(BITTree, n, i, v):
    i += 1
    while i <= n:
        BITTree[i] += v
        i += i & (-i)

def construct(arr, n):
    BITTree = [0] * (n + 1)
    for i in range(n):
        upd(BITTree, n, i, arr[i])
    return BITTree

from collections import defaultdict
n = int(input())
swt = list(map(int, input().split()))
graph = defaultdict(list)

for i in range(n-1):
    n1, n2 = list(map(int, input().split()))
    graph[n1-1].append(n2-1)
    graph[n2-1].append(n1-1)

flat_tree = [0]*(2*n+1)
i_c = [0]*n
o_c = [0]*n
visited = [0]*n
flattree(0)

tre = construct(flat_tree, 2*n)

q = int(input())
for i in range(q):
    query = list(map(int, input().split()))
    if query[0] == 1:
        node = query[1] - 1
        answer = getsum(tre, i_c[node])
        print(answer)
    else:
        node = query[1]-1
        upd(flat_tree, (2*n), i_c[node], query[2])
        upd(flat_tree, (2*n), o_c[node], -query[2])


Solve in Python:
$Neha$  is given a number $N$. She always looks for special thing , this time she is looking for $Special$ $Number$ and $Partial$ $Special$ $Number$. A $Special$ $Number$ is a number whose product of its digits is equal to number itself i.e. $N $, and in this number there is no digit $1$. $Partial$ $Special$ is a number having all the condition same as $Special$ except that it can also have digit $1$ in it .Neha have to count the number of $Special$ and $Partial$ $Special$ $Numbers $for a given  $N$ . She is not so good in programming , so go and help her.

-----Input:-----
- Integers $N$ is taken as input from input stream.

-----Output:-----
- Print the number of  $Special$ and $Partial$ $Special$ $Numbers $for a given  $N$.

-----Constraints-----
- $1 \leq N \leq 100$ numbers to be count will be less then 10^6

-----Sample Input:-----
3

-----Sample Output:-----
1 20

-----EXPLANATION:-----
There are only one natural numbers, the product of the digits of which is 3  :- {3}.
There are 20 natural numbers with digit 1 , whose  product of the digits  is 3 :-{13, 31, 113 ,131 311 ,1113 ,1131 ,1311, 3111 ,11113, 11131, 11311 ,13111, 31111, 111113, 111131, 111311,113111, 131111 ,311111}


Solve in Python:
$n$ boys and $m$ girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from $1$ to $n$ and all girls are numbered with integers from $1$ to $m$. For all $1 \leq i \leq n$ the minimal number of sweets, which $i$-th boy presented to some girl is equal to $b_i$ and for all $1 \leq j \leq m$ the maximal number of sweets, which $j$-th girl received from some boy is equal to $g_j$.

More formally, let $a_{i,j}$ be the number of sweets which the $i$-th boy give to the $j$-th girl. Then $b_i$ is equal exactly to the minimum among values $a_{i,1}, a_{i,2}, \ldots, a_{i,m}$ and $g_j$ is equal exactly to the maximum among values $b_{1,j}, b_{2,j}, \ldots, b_{n,j}$.

You are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of $a_{i,j}$ for all $(i,j)$ such that $1 \leq i \leq n$ and $1 \leq j \leq m$. You are given the numbers $b_1, \ldots, b_n$ and $g_1, \ldots, g_m$, determine this number.

-----Input-----

The first line contains two integers $n$ and $m$, separated with space — the number of boys and girls, respectively ($2 \leq n, m \leq 100\,000$). The second line contains $n$ integers $b_1, \ldots, b_n$, separated by spaces — $b_i$ is equal to the minimal number of sweets, which $i$-th boy presented to some girl ($0 \leq b_i \leq 10^8$). The third line contains $m$ integers $g_1, \ldots, g_m$, separated by spaces — $g_j$ is equal to the maximal number of sweets, which $j$-th girl received from some boy ($0 \leq g_j \leq 10^8$).

-----Output-----

If the described situation is impossible, print $-1$. In another case, print the minimal total number of sweets, which boys could have presented and all conditions could have satisfied.

-----Examples-----
Input
3 2
1 2 1
3 4

Output
12
Input
2 2
0 1
1 0

Output
-1
Input
2 3
1 0
1 1 2

Output
4

-----Note-----

In the first test, the minimal total number of sweets, which boys could have presented is equal to $12$. This can be...

mx1 = 0
mx2 = 0
sum = 0

def parsare(s, lista):
    number = ""
    for l in s:
        if l != " ":
            number += l
        else:
            lista.append(int(number))
            number = ""
    lista.append(int(number))

row1 = []
row2 = []
row3 = []

sir = input()
parsare(sir, row1)

sir = input()
parsare(sir, row2)

sir = input()
parsare(sir, row3)

for nr in row2:
    sum += nr * row1[1]
    if nr > mx1:
        mx2 = mx1
        mx1 = nr
    elif nr > mx2:
        mx2 = nr

ok = True
ok2 = False

for nr in row3:
    dif = nr - mx1
    if dif < 0:
        ok = False
        break
    elif dif == 0:
        ok2 = True
    sum += dif

if ok and ok2:
    print(sum)
elif ok:
    print(sum + mx1 - mx2)
else:
    print(-1)


Solve in Python:
$n$ robots have escaped from your laboratory! You have to find them as soon as possible, because these robots are experimental, and their behavior is not tested yet, so they may be really dangerous!

Fortunately, even though your robots have escaped, you still have some control over them. First of all, you know the location of each robot: the world you live in can be modeled as an infinite coordinate plane, and the $i$-th robot is currently located at the point having coordinates ($x_i$, $y_i$). Furthermore, you may send exactly one command to all of the robots. The command should contain two integer numbers $X$ and $Y$, and when each robot receives this command, it starts moving towards the point having coordinates ($X$, $Y$). The robot stops its movement in two cases:  either it reaches ($X$, $Y$);  or it cannot get any closer to ($X$, $Y$).

Normally, all robots should be able to get from any point of the coordinate plane to any other point. Each robot usually can perform four actions to move. Let's denote the current coordinates of the robot as ($x_c$, $y_c$). Then the movement system allows it to move to any of the four adjacent points:  the first action allows it to move from ($x_c$, $y_c$) to ($x_c - 1$, $y_c$);  the second action allows it to move from ($x_c$, $y_c$) to ($x_c$, $y_c + 1$);  the third action allows it to move from ($x_c$, $y_c$) to ($x_c + 1$, $y_c$);  the fourth action allows it to move from ($x_c$, $y_c$) to ($x_c$, $y_c - 1$).

Unfortunately, it seems that some movement systems of some robots are malfunctioning. For each robot you know which actions it can perform, and which it cannot perform.

You want to send a command so all robots gather at the same point. To do so, you have to choose a pair of integer numbers $X$ and $Y$ so that each robot can reach the point ($X$, $Y$). Is it possible to find such a point?

-----Input-----

The first line contains one integer $q$ ($1 \le q \le 10^5$) — the number of queries.

Then $q$ queries follow. Each query begins with one line...

q = int(input())
for _ in range(q):
    n = int(input())
    lm = dm = -100000
    rm = um = 100000
    for _ in range(n):
        x, y, l, u, r, d = list(map(int, input().split()))
        if l == 0:
            lm = max(lm, x)
        if r == 0:
            rm = min(rm, x)
        if u == 0:
            um = min(um, y)
        if d == 0:
            dm = max(dm, y)
    if lm > rm or um < dm:
        print(0)
    else:
        print(1, lm, dm)


Solve in Python:
(This problem is the same as Minimize Malware Spread, with the differences bolded.)
In a network of nodes, each node i is directly connected to another node j if and only if graph[i][j] = 1.
Some nodes initial are initially infected by malware.  Whenever two nodes are directly connected and at least one of those two nodes is infected by malware, both nodes will be infected by malware.  This spread of malware will continue until no more nodes can be infected in this manner.
Suppose M(initial) is the final number of nodes infected with malware in the entire network, after the spread of malware stops.
We will remove one node from the initial list, completely removing it and any connections from this node to any other node.  Return the node that if removed, would minimize M(initial).  If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index.

Example 1:
Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
Output: 0

Example 2:
Input: graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1]
Output: 1

Example 3:
Input: graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]
Output: 1

Note:

1 < graph.length = graph[0].length <= 300
0 <= graph[i][j] == graph[j][i] <= 1
graph[i][i] = 1
1 <= initial.length < graph.length
0 <= initial[i] < graph.length

class Solution:
    def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:
        numNodes = len(graph)
        minSpread = float('inf')
        minNode = None
        initial.sort()

        def helper(curr, visited):

            if curr in visited:
                return

            edges = graph[curr]
            visited.add(curr)

            for i in range(len(edges)):
                if graph[curr][i] == 1:
                    helper(i, visited)

        for i in initial:
            visited = set([i])
            for j in initial:
                if i!= j:
                    helper(j, visited)

            if len(visited) < minSpread:
                minSpread = len(visited)
                minNode = i

        return minNode


Solve in Python:
*** No Loops Allowed ***

You will be given an array (a) and a limit value (limit). You must check that all values in the array are below or equal to the limit value. If they are, return true. Else, return false.

You can assume all values in the array are numbers.

Do not use loops. Do not modify input array.

Looking for more, loop-restrained fun? Check out the other kata in the series:

 https://www.codewars.com/kata/no-loops-2-you-only-need-one
 https://www.codewars.com/kata/no-loops-3-copy-within

def small_enough(a, limit):
    return all(map(lambda x: x <= limit, a))


Solve in Python:
*** No Loops Allowed ***

You will be given an array (a) and a value (x). All you need to do is check whether the provided array contains the value, without using a loop.

Array can contain numbers or strings. X can be either. Return true if the array contains the value, false if not. With strings you will need to account for case.

Looking for more, loop-restrained fun? Check out the other kata in the series:

 https://www.codewars.com/kata/no-loops-1-small-enough
 https://www.codewars.com/kata/no-loops-3-copy-within

def check(a, x):
    # your code here
    return False if a.count(x)==0 else True


Solve in Python:
*** Nova polynomial derivative***

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

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

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

In this kata return the derivative of a polynomial:

```python
poly_derivative([1, 2] ) = [2]
poly_derivative([9, 1, 3]) =  [1, 6]
```

Previous Katas on Nova polynomial:

 1. [poly_add](http://www.codewars.com/kata/nova-polynomial-1-add-1)
 2. [poly_multiply](http://www.codewars.com/kata/570eb07e127ad107270005fe).
 3. [poly_subtract](http://www.codewars.com/kata/5714041e8807940ff3001140 )

def poly_derivative(p):
    return [el * idx for idx, el in enumerate(p) if idx > 0]


Solve in Python:
*** Nova polynomial from roots***

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

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

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

In this kata create the polynomial from a list of roots:

[r0, r1 ,r2, r3 ]

p = (x-r0)(x-r1)(x-r2)(x-r3)

note: no roots should return the identity polynomial.

```python
poly_from_roots([4]) = [-4, 1]
poly_from_roots([0, 0, 0, 0] ) = [0, 0, 0, 0, 1]
poly_from_roots([]) = [1]
```
The first katas of this series is preloaded in the code and can be used: [poly_add](http://www.codewars.com/kata/570eb07e127ad107270005fe) [poly_multiply](http://www.codewars.com/kata/570eb07e127ad107270005fe)

def poly_multiply(p1, p2):
    answer = [0] * (len(p1) + len(p2) - 1)
    for i, coeff1 in enumerate(p1):
        for j, coeff2 in enumerate(p2):
            answer[i + j] += coeff1 * coeff2
    return [] if all(coeff == 0 for coeff in answer) else answer

def poly_from_roots(r):
    if not r:
        return [1]
    parts = [[-root, 1] for root in r]
    answer = parts[0]
    for part in parts[1:]:
        answer = poly_multiply(answer, part)
    return answer


Solve in Python:
*** Nova polynomial multiply***

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

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

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

In this kata multiply two polynomials:

```python
poly_multiply([1, 2], [1] ) = [1, 2]
poly_multiply([2, 4], [4, 5] ) = [8, 26, 20]
```
The first kata of this series is preloaded in the code and can be used: [poly_add](http://www.codewars.com/kata/nova-polynomial-1-add-1)

def poly_multiply(p1, p2):
  if not p1 or not p2: return []
  n = len(p1) + len(p2) - 1
  p = [0]*n
  for i,a in enumerate(p1):
    for j,b in enumerate(p2):
      p[i + j] += a*b
  return p


Solve in Python:
*** Nova polynomial subtract***

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

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

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

In this kata subtract two polynomials:

```python
poly_subtract([1, 2], [1] ) = [0, 2]
poly_subtract([2, 4], [4, 5] ) = [-2, -1]
```
The first and second katas of this series are preloaded in the code and can be used:

 * [poly_add](http://www.codewars.com/kata/nova-polynomial-1-add-1)
 * [poly_multiply](http://www.codewars.com/kata/570eb07e127ad107270005fe).

# return the subtraction of the two polynomials p1 and p2.
def poly_subtract(p1, p2):
    res = []
    longest_p = max(len(p1), len(p2))
    for i in range(longest_p):
        # add the two numbers together unless there is no number there, then just subtract 0 (don't change)
        res.append((p1[i] if i < len(p1) else 0) - (p2[i] if i < len(p2) else 0))
    return res


Solve in Python:
**An [isogram](https://en.wikipedia.org/wiki/Isogram)** (also known as a "nonpattern word") is a logological term for a word or phrase without a repeating letter. It is also used by some to mean a word or phrase in which each letter appears the same number of times, not necessarily just once.

You task is to write a method `isogram?` that takes a string argument and returns true if the string has the properties of being an isogram and false otherwise. Anything that is not a string is not an isogram (ints, nils, etc.)

**Properties:**

 - must be a string
 - cannot be nil or empty
 - each letter appears the same number of times (not necessarily just once)
 - letter case is not important (= case insensitive)
 - non-letter characters (e.g. hyphens) should be ignored

is_isogram = lambda word: type(word) == str and bool(word) and len(set( __import__("collections").Counter( __import__("re").sub(r'[^a-z]', "", word.lower())).values() )) == 1


Solve in Python:
**Background**
You most probably know, that the *kilo* used by IT-People differs from the
*kilo* used by the rest of the world. Whereas *kilo* in kB is (mostly) intrepreted as 1024 Bytes (especially by operating systems) the non-IT *kilo* denotes the factor 1000 (as in "1 kg is 1000g"). The same goes for the prefixes mega, giga, tera, peta and so on.
To avoid misunderstandings (like your hardware shop selling you a 1E+12 Byte harddisk as 1 TB, whereas  your Windows states that it has only 932 GB, because the shop uses factor 1000 whereas operating systems use factor 1024 by default) the  International Electrotechnical Commission has proposed to use **kibibyte** for 1024 Byte.The according unit symbol would be **KiB**. Other Prefixes would be respectivly:

```
1 MiB = 1024 KiB
1 GiB = 1024 MiB
1 TiB = 1024 GiB
```

**Task**
Your task is to write a conversion function between the kB and the KiB-Units. The function receives as parameter a memory size including a unit and converts into the corresponding unit of the other system:

```
memorysizeConversion ( "10 KiB") -> "10.24 kB"
memorysizeConversion ( "1 kB") -> "0.977 KiB"
memorysizeConversion ( "10 TB") -> "9.095 TiB"
memorysizeConversion ( "4.1 GiB") -> "4.402 GB"
```

**Hints**
- the parameter always contains a (fractioned) number, a whitespace and a valid unit
- units are case sensitive, valid units are **kB MB GB TB KiB MiB GiB TiB**
- result must be rounded to 3 decimals (round half up,no trailing zeros) see examples above

**Resources**
If you want to read more on ...ibi-Units:
https://en.wikipedia.org/wiki/Kibibyte

def memorysize_conversion(s):
    a, b = s.split()
    n, m, i = (1024, 1000, "") if "i" in b else (1000, 1024, "i")
    p = " KMGT".index(b[0].upper())
    return f"{round(float(a) * n**p / m**p, 3)} {'k' if b[0] == 'K' else b[0].upper()}{i}B"


Solve in Python:
**DESCRIPTION:**

  Your strict math teacher is teaching you about right triangles, and the Pythagorean Theorem --> a^2 + b^2 = c^2 whereas a and b are the legs of the right triangle and c is the hypotenuse of the right triangle. On the test however, the question asks: What are the possible integer lengths for the other side of the triangle, but since you never learned anything about that in class, you realize she meant What are the possible integer lengths for the other side of the right triangle. Because you want to address the fact that she asked the wrong question and the fact that you're smart at math, you've decided to answer all the possible values for the third side EXCLUDING the possibilities for a right triangle in increasing order.

**EXAMPLES:**

```
side_len(1, 1) --> [1]
side_len(3, 4) --> [2, 3, 4, 6]
side_len(4, 6) --> [3, 4, 5, 6, 7, 8, 9]
```
**RETURN:**

  Return your answer as a list of all the possible third side lengths of the triangle without the right triangles in increasing order.

By the way, after finishing this kata, please try some of my other katas: [Here](https://www.codewars.com/collections/tonylicodings-authored-katas)

NOTE:

  When given side_len(x, y), y will always be greater than or equal to x. Also, if a right triangle's legs are passed in, exclude the hypotenuse. If a right triangle's leg and hypotenuse are passed in, exclude the other leg.

def side_len(x, y):
    return [i for i in range(y-x+1,x+y) if abs(i**2-y**2) != x**2]


Solve in Python:
**Debug** a function called calculate that takes 3 values. The first and third values are numbers. The second value is a character. If the character is "+" , "-", "\*", or "/", the function will return the result of the corresponding mathematical function on the two numbers. If the string is not one of the specified characters, the function should return null.

```
calculate(2,"+", 4); //Should return 6
calculate(6,"-", 1.5); //Should return 4.5
calculate(-4,"*", 8); //Should return -32
calculate(49,"/", -7); //Should return -7
calculate(8,"m", 2); //Should return null
calculate(4,"/",0) //should return null
```

Kind of a fork (not steal :)) of [Basic Calculator][1] kata by [TheDoctor][2].

[1]: http://www.codewars.com/kata/basic-calculator/javascript
[2]: http://www.codewars.com/users/528c45adbd9daa384300068d

calculate = lambda a,o,b, m=__import__("operator"): None if o not in "+-*/" or o=='/' and not b else {"+":m.__add__, "-":m.__sub__, "*":m.__mul__, "/":m.__truediv__}[o](a, b)


Solve in Python:
**Getting Familiar:**
LEET: (sometimes written as "1337" or "l33t"), also known as eleet or leetspeak, is another alphabet for the English language that is used mostly on the internet. It uses various combinations of ASCII characters to replace Latinate letters. For example, leet spellings of the word leet include 1337 and l33t; eleet may be spelled 31337 or 3l33t.

GREEK:
The Greek alphabet has been used to write the Greek language since the 8th century BC. It was derived from the earlier Phoenician alphabet, and was the first alphabetic script to have distinct letters for vowels as well as consonants. It is the ancestor of the Latin and Cyrillic scripts.Apart from its use in writing the Greek language, both in its ancient and its modern forms, the Greek alphabet today also serves as a source of technical symbols and labels in many domains of mathematics, science and other fields.

**Your Task :**

    You have to create a function **GrεεκL33t** which
    takes a string as input and returns it in the form of
    (L33T+Grεεκ)Case.
    Note: The letters which are not being converted in
    (L33T+Grεεκ)Case should be returned in the lowercase.

**(L33T+Grεεκ)Case:**

    A=α (Alpha)      B=β (Beta)      D=δ (Delta)
    E=ε (Epsilon)    I=ι (Iota)      K=κ (Kappa)
    N=η (Eta)        O=θ (Theta)     P=ρ (Rho)
    R=π (Pi)         T=τ (Tau)       U=μ (Mu)
    V=υ (Upsilon)    W=ω (Omega)     X=χ (Chi)
    Y=γ (Gamma)

**Examples:**

    GrεεκL33t("CodeWars") = "cθδεωαπs"
    GrεεκL33t("Kata") = "κατα"

def gr33k_l33t(string):
  return string.lower().translate(str.maketrans('abdeiknoprtuvwxy', 'αβδεικηθρπτμυωχγ'))


Solve in Python:
**Introduction**
 Little Petya very much likes sequences. However, recently he received a sequence as a gift from his mother.
 Petya didn't like it at all! He decided to make a single replacement. After this replacement, Petya would like to the sequence in increasing order.
 He asks himself: What is the lowest possible value I could have got after making the replacement and sorting the sequence?

**About the replacement**
 Choose exactly one element from the sequence and replace it with another integer > 0. You are **not allowed** to replace a number with itself, or to change no number at all.

**Task**
 Find the lowest possible sequence after performing a valid replacement, and sorting the sequence.

**Input:**
 Input contains sequence with `N` integers. All elements of the sequence > 0. The sequence will never be empty.

**Output:**
 Return sequence with `N` integers — which includes the lowest possible values of each sequence element, after the single replacement and sorting has been performed.

**Examples**:
```
([1,2,3,4,5])  =>  [1,1,2,3,4]
([4,2,1,3,5])  =>  [1,1,2,3,4]
([2,3,4,5,6])  =>  [1,2,3,4,5]
([2,2,2])      =>  [1,2,2]
([42])         =>  [1]
```

def sort_number(a):
    a.sort()
    if a==[1]*len(a):
        del a[-1]
        a.append(2)
        return a
    l=[1]
    a.remove(max(a))
    for i in range(len(a)):
        l.append(a[i])
    return l


Solve in Python:
**Principal Diagonal** -- The principal diagonal in a matrix identifies those elements of the matrix running from North-West to South-East.

**Secondary Diagonal** -- the secondary diagonal of a matrix identifies those elements of the matrix running from North-East to South-West.

For example:
```
matrix:             [1, 2, 3]
                    [4, 5, 6]
                    [7, 8, 9]

principal diagonal: [1, 5, 9]
secondary diagonal: [3, 5, 7]

```

## Task
Your task is to find which diagonal is "larger": which diagonal has a bigger sum of their elements.

* If the principal diagonal is larger, return `"Principal Diagonal win!"`
* If the secondary diagonal is larger, return `"Secondary Diagonal win!"`
* If they are equal, return `"Draw!"`

**Note:** You will always receive matrices of the same dimension.

def diagonal(matrix):
    sp, ss = map(sum, zip(*((matrix[x][x], matrix[len(matrix)-1-x][x]) for x in range(len(matrix)))))
    return "Draw!" if ss == sp else "{} Diagonal win!".format("Principal" if sp > ss else "Secondary")


Solve in Python:
**See Also**
* [Traffic Lights - one car](.)
* [Traffic Lights - multiple cars](https://www.codewars.com/kata/5d230e119dd9860028167fa5)

---

# Overview

A character string represents a city road.

Cars travel on the road obeying the traffic lights..

Legend:
* `.` = Road
* `C` = Car
* `G` = GREEN traffic light
* `O` = ORANGE traffic light
* `R` = RED traffic light

Something like this:

C...R............G......

# Rules

## Simulation

At each iteration:

1. the lights change, according to the traffic light rules... then
2. the car moves, obeying the car rules

## Traffic Light Rules

Traffic lights change colour as follows:
* GREEN for `5` time units... then
* ORANGE for `1` time unit... then
* RED for `5` time units....
* ... and repeat the cycle

## Car Rules

* Cars travel left to right on the road, moving 1 character position per time unit

* Cars can move freely until they come to a traffic light. Then:
 * if the light is GREEN they can move forward (temporarily occupying the same cell as the light)
 * if the light is ORANGE then they must stop (if they have already entered the intersection they can continue through)
 * if the light is RED the car must stop until the light turns GREEN again

# Kata Task

Given the initial state of the road, return the states for all iterations of the simiulation.

## Input

* `road` = the road array
* `n` = how many time units to simulate (n >= 0)

## Output

* An array containing the road states at every iteration (including the initial state)
 * Note: If a car occupies the same position as a traffic light then show only the car

## Notes

* There is only one car
* For the initial road state
 * the car is always at the first character position
 * traffic lights are either GREEN or RED, and are at the beginning of their countdown cycles
* There are no reaction delays - when the lights change the car drivers will react immediately!
* If the car goes off the end of the road it just disappears from view
* There will always be some road between adjacent traffic...

def traffic_lights(road, n):
    k, car, res = 'GGGGGORRRRR', 0, []
    for i in range(n+1):
        lights = [k[(k.index(s) + i) % 11] if s in 'ROG' else '.' for s in road]
        if car < len(road) - 1:
            if i: car += lights[car+1] not in 'RO'
            lights[car] = 'C'
        res.append(''.join(lights))
    return res


Solve in Python:
**Step 1:** Create a function called `encode()` to replace all the lowercase vowels in a given string with numbers according to the following pattern:
```
a -> 1
e -> 2
i -> 3
o -> 4
u -> 5
```

For example, `encode("hello")` would return `"h2ll4"`. There is no need to worry about uppercase vowels in this kata.

**Step 2:** Now create a function called `decode()` to turn the numbers back into vowels according to the same pattern shown above.

For example, `decode("h3 th2r2")` would return `"hi there"`.

For the sake of simplicity, you can assume that any numbers passed into the function will correspond to vowels.

def encode(s, t=str.maketrans("aeiou", "12345")):
    return s.translate(t)

def decode(s, t=str.maketrans("12345", "aeiou")):
    return s.translate(t)


Solve in Python:
**Steps**
1. Square the numbers that are greater than zero.
2. Multiply by 3 every third number.
3. Multiply by -1 every fifth number.
4. Return the sum of the sequence.

**Example**
`{ -2, -1, 0, 1, 2 }` returns `-6`
```
1. { -2, -1, 0, 1 * 1, 2 * 2 }
2. { -2, -1, 0 * 3, 1, 4 }
3. { -2, -1, 0, 1, -1 * 4 }
4. -6
```

P.S.: The sequence consists only of integers. And try not to use "for", "while" or "loop" statements.

from itertools import cycle

def calc(lst):
    return sum((a ** 2 if a > 0 else a) * b * c
        for a, b, c in zip(lst, cycle((1, 1, 3)), cycle((1, 1, 1, 1, -1))))


Solve in Python:
**Story**
On some island lives a chameleon population. Chameleons here can be of only one of three colors - red, green and blue. Whenever two chameleons of different colors meet, they can change their colors to a third one (i.e. when red and blue chameleons meet, they can both become green). There is no other way for chameleons to change their color (in particular, when red and blue chameleons meet, they can't become both red, only third color can be assumed).
Chameleons want to become of one certain color. They may plan they meetings to reach that goal. Chameleons want to know, how fast their goal can be achieved (if it can be achieved at all).

**Formal problem**
*Input:*
Color is coded as integer, 0 - red, 1 - green, 2 - blue.
Chameleon starting population is given as an array of three integers, with index corresponding to color (i.e. [2, 5, 3] means 2 red, 5 green and 3 blue chameleons). All numbers are non-negative, their sum is between `1` and `int.MaxValue` (maximal possible value for `int` type, in other languages). Desired color is given as an integer from 0 to 2.
*Output:*
`Kata.Chameleon` should return *minimal* number of meetings required to change all chameleons to a given color, or -1 if it is impossible (for example, if all chameleons are initially of one other color).

**Notes and hints**
-- Some tests use rather big input values. Be effective.
-- There is a strict proof that answer is either -1 or no greater than total number of chameleons (thus, return type `int` is justified). Don't worry about overflow.

**Credits**
Kata based on "Chameleons" puzzle from braingames.ru: http://www.braingames.ru/?path=comments&puzzle=226 (russian, not translated).

def chameleon(chameleons, color):
    (_,a), (_,b), (_,c) = sorted((i==color, v) for i,v in enumerate(chameleons))
    return -1 if not a and not c or (b-a) % 3 else b


Solve in Python:
**The Rub**

You need to make a function that takes an object as an argument, and returns a very similar object but with a special property. The returned object should allow a user to access values by providing only the beginning of the key for the value they want. For example if the given object has a key `idNumber`, you should be able to access its value on the returned object by using a key `idNum` or even simply `id`. `Num` and `Number` shouldn't work because we are only looking for matches at the beginning of a key.

Be aware that you _could_ simply add all these partial keys one by one to the object. However, for the sake of avoiding clutter, we don't want to have a JSON with a bunch of nonsensical keys. Thus, in the random tests there will be a test to check that you did not add or remove any keys from the object passed in or the object returned.

Also, if a key is tested that appears as the beginning of more than one key in the original object (e.g. if the original object had a key `idNumber` and `idString` and we wanted to test the key `id`) then return the value corresponding with whichever key comes first **alphabetically**. (In this case it would be `idNumber`s value because it comes first alphabetically.)

**Example**

```python
o = partial_keys({"abcd": 1})

o['abcd'] == 1 # true
o['abc'] == 1 # true
o['ab'] == 1 # true
o['a'] == 1 # true

o['b'] == 1 # false!
o['b'] == None # true

list(o.keys()) # ['abcd']
```

class partial_keys(dict):
    def __getitem__(self, key):
        keys = sorted(k for k in self.keys() if k.startswith(key))
        if keys: return super().__getitem__(keys[0])


Solve in Python:
**This Kata is intended as a small challenge for my students**

All Star Code Challenge #16

Create a function called noRepeat() that takes a string argument and returns a single letter string of the **first** not repeated character in the entire string.

``` haskell
noRepeat "aabbccdde" `shouldBe` 'e'
noRepeat "wxyz"      `shouldBe` 'w'
noRepeat "testing"   `shouldBe` 'e'
```

Note:
ONLY letters from the english alphabet will be used as input
There will ALWAYS be at least one non-repeating letter in the input string

no_repeat=lambda s: [w for w in s if s.count(w)==1][0]


Solve in Python:
**This Kata is intended as a small challenge for my students**

All Star Code Challenge #18

Create a function called that accepts 2 string arguments and returns an integer of the count of occurrences the 2nd argument is found in the first one.

If no occurrences can be found, a count of 0 should be returned.

Notes:
* The first argument can be an empty string
* The second string argument will always be of length 1

def str_count(strg, letter):
    # Your code here ;)
    return strg.count(letter)


Solve in Python:
**This Kata is intended as a small challenge for my students**

All Star Code Challenge #19

You work for an ad agency and your boss, Bob, loves a catchy slogan. He's always jumbling together "buzz" words until he gets one he likes. You're looking to impress Boss Bob with a function that can do his job for him.

Create a function called sloganMaker() that accepts an array of string "buzz" words. The function returns an array of all possible UNIQUE string permutations of the buzz words (concatonated and separated by spaces).

Your boss is not very bright, so anticipate him using the same "buzz" word more than once, by accident. The function should ignore these duplicate string inputs.

```
sloganMaker(["super", "hot", "guacamole"]);
//[ 'super hot guacamole',
//  'super guacamole hot',
//  'hot super guacamole',
//  'hot guacamole super',
//  'guacamole super hot',
//  'guacamole hot super' ]

sloganMaker(["cool", "pizza", "cool"]); // => [ 'cool pizza', 'pizza cool' ]
```

Note:
There should be NO duplicate strings in the output array

The input array MAY contain duplicate strings, which should STILL result in an output array with all unique strings

An empty string is valid input

```if-not:python,crystal
The order of the permutations in the output array does not matter
```
```if:python,crystal
The order of the output array must match those rules:
1. Generate the permutations in lexicographic order of the original array.
2. keep only the first occurence of a permutation, when duplicates are found.
```


Solve in Python:
**This Kata is intended as a small challenge for my students**

All Star Code Challenge #23

There is a certain multiplayer game where players are assessed at the end of the game for merit. Players are ranked according to an internal scoring system that players don't see.

You've discovered the formula for the scoring system!

Create a function called `scoring()` that takes an array of Player objects and returns an array of player names, in order of descending score (highest score is index 0, 2nd highest is index 1, etc.).

Each player's score is calculated as follows:

1. Each normal kill is worth 100 points
2. Each assist is worth 50 points
3. Each point of damage done is worth .5 points
4. Each point of healing done is worth 1 point
5. The longest kill streak is worth 2^N, where N is the number of kills of the streak
6. Environmental kills are worth 500 points (These are counted separately from normal kills)

For each of the above statistic, a Player object contains a respective "key:value" pairing. All values except the 'name' are integers.

Note:
Assume the input array will ALWAYS have a properly constructed Player object (no missing keys or values)
Names will not contain unusual characters nor repeat (names are unique)
Players with the same score should be sorted by the order they appear in the array
For simplicity, for a kill streak of 0 the kill streak calculation will yield 1 (or 2^(0)) points

values = (("norm_kill", (100).__mul__),
          ("assist", (50).__mul__),
          ("damage", (0.5).__mul__),
          ("healing", (1).__mul__),
          ("streak", (2).__pow__),
          ("env_kill", (500).__mul__))

def score(player):
    return sum(f(player[k]) for k,f in values)

def scoring(array):
    return [player["name"] for player in sorted(array, key=score, reverse=True)]


Solve in Python:
**This Kata is intended as a small challenge for my students**

All Star Code Challenge #29

Your friend Nhoj has dislexia, but can easily read messages if the words are written backwards.
Create a function called `reverseSentence()/reverse_sentence()` that accepts a string argument. The function returns a string of the same length with each word reversed, but still in their original order.

```python
reverse_sentence("Hello !Nhoj Want to have lunch?") # "olleH johN! tnaW ot evah ?hcnul"
```
Note:
A "word" should be considered a string split by a space character, " "
Letter capitalization should be maintained.

def reverse_sentence(sentence):
    return ' '.join(w[::-1] for w in sentence.split())


Solve in Python:
**This Kata is intended as a small challenge for my students**

Create a function, called ``removeVowels`` (or ``remove_vowels``), that takes a string argument and returns that same string with all vowels removed (vowels are "a", "e", "i", "o", "u").

REMOVE_VOWS = str.maketrans('','','aeiou')

def remove_vowels(s):
    return s.translate(REMOVE_VOWS)


Solve in Python:
*Are you a file extension master? Let's find out by checking if Bill's files are images or audio files. Please use regex if available natively for your language.*

You will create 2 string methods:

- **isAudio/is_audio**, matching 1 or + uppercase/lowercase letter(s) (combination possible), with the extension .mp3, .flac, .alac, or .aac.

- **isImage/is_image**, matching 1 or + uppercase/lowercase letter(s) (combination possible), with the extension .jpg, .jpeg, .png, .bmp, or .gif.

*Note that this is not a generic image/audio files checker. It's meant to be a test for Bill's files only. Bill doesn't like punctuation. He doesn't like numbers, neither. Thus, his filenames are letter-only*

**Rules**

1. It should return true or false, simply.
2. File extensions should consist of lowercase letters and numbers only.
3. File names should consist of letters only (uppercase, lowercase, or both)

Good luck!

import re

def is_audio(file_name):
    return bool(re.search(r'^[A-Za-z]+\.(mp3|flac|alac|aac)$', file_name))

def is_img(file_name):
    return bool(re.search(r'^[A-Za-z]+\.(jpg|jpeg|png|bmp|gif)$', file_name))


Solve in Python:
*Based on this Numberphile video: https://www.youtube.com/watch?v=Wim9WJeDTHQ*

---

Multiply all the digits of a nonnegative integer `n` by each other, repeating with the product until a single digit is obtained. The number of steps required is known as the **multiplicative persistence**.

Create a function that calculates the individual results of each step, not including the original number, but including the single digit, and outputs the result as a list/array. If the input is a single digit, return an empty list/array.

## Examples
```
per(1)  = []

per(10) = [0]
// 1*0 = 0

per(69) = [54, 20, 0]
// 6*9 = 54 --> 5*4 = 20 --> 2*0 = 0

per(277777788888899) = [4996238671872, 438939648, 4478976, 338688, 27648, 2688, 768, 336, 54, 20, 0]
// 2*7*7*7*7*7*7*8*8*8*8*8*8*9*9 = 4996238671872 --> 4*9*9*6*2*3*8*6*7*1*8*7*2 = 4478976 --> ...
```

def per(n):
    r = []
    while n>=10:
        p=1
        for i in str(n):
            p=p*int(i)
        r.append(p)
        n = p
    return r


Solve in Python:
*Debug*   function `getSumOfDigits` that takes positive integer to calculate sum of it's digits. Assume that argument is an integer.

### Example
```
123  => 6
223  => 7
1337 => 15
```

def get_sum_of_digits(num):
    return sum(list(map(int, [i for i in str(num)])))


Solve in Python:
*Inspired by the [Fold an Array](https://www.codewars.com/kata/fold-an-array) kata. This one is sort of similar but a little different.*

---

## Task
You will receive an array as parameter that contains 1 or more integers and a number `n`.

Here is a little visualization of the process:

* Step 1: Split the array in two:
```
  [1, 2, 5, 7, 2, 3, 5, 7, 8]
        /            \
[1, 2, 5, 7]    [2, 3, 5, 7, 8]
```

* Step 2: Put the arrays on top of each other:
```
     [1, 2, 5, 7]
[2, 3, 5, 7, 8]
```

* Step 3: Add them together:
```
[2, 4, 7, 12, 15]
```

Repeat the above steps `n` times or until there is only one number left, and then return the array.

## Example

```
Input: arr=[4, 2, 5, 3, 2, 5, 7], n=2

Round 1
-------
step 1: [4, 2, 5]  [3, 2, 5, 7]

step 2:    [4, 2, 5]
        [3, 2, 5, 7]

step 3: [3, 6, 7, 12]

Round 2
-------
step 1: [3, 6]  [7, 12]

step 2:  [3,  6]
         [7, 12]

step 3: [10, 18]

Result: [10, 18]
```

from itertools import starmap
from operator import add

def split_and_add(numbers, n):
    for __ in range(n):
        mid, uneven = divmod(len(numbers), 2)
        numbers = list(starmap(add, zip([0] * uneven + numbers[:mid], numbers[mid:])))
    return numbers


Solve in Python:
*It seemed a good idea at the time...*

# Why I did it?

After a year on **Codewars** I really needed a holiday...

But not wanting to drift backwards in the honour rankings while I was away, I hatched a cunning plan!

# The Cunning Plan

So I borrowed my friend's "Clone Machine" and cloned myself :-)

Now my clone can do my Kata solutions for me and I can relax!

Brilliant!!

Furthermore, at the end of the day my clone can re-clone herself...

Double brilliant!!

I wonder why I didn't think to do this earlier?

So as I left for the airport I gave my clone instructions to:

* do my Kata solutions for me
* feed the cat
* try to keep the house tidy and not eat too much
* sleep
* clone yourself
* repeat same next day

# The Flaw

Well, how was I supposed to know that cloned DNA is faulty?

:-(

Every time they sleep they wake up with decreased ability - they get slower... they get dumber... they are only able to solve 1 less Kata than they could the previous day.

For example, if they can solve 10 Kata today, then tomorrow they can solve only 9 Kata, then 8, 7, 6... Eventually they can't do much more than sit around all day playing video games.

And (unlike me), when the clone cannot solve any more Kata they are no longer clever enough to operate the clone machine either!

# The Return Home

I suspected something was wrong when I noticed my **Codewars** honour had stopped rising.

I made a hasty return home...

...and found 100s of clones scattered through the house. Mostly they sit harmlessly mumbling to themselves. The largest group have made a kind of nest in my loungeroom where they sit catatonic in front of the PlayStation.

The whole place needs fumigating.

The fridge and pantry are empty.

And I can't find the cat.

# Kata Task

Write a method to predict the final outcome where:

Input:

* `kata-per-day` is the number of Kata I can solve per day

Output:

* ```[number-of-clones, number-of-kata-solved-by-clones]```

def clonewars(k):
    return [2**max(k-1,0),2**(k+1)-k-2]


Solve in Python:
*Recreation of [Project Euler problem #6](https://projecteuler.net/problem=6)*

Find the difference between the sum of the squares of the first `n` natural numbers `(1 <= n <= 100)` and the square of their sum.

## Example
For example, when `n = 10`:

* The square of the sum of the numbers is:

  (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10)^(2) = 55^(2) = 3025

* The sum of the squares of the numbers is:

 1^(2) + 2^(2) + 3^(2) + 4^(2) + 5^(2) + 6^(2) + 7^(2) + 8^(2) + 9^(2) + 10^(2) = 385

Hence the difference between square of the sum of the first ten natural numbers and the sum of the squares of those numbes is: 3025 - 385 = 2640

def difference_of_squares(n):
    sum_square=0
    sum_numbers=0
    for i in range (1,n+1):
        sum_square+=(i**2)
    for i in range (1,n+1):
        sum_numbers+=i
    squared=(sum_numbers)**2
    return(squared-sum_square)


Solve in Python:
*SCHEDULE YOUR DA(RRA)Y*

The best way to have a productive day is to plan out your work schedule. Given the following three inputs, please create an an array of time alloted to work, broken up with time alloted with breaks:

Input 1: Hours - Number of hours available to you to get your work done!
Input 2: Tasks - How many tasks you have to do througout the day
Input 3: Duration (minutes)- How long each of your tasks will take to complete
Criteria to bear in mind:
- Your schedule should start with work and end with work.
- It should also be in minutes, rounded to the nearest whole minute.
- If your work is going to take more time than you have, return "You're not sleeping tonight!"
Example:

```python
day_plan(8, 5, 30) == [ 30, 82, 30, 82, 30, 82, 30, 82, 30 ]
day_plan(3, 5, 60) == "You're not sleeping tonight!"
```

day_plan=lambda h,t,d:t*d>h*60and"You're not sleeping tonight!"or([(h*60-t*d)//(t-1+1e-9),d]*t)[1:]


Solve in Python:
*Shamelessly stolen from Here :)*

Your server has sixteen memory banks; each memory bank can hold any number of blocks. You must write a routine to balance the blocks between the memory banks.

The reallocation routine operates in cycles. In each cycle, it finds the memory bank with the most blocks (ties won by the lowest-numbered memory bank) and redistributes those blocks among the banks. To do this, it removes all of the blocks from the selected bank, then moves to the next (by index) memory bank and inserts one of the blocks. It continues doing this until it runs out of blocks; if it reaches the last memory bank, it wraps around to the first one.

We need to know how many redistributions can be done before a blocks-in-banks configuration is produced that has been seen before.

For example, imagine a scenario with only four memory banks:

* The banks start with 0, 2, 7, and 0 blocks (`[0,2,7,0]`). The third bank has the most blocks (7), so it is chosen for redistribution.
* Starting with the next bank (the fourth bank) and then continuing one block at a time, the 7 blocks are spread out over the memory banks. The fourth, first, and second banks get two blocks each, and the third bank gets one back. The final result looks like this: 2 4 1 2.
* Next, the second bank is chosen because it contains the most blocks (four). Because there are four memory banks, each gets one block. The result is: 3 1 2 3.
* Now, there is a tie between the first and fourth memory banks, both of which have three blocks. The first bank wins the tie, and its three blocks are distributed evenly over the other three banks, leaving it with none: 0 2 3 4.
* The fourth bank is chosen, and its four blocks are distributed such that each of the four banks receives one: 1 3 4 1.
* The third bank is chosen, and the same thing happens: 2 4 1 2.
At this point, we've reached a state we've seen before: 2 4 1 2 was already seen. The infinite loop is detected after the fifth block redistribution cycle, and so the answer in this example is 5.

Return...

from operator import itemgetter

def mem_alloc(banks):
    cache = set()
    count = 0
    while tuple(banks) not in cache:
        cache.add(tuple(banks))
        count += 1
        ind, val = max(enumerate(banks), key=itemgetter(1))
        banks[ind] = 0
        for i in range(val):
            ind += 1
            banks[ind % len(banks)] += 1
    return count


Solve in Python:
*This is my first Kata in the Ciphers series. This series is meant to test our coding knowledge.*

## Ciphers #1 - The 01 Cipher
This cipher doesn't exist, I just created it by myself. It can't actually be used, as there isn't a way to decode it. It's a hash. Multiple sentences may also have the same result.

## How this cipher works
It looks at the letter, and sees it's index in the alphabet, the alphabet being `a-z`, if you didn't know. If it is odd, it is replaced with `1`, if it's even, its replaced with `0`. Note that the index should start from 0. Also, if the character isn't a letter, it remains the same.

## Example

This is because `H`'s index is `7`, which is odd, so it is replaced by `1`, and so on.

Have fun (en)coding!

def encode(s):
    return ''.join( str(1 - ord(c)%2) if c.isalpha() else c for c in s )


Solve in Python:
*This is the advanced version of the
[Minimum and Maximum Product of k Elements](https://www.codewars.com/kata/minimum-and-maximum-product-of-k-elements/) kata.*

---

Given a list of **integers** and a positive integer `k` (> 0), find the minimum and maximum possible product of `k` elements taken from the list.

If you cannot take enough elements from the list, return `None`/`nil`.

## Examples

```python
numbers = [1, -2, -3, 4, 6, 7]

k = 1  ==>  -3, 7
k = 2  ==>  -21, 42    # -3*7, 6*7
k = 3  ==>  -126, 168  # -3*6*7, 4*6*7
k = 7  ==>  None       # there are only 6 elements in the list
```

Note: the test lists can contain up to 500 elements, so a naive approach will not work.

---

## My other katas

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

#### *Translations are welcome!*

def find_min_max_product(arr, k):
    if k > len(arr): return None
    arr.sort(key=abs, reverse=True)
    neg, pos, prod = None, None, 1
    for i in range(k):
        if arr[i] < 0: neg = arr[i]
        if arr[i] > 0: pos = arr[i]
        prod *= arr[i]
    neg1, pos1 = None, None
    for i in range(k, len(arr)):
        if not neg1 and arr[i] < 0: neg1 = arr[i]
        if not pos1 and arr[i] > 0: pos1 = arr[i]
        if neg1 and pos1: break
    candidates = [prod]
    if neg and pos1: candidates.append(prod // neg * pos1)
    if pos and neg1: candidates.append(prod // pos * neg1)
    if not (neg and neg1 and pos and pos1):
        prod = 1
        for i in range(-k, 0): prod *= arr[i]
        candidates.append(prod)
    return min(candidates), max(candidates)


Solve in Python:
*This is the advanced version of the [Total Primes](https://www.codewars.com/kata/total-primes/) kata.*

---

The number `23` is the smallest prime that can be "cut" into **multiple** primes: `2, 3`. Another such prime is `6173`, which can be cut into `61, 73` or `617, 3` or `61, 7, 3` (all primes). A third one is `557` which can be sliced into `5, 5, 7`. Let's call these numbers **total primes**.

Notes:
* one-digit primes are excluded by definition;
* leading zeros are also excluded: e.g. splitting `307` into `3, 07` is **not** valid

## Task

Complete the function that takes a range `[a..b]` (both limits included) and returns the total primes within that range (`a ≤ total primes ≤ b`).

The tests go up to 10^(6).
~~~if:python
For your convenience, a list of primes up to 10^(6) is preloaded, called `PRIMES`.
~~~

## Examples
```
(0, 100)  ==>  [23, 37, 53, 73]

(500, 600) ==> [523, 541, 547, 557, 571, 577, 593]
```
Happy coding!

---

## My other katas

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

#### *Translations are welcome!*

import numpy as np
from itertools import accumulate
def sieve_primes(n):
    sieve = np.ones(n // 2, dtype = np.bool)
    limit = 1 + int(n ** 0.5)

    for a in range(3, limit, 2):
        if sieve[a // 2]:
            sieve[a * a // 2::a] = False

    prime_indexes = 2 * np.nonzero(sieve)[0].astype(int) + 1
    prime_indexes[0] = 2
    return set(map(str, prime_indexes))

primes = sieve_primes(10 ** 6)

def all_primes(s):
    if int(s) < 10:
        return s in primes
    for n in accumulate(s[:-1]):
        if n in primes:
            m = s[len(n):]
            if m in primes or all_primes(m):
                return True

def total_primes(a, b):
    return [int(a) for a in map(str, range(max(10, a), b + 1)) if a in primes and all_primes(a)]


Solve in Python:
*This is the second Kata in the Ciphers series. This series is meant to test our coding knowledge.*

## Ciphers #2 - The reversed Cipher
This is a lame method I use to write things such that my friends don't understand. It's still fairly readable if you think about it.

## How this cipher works
First, you need to reverse the string. Then, the last character in the original string (the first character in the reversed string) needs to be moved to the back. Words will be separated by spaces, and punctuation marks can be counted as part of the word.

## Example

This is because `"Hello"` reversed is `"olleH"` and `"o"` is moved to the back, and so on. The exclamation mark is considered to be part of the word `"World"`.

Have fun (en)coding!


Solve in Python:
*This kata is based on [Project Euler Problem #349](https://projecteuler.net/problem=349). You may want to start with solving [this kata](https://www.codewars.com/kata/langtons-ant) first.*

---

[Langton's ant](https://en.wikipedia.org/wiki/Langton%27s_ant) moves on a regular grid of squares that are coloured either black or white.
The ant is always oriented in one of the cardinal directions (left, right, up or down) and moves  according to the following rules:
- if it is on a black square, it flips the colour of the square to white, rotates 90 degrees counterclockwise and moves forward one square.
- if it is on a white square, it flips the colour of the square to black, rotates 90 degrees clockwise and moves forward one square.

Starting with a grid that is **entirely white**, how many squares are black after `n` moves of the ant?

**Note:** `n` will go as high as 10^(20)

---

## My other katas

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

#### *Translations are welcome!*

def langtons_ant(n):
    grid = [[0]]
    column = 0
    row = 0
    direction = 0
    move = {
        0: (-1, 0),
        1: ( 0, 1),
        2: ( 1, 0),
        3: ( 0,-1),
        }
    rows = len(grid)
    cols = len(grid[0])
    ap = (row, column)
    dir = direction
    n_black = 0

    max_simple_range = 11000
    n_black_highway_ref = []
    ref = 0

    for i in range(1, n + 1):
        if (grid[ap[0]][ap[1]]) == 1:
            grid[ap[0]][ap[1]] = 0
            dir = (dir + 1) % 4
            n_black -= 1
        else:
            grid[ap[0]][ap[1]] = 1
            dir = (dir - 1) % 4
            n_black += 1
        ap = (ap[0] + move[dir][0], ap[1] + move[dir][1])

        if ap[0] >= rows:
            grid = grid + ([[0]*cols])
            rows += 1
        elif ap[0] < 0:
            grid = ([[0]*cols]) + grid
            rows += 1
            ap = (0, ap[1])

        if ap[1] >= cols:
            for j, r in enumerate(grid):
                grid[j] = r + [0]
            cols += 1
        elif ap[1] < 0:
            for j, r in enumerate(grid):
                grid[j] = [0] + r
            cols += 1

            ap = (ap[0], 0)

        if i >= max_simple_range:
            if i == max_simple_range:
                ref = n_black
            n_black_highway_ref.append(n_black - ref)

            if i == (max_simple_range + 104):
                break

    if n > (max_simple_range + 104):
        n_black += (n_black_highway_ref[-1] * (((n - max_simple_range) // 104) - 1))
        n_black += (n_black_highway_ref[((n - max_simple_range) % 104)])
    return n_black


Solve in Python:
*This kata is based on [Project Euler Problem 539](https://projecteuler.net/problem=539)*

##Object

Find the last number between 1 and `n` (inclusive) that survives the elimination process

####How It Works

Start with the first number on the left then remove every other number moving right until you reach the the end, then from the numbers remaining start with the first number on the right and remove every other number moving left, repeat the process alternating between left and right until only one number remains which you return as the "last man standing"

##Example

    given an input of `9` our set of numbers is `1 2 3 4 5 6 7 8 9`

    start by removing from the left    2   4   6   8
                                     1   3   5   7   9

    then from the right                2       6
                                           4       8

    then the left again                        6
                                       2

    until we end with `6` as the last man standing

**Note:** due to the randomness of the tests it is possible that you will get unlucky and a few of the tests will be really large, so try submitting 2 or 3 times.

As allways any feedback would be much appreciated

def last_man_standing(n):
    dir, lst = -1, range(2,n+1,2)
    while len(lst) != 1:
        lst = lst[len(lst)%2 or dir == 1 ::2]
        dir = -dir
    return lst[0]


Solve in Python:
*This kata is inspired by [Project Euler Problem #387](https://projecteuler.net/problem=387)*

---

A [Harshad number](https://en.wikipedia.org/wiki/Harshad_number) (or Niven number) is a number that is divisible by the sum of its digits. A *right truncatable Harshad number* is any Harshad number that, when recursively right-truncated, results in a Harshad number at each truncation. By definition, 1-digit numbers are **not** right truncatable Harshad numbers.

For example `201` (which is a Harshad number) yields `20`, then `2` when right-truncated, which are all Harshad numbers. Thus `201` is a *right truncatable Harshad number*.

## Your task

Given a range of numbers (`(a, b)`, both included), return the list of right truncatable Harshad numbers in this range.

```if-not:javascript
Note: there are `500` random tests, with 0 <= `a` <= `b` <= 10^(16)
```
```if:javascript
Note: there are `500` random tests, with `0 <= a <= b <= Number.MAX_SAFE_INTEGER`
```

## Examples

```
0, 20        -->  [10, 12, 18, 20]
30, 100      -->  [30, 36, 40, 42, 45, 48, 50, 54, 60, 63, 70, 72, 80, 81, 84, 90, 100]
90, 200      -->  [90, 100, 102, 108, 120, 126, 180, 200]
200, 210     -->  [200, 201, 204, 207, 209, 210]
1000, 2000   -->  [1000, 1002, 1008, 1020, 1026, 1080, 1088, 1200, 1204, 1206, 1260, 1800, 2000]
2200, 2300   -->  []
9000002182976, 9000195371842  -->  [9000004000000, 9000004000008]
```

---

## My other katas

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

#### *Translations are welcome!*

def gen(n):
    if n >= 10**16: return
    for i in range(10):
        x = 10*n + i
        if x % sum(map(int, str(x))): continue
        yield x
        for y in gen(x): yield y
L = sorted(x for n in range(1, 10) for x in gen(n))

from bisect import bisect_left as bl, bisect_right as br
def rthn_between(a, b):
    return L[bl(L, a):br(L, b)]


Solve in Python:
*Translations appreciated*

# Overview

Your task is to decode a qr code.
You get the qr code as 2 dimensional array, filled with numbers. 1 is for a black field and 0 for a white field.
It is always a qr code of version 1 (21*21), it is always using mask 0 ((x+y)%2), it is always using byte mode and it always has error correction level H (up to 30%). The qr code won't be positioned wrong and there won't be any squares for positioning exept the three big ones in the corners.

You should return the message inside the qr code as string.
The QR Code will always be valid and be of `version 1`, meaning the decoded message will never be more than 8 characters long. The way to decode a complete QR-code is explained below, but keep in mind that in this kata, you'll only have to decode the parts in green in the picture below:

# Input/ouput

* Input: 2D array of `0` (white) and `1` (black) values
* Output: the decoded message, according to the process described below.

```python
qrcode = [[ 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1 ],
          [ 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1 ],
          [ 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1 ],
          [ 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1 ],
          [ 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1 ],
          [ 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1 ],
          [ 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1 ],
          [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
          [ 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 ],
          [ 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1 ],
          [ 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1 ],
          [ 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0 ],
          [ 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0 ],
          [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0,...

def scanner(qrc):
    bits = ''.join( str(qrc[x][y] ^ ((x+y)%2==0)) for x,y in ticTocGen())
    size = int(bits[4:12],2)
    return ''.join( chr(int(bits[i:i+8],2)) for i in range(12,12+8*size,8))

def ticTocGen():
    x,y,dx = 20,20,-1
    while y>13:
        yield from ( (x,y-dy) for dy in range(2) )
        x+=dx
        if x==8 or x>20:
            dx *= -1
            y  -= 2
            x   = x==8 and 9 or 20


Solve in Python:
*Translations appreciated*

## Background information

The Hamming Code is used to correct errors, so-called bit flips, in data transmissions. Later in the description follows a detailed explanation of how it works.
In this Kata we will implement the Hamming Code with bit length 3, this has some advantages and disadvantages:
- ✓ Compared to other versions of hamming code, we can correct more mistakes
- ✓ It's simple to implement
- x  The size of the input triples

## Task 1: Encode function:

First of all we have to implement the encode function, which is pretty easy, just follow the steps below.

Steps:
1. convert every letter of our text to ASCII value
2. convert ASCII value to 8-bit binary string
3. replace every "0" with "000" and every "1" with "111"

Let's do an example:

We have to convert the string ```hey``` to hamming code sequence.

1. First convert it to ASCII values:

```104``` for ```h```, ```101``` for ```e``` and ```121``` for ```y```.

2. Now we convert the ASCII values to a 8-bit binary string:

```104``` -> ```01101000```, ```101``` -> ```01100101``` and ```121``` -> ```01111001```

if we concat the binarys we get ```011010000110010101111001```

3. Now we replace every "0" with "000" and every "1" with "111":

```011010000110010101111001``` -> ```000111111000111000000000000111111000000111000111000111111111111000000111```

That's it good job!

## Task 2: Decode function:

Now we have to check if there happened any mistakes and correct them.
Errors will only be a bit flip and not a loose of bits, so the length of the input string is always divisible by 3.

example:
- 111 --> 101  this can and will happen
- 111 --> 11   this won't happen

The length of the input string is also always divsible by 24 so that you can convert it to an ASCII value.

Steps:
1. Split the string of 0 and 1 in groups of three characters example: "000", "111"
2. Check if an error occured:
 If no error occured the group is "000" or "111", then replace "000" with "0" and "111" with 1
 If an error occured the group...

def encode(string):
    return ''.join(map('{:08b}'.format, string.encode())).replace('0', '000').replace('1', '111')

def decode(bits):
    bytes_ = ('01'['11' in a+b+c+a] for a,b,c in zip(* [iter(bits)] * 3))
    return bytes(int(''.join(b), 2) for b in zip(* [iter(bytes_)] * 8)).decode()


Solve in Python:
*You are a composer who just wrote an awesome piece of music. Now it's time to present it to a band that will perform your piece, but there's a problem! The singers vocal range doesn't stretch as your piece requires, and you have to transpose the whole piece.*

# Your task
Given a list of notes (represented as strings) and an interval, output a list of transposed notes in *sharp* notation.

**Input notes may be represented both in flat and sharp notations (more on that below).**

**For this kata, assume that input is always valid and the song is *at least* 1 note long.**

**Assume that interval is an integer between -12 and 12.**

# Short intro to musical notation
Transposing a single note means shifting its value by a certain interval.

The notes are as following:

    A, A#, B, C, C#, D, D#, E, F, F#, G, G#.

This is using *sharp* notation, where '#' after a note means that it is one step higher than the note. So A# is one step higher than A.

An alternative to sharp notation is the *flat* notation:

    A, Bb, B, C, Db, D, Eb, E, F, Gb, G, Ab.

The 'b' after a note means that it is one step lower than the note.

# Examples

    ['G'] -> 5 steps -> ['C']
    ['Db'] -> -4 steps -> ['A#']
    ['E', 'F'] -> 1 step -> ['F', 'F#']

table = "A Bb B C Db D Eb E F Gb G Ab".split()
table += "A A# B C C# D D# E F F# G G#".split() * 3

def transpose(song, interval):
    return [table[table.index(note) + interval%12 + 12] for note in song]


Solve in Python:
*`This kata is a tribute/fanwork to the TV-show: Supernatural`*

Balls!

Those wayward Winchester boys are in trouble again, hunting something down in New Orleans.
You are Bobby Singer, you know how "idjits" they can be, so you have to prepare.
They will call you any minute with the race of the thing, and you want to answer as soon as possible. By answer, I mean: tell them how to kill, or fight it.

You have something like a database (more like drunken doodling) to help them:

- werewolf           : Silver knife or bullet to the heart
- vampire            : Behead it with a machete
- wendigo            : Burn it to death
- shapeshifter       : Silver knife or bullet to the heart
- angel              : Use the angelic blade
- demon              : Use Ruby's knife, or some Jesus-juice
- ghost              : Salt and iron, and don't forget to burn the corpse
- dragon             : You have to find the excalibur for that
- djinn              : Stab it with silver knife dipped in a lamb's blood
- pagan god          : It depends on which one it is
- leviathan          : Use some Borax, then kill Dick
- ghoul              : Behead it
- jefferson starship : Behead it with a silver blade
- reaper             : If it's nasty, you should gank who controls it
- rugaru             : Burn it alive
- skinwalker         : A silver bullet will do it
- phoenix            : Use the colt
- witch              : They are humans
- else               : I have friggin no idea yet

You can access the database as `drunkenDoodling`/`drunken_doodling`/`DrunkenDoodling` depending on your language.

---

So a call would go down like this:

The guys call you:
```bob('rugaru')```

...and you reply (return) with the info, and your signature saying of yours!
```Burn it alive, idjits!```

database = {
    "werewolf" : "Silver knife or bullet to the heart",
    "vampire" :  "Behead it with a machete",
    "wendigo" :  "Burn it to death",
    "shapeshifter" : "Silver knife or bullet to the heart",
    "angel" :  "Use the angelic blade",
    "demon" :  "Use Ruby's knife, or some Jesus-juice",
    "ghost" :  "Salt and iron, and don't forget to burn the corpse",
    "dragon" :  "You have to find the excalibur for that",
    "djinn" :  "Stab it with silver knife dipped in a lamb's blood",
    "pagan god" :  "It depends on which one it is",
    "leviathan" :  "Use some Borax, then kill Dick",
    "ghoul" : "Behead it",
    "jefferson starship": "Behead it with a silver blade",
    "reaper": "If it's nasty, you should gank who controls it",
    "rugaru": "Burn it alive",
    "skinwalker": "A silver bullet will do it",
    "phoenix": "Use the colt",
    "witch": "They are humans",
}
def bob(what):
    default = "I have friggin no idea yet"
    return database.get(what, default) + ", idjits!"


Solve in Python:
- Input: Integer `n`
- Output: String

Example:

`a(4)` prints as
```
   A
  A A
 A A A
A     A
```

`a(8)` prints as
```
       A
      A A
     A   A
    A     A
   A A A A A
  A         A
 A           A
A             A
```

`a(12)` prints as
```
           A
          A A
         A   A
        A     A
       A       A
      A         A
     A A A A A A A
    A             A
   A               A
  A                 A
 A                   A
A                     A
```
Note:

- Each line's length is `2n - 1`
- Each line should be concatenate by line break `"\n"`
- If `n` is less than `4`, it should return `""`
- If `n` is odd, `a(n) = a(n - 1)`, eg `a(5) == a(4); a(9) == a(8)`

def a(n):
    if n<4: return ''
    n-=n%2
    l=2*n-1
    return '\n'.join((' '.join(['A']*(i+1)) if i*2==n else ''.join('A' if j in (0,i*2) else ' ' for j in range(i*2+1))).center(l) for i in range(n))


Solve in Python:
- Kids drink toddy.
- Teens drink coke.
- Young adults drink beer.
- Adults drink whisky.

Make a function that receive age, and return what they drink.

**Rules:**

- Children under 14 old.
- Teens under 18 old.
- Young under 21 old.
- Adults have 21 or more.

**Examples:**

```python
people_with_age_drink(13) == "drink toddy"
people_with_age_drink(17) == "drink coke"
people_with_age_drink(18) == "drink beer"
people_with_age_drink(20) == "drink beer"
people_with_age_drink(30) == "drink whisky"
```

def people_with_age_drink(age):
    if age < 14:
        return "drink toddy"
    if age<18 and age>13:
        return "drink coke"
    if age<21 and age>=18:
        return "drink beer"
    if age>=21:
        return "drink whisky"


Solve in Python:
---

# Hint

This Kata is an extension of the earlier ones in this series. Completing those first will make this task easier.

# Background

My TV remote control has arrow buttons and an `OK` button.

I can use these to move a "cursor" on a logical screen keyboard to type words...

# Keyboard

The screen "keyboard" layouts look like this

  #tvkb {
    width : 400px;
    border: 5px solid gray; border-collapse: collapse;
  }
  #tvkb td {
    color : orange;
    background-color : black;
    text-align : center;
    border: 3px solid gray; border-collapse: collapse;
  }
  #legend {
    width : 400px;
    border: 1px solid gray; border-collapse: collapse;
  }
  #legend td {
    text-align : center;
    border: 1px solid gray; border-collapse: collapse;
  }

Keypad Mode 1 = alpha-numeric (lowercase)
Keypad Mode 3 = symbols

abcde123
fghij456
klmno789
pqrst.@0
uvwxyz_/
aA#SP

^~?!'"()
-:;+&%*=
<>€£$¥¤\
[]{},.@§
#¿¡_/
aA#SP

* `aA#` is the SHIFT key. Pressing this key cycles through THREE keypad modes.
 * **Mode 1** = alpha-numeric keypad with lowercase alpha (as depicted above)
 * **Mode 2** = alpha-numeric keypad with UPPERCASE alpha
 * **Mode 3** = symbolic keypad (as depicted above)

* `SP` is the space character
* The other (solid fill) keys in the bottom row have no function

## Special Symbols

For your convenience, here are Unicode values for the less obvious symbols of the **Mode 3** keypad

¡ = U-00A1£ = U-00A3¤ = U-00A4¥ = U-00A5
§ = U-00A7¿ = U-00BF€ = U-20AC

# Kata task

How many button presses on my remote are required to type the given `words`?

## Notes

* The cursor always starts on the letter `a` (top left)
* The inital keypad layout is **Mode 1**
* Remember to also press `OK` to "accept" each letter
* Take the shortest route from one letter to the next
* The cursor wraps, so as it moves off one edge it will reappear on the opposite edge
* Although the blank keys have no function, you may navigate through them if you want to
* Spaces may occur anywhere in the `words` string
*...

H, W     = 6, 8
KEYBOARD = [ "abcde123fghij456klmno789pqrst.@0uvwxyz_/\u000e ",
             "ABCDE123FGHIJ456KLMNO789PQRST.@0UVWXYZ_/\u000e ",
             "^~?!'\"()-:;+&%*=<>€£$¥¤\\[]{},.@§#¿¡\u000e\u000e\u000e_/\u000e "]
MAP      = [ {c: (i//W, i%W) for i,c in enumerate(KEYBOARD[x])} for x in range(len(KEYBOARD)) ]

def manhattan(*pts):
    dxy = [abs(z2-z1) for z1,z2 in zip(*pts)]
    return 1 + sum( min(dz, Z-dz) for dz,Z in zip(dxy, (H,W)) )

def tv_remote(words):
    cnt, mod, was = 0, 0, 'a'
    for c in words:
        while c not in KEYBOARD[mod]:
            cnt += manhattan(MAP[mod][was], MAP[mod]['\u000e'])
            was = '\u000e'
            mod = (mod+1) % 3
        cnt += manhattan(MAP[mod][was], MAP[mod][c])
        was  = c
    return cnt


Solve in Python:
---

# Story

The Pied Piper has been enlisted to play his magical tune and coax all the rats out of town.

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

# Kata Task

How many deaf rats are there?

# Legend

* ```P``` = The Pied Piper
* ```O~``` = Rat going left
* ```~O``` = Rat going right

# Example

* ex1 ```~O~O~O~O P``` has 0 deaf rats

* ex2 ```P O~ O~ ~O O~``` has 1 deaf rat

* ex3 ```~O~O~O~OP~O~OO~``` has 2 deaf rats

---

# Series

* [The deaf rats of Hamelin (2D)](https://www.codewars.com/kata/the-deaf-rats-of-hamelin-2d)

import re

def count_deaf_rats(town):
    town = re.sub("(~O|O~)", lambda m: ">" if m.group(1) == "~O" else "<", town)
    left, right = town.split("P")
    return left.count("<") + right.count(">")


Solve in Python:
----
Vampire Numbers
----

Our loose definition of [Vampire Numbers](http://en.wikipedia.org/wiki/Vampire_number) can be described as follows:

```python
6 * 21 = 126
# 6 and 21 would be valid 'fangs' for a vampire number as the
# digits 6, 1, and 2 are present in both the product and multiplicands

10 * 11 = 110
# 110 is not a vampire number since there are three 1's in the
# multiplicands, but only two 1's in the product
```

Create a function that can receive two 'fangs' and determine if the product of the two is a valid vampire number.

def vampire_test(x, y):
  return "".join(sorted(list(str(x) + str(y)))) == "".join(sorted(list(str(x * y))))


Solve in Python:
-----
ARRAY AND DISTINCT ELEMENTS
-----

Chef is multitalented but he mistakenly took part in 2 contest which will take place
at the same time. So while chef is busy at one cooking contest, he wants you to
take part in coding contest. Chef wants u to solve this program for him.

You have been given an array of size n. You have to calculate a subarray of size k
with maximum sum having distinct elements same as original array.

-----Input Format-----

First line contains no. of test cases. Second line contains n and k. Third line
contains array of n integers.

-----Output-----

Print maximum possible sum as stated in question

-----Example Text Case-----
Input:

1
10 6
8 8 3 5 3 8 5 7 7 7

Output:
37

x=int(input())
for i in range(x):
 n,k=map(int,input().split())
 l=list(map(int,input().split()))
 j=0
 m=0
 while j+k<=n:
  #print(set(l[j:j+k]),set(l))
  if m<sum(l[j:j+k]) and set(l[j:j+k])==set(l):
   m=sum(l[j:j+k])
  j+=1
 print(m)


Solve in Python:
-----
CHEF N TIMINGS
-----

One day chef was working with some random numbers. Then he found something
interesting. He observed that no 240, 567, 9999 and 122 and called these numbers
nice as the digits in numbers are in increasing order. Also he called 434, 452, 900
are not nice as digits are in decreasing order

Now you are given a no and chef
wants you to find out largest "nice" integer which is smaller than or equal to the
given integer.

-----Constraints-----

1< t < 1000

1< N < 10^18

-----Input Format-----

First line contains no. of test cases t. Then t test cases follow. Each test case
contain a integer n.

-----Output-----

Output a integer for each test case in a new line which is largest nice
integer smaller or equal to the given integer.

-----Example Text Case-----
Input:

1
132

Output:

129

# cook your dish here
def check(n):
 l=list(map(int,str(n)))
 t=len(l)
 p=t-1
 for i in range(t-1,0,-1):
  if l[i]<l[i-1]:
   l[i-1]-=1
   p=i-1

 for i in range(p+1,t):
  l[i]=9
 return int(''.join(map(str,l)))

try:
 for _ in range(int(input())):
  n=int(input())
  print(check(n))
except EOFError as e:pass


Solve in Python:
-----
HALLOWEEN EVE
-----

In some other world, today is Halloween Eve.There are N trees planted in Mr. Smith’s
garden. The height of the i-th tree (1≤i≤N) is h i meters.
He decides to choose K trees from these trees and decorate them with electric lights.
To make the scenery more beautiful, the heights of the decorated trees should be as
close to each other as possible.

More specifically, let the height of the tallest decorated tree be hmax meters, and the
height of the shortest decorated tree be hmin meters.
The smaller the value hmax−hmin is, the better. What is the minimum possible value of
hmax−hmin?

-----Constraints-----

	    2≤K< N ≤105

1≤hi≤109

hi is an integer

-----Input Format-----

Input is given from Standard Input in the following format:

N K

h1

h2

:

hN

-----Output-----

Print the minimum possible value of hmax−hmin.

-----Example Text Case-----
Input:

5 3
10
15
11
14
12

Output:

2

Explanation

If we decorate the first, third and fifth trees, hmax=12,hmin=10 so hmax−hmin=2. This is
optimal.

n,k=map(int,input().split())
l=[]
l.append(-1)
for i in range(n):
    l.append(int(input()))
l.sort()
m=l[k]-l[1]
for i in range(2,n-k):
    if(l[i+k-1]-l[i]<m):
        m=l[i+k-1]-l[i]
print(m)


Solve in Python:
-----
RANJANA QUIZ
-----

Prof. Ranjana decided to conduct a quiz in her class. She divided all the students of her
class into groups of three. Consider that no student was left out after the division. She gave
different sets of questions to every group. A set is said to be unique if there is no other team that
received the same number of maths, science and english questions. In every set, maximum
questions for each group were related to maths, then science, and the least number of
questions were related to English. Total number of questions given to each team can be
different.

After the test, the CR of the class asked every team to report the number of questions
they got on each subject. The CR wants to know the number of unique sets of questions that
were given to the teams, the problem is that all the students have just submitted the number of
questions of each subject but in no particular order. Help the CR to find the number of unique
sets

-----Input Format-----

Line 1 contains the number of teams ‘n’. In the next n lines, each line contains three space separated integers,i.e, the number of questions of each subject(in no particular order).
employee

-----Output-----

Print the number of unique sets

-----Example Text Case-----
Input:

5
6 5 4
2 3 7
4 6 5
7 2 3
5 3 1

Output:
1

# cook your dish here
n=int(input())
lst=[]
unique=0
for _ in range(n):
    a=list(map(int,input().split()))
    a.sort(reverse=True)
    lst.append(a)
for ele in lst:
    if(lst.count(ele)==1):
        unique+=1
print(unique)