Solve in Python:
## Your Story
"A *piano* in the home meant something." - *Fried Green Tomatoes at the Whistle Stop Cafe*

You've just realized a childhood dream by getting a beautiful and beautiful-sounding upright piano from a friend who was leaving the country. You immediately started doing things like playing "Heart and Soul" over and over again, using one finger to pick out any melody that came into your head, requesting some sheet music books from the library, signing up for some MOOCs like Developing Your Musicianship, and wondering if you will think of any good ideas for writing piano-related katas and apps.

Now you're doing an exercise where you play the very first (leftmost, lowest in pitch) key on the 88-key keyboard, which (as shown below) is white, with the little finger on your left hand, then the second key, which is black, with the ring finger on your left hand, then the third key, which is white, with the middle finger on your left hand, then the fourth key, also white, with your left index finger, and then the fifth key, which is black, with your left thumb. Then you play the sixth key, which is white, with your right thumb, and continue on playing the seventh, eighth, ninth, and tenth keys with the other four fingers of your right hand. Then for the eleventh key you go back to your left little finger, and so on. Once you get to the rightmost/highest, 88th, key, you start all over again with your left little finger on the first key. Your thought is that this will help you to learn to move smoothly and with uniform pressure on the keys from each finger to the next and back and forth between hands.

You're not saying the names of the notes while you're doing this, but instead just counting each key press out loud (not starting again at 1 after 88, but continuing on to 89 and so forth) to try to keep a steady rhythm going and to see how far you can get before messing up. You move gracefully and with flourishes, and between screwups you hear, see, and feel that you are part of some great repeating...


Solve in Python:
## Your story
You've always loved both Fizz Buzz katas and cuckoo clocks, and when you walked by a garage sale and saw an ornate cuckoo clock with a missing pendulum, and a "Beyond-Ultimate Raspberry Pi Starter Kit" filled with all sorts of sensors and motors and other components, it's like you were suddenly hit by a beam of light and knew that it was your mission to combine the two to create a computerized Fizz Buzz cuckoo clock!

You took them home and set up shop on the kitchen table, getting more and more excited as you got everything working together just perfectly. Soon the only task remaining was to write a function to select from the sounds you had recorded depending on what time it was:

## Your plan
* When a minute is evenly divisible by three, the clock will say the word "Fizz".
* When a minute is evenly divisible by five, the clock will say the word "Buzz".
* When a minute is evenly divisible by both, the clock will say "Fizz Buzz", with two exceptions:
  1. On the hour, instead of "Fizz Buzz", the clock door will open, and the cuckoo bird will come out and "Cuckoo" between one and twelve times depending on the hour.
  2. On the half hour, instead of "Fizz Buzz", the clock door will open, and the cuckoo will come out and "Cuckoo" just once.
* With minutes that are not evenly divisible by either three or five, at first you had intended to have the clock just say the numbers ala Fizz Buzz, but then you decided at least for version 1.0 to just have the clock make a quiet, subtle "tick" sound for a little more clock nature and a little less noise.

Your input will be a string containing hour and minute values in 24-hour time, separated by a colon, and with leading zeros. For example, 1:34 pm would be `"13:34"`.

Your return value will be a string containing the combination of Fizz, Buzz, Cuckoo, and/or tick sounds that the clock needs to make at that time, separated by spaces. Note that although the input is in 24-hour time, cuckoo clocks' cuckoos are in 12-hour time.

## Some examples
```
"13:34"  ...


Solve in Python:
## Your task

You are given a dictionary/hash/object containing some languages and your test results in the given languages. Return the list of languages where your test score is at least `60`, in descending order of the results.

Note: the scores will always be unique (so no duplicate values)

## Examples

```python
{"Java": 10, "Ruby": 80, "Python": 65}    -->  ["Ruby", "Python"]
{"Hindi": 60, "Dutch" : 93, "Greek": 71}  -->  ["Dutch", "Greek", "Hindi"]
{"C++": 50, "ASM": 10, "Haskell": 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 my_languages(results):
    g = results.items()
    g = list(g)
    f = []
    g.sort(key=lambda i: i[1])
    for i in g:
        if i[1] >= 60:
            i = f.append(i[0])
    h = f.reverse()
    return f


Solve in Python:
### **[Mahjong Series](/collections/mahjong)**

**Mahjong** is based on draw-and-discard card games that were popular in 18th and 19th century China and some are still popular today.

In each deck, there are three different suits numbered `1` to `9`, which are called **Simple tiles**. To simplify the problem, we talk about only one suit of *simple tiles* in this kata (and that's what the term **Pure Hand** means). Note that there are **EXACTLY** 4 identical copies of each kind of tiles in a deck.

In each of Mahjong games, each of the 4 players around the table has 13 tiles. They take turns drawing a tile from the tile walls and then discarding one of the tiles from their hands. One wins the game if that player holds a combination of tiles as defined below:

A regular winning hand consists of 4 *Melds* and 1 *Pair*. Each *meld* of tiles can be 3 identical or consecutive tiles of a suit, *e.g.* `222` or `456`.

![t2](https://upload.wikimedia.org/wikipedia/commons/6/61/MJt2.png)
![t2](https://upload.wikimedia.org/wikipedia/commons/6/61/MJt2.png)
![t2](https://upload.wikimedia.org/wikipedia/commons/6/61/MJt2.png)

![t4](https://upload.wikimedia.org/wikipedia/commons/7/72/MJt4.png)
![t5](https://upload.wikimedia.org/wikipedia/commons/5/5c/MJt5.png)
![t6](https://upload.wikimedia.org/wikipedia/commons/7/72/MJt6.png)

Now let's consider a hand of...

# lazy backtrack attempt

def validate(tiles, used_pair=False):
    tiles = sorted(tiles)
    if not tiles:
            return True

    current_tile = tiles.pop(0)
    if tiles.count(current_tile) > 1:
        tiles.remove(current_tile)
        tiles.remove(current_tile)
        ok = validate(tiles, used_pair)
        if ok:
            return True
        tiles.append(current_tile)
        tiles.append(current_tile)
        tiles = list(sorted(tiles))

    if tiles.count(current_tile + 1) > 0 and tiles.count(current_tile + 2) > 0:
        tiles.remove(current_tile + 1)
        tiles.remove(current_tile + 2)
        ok = validate(tiles, used_pair)
        if ok:
            return True
        tiles.append(current_tile + 1)
        tiles.append(current_tile + 2)
        tiles = list(sorted(tiles))

    if not used_pair and tiles.count(current_tile) > 0:
        tiles.remove(current_tile)
        ok = validate(tiles, True)
        if ok:
            return True
        tiles.append(current_tile)
        tiles = list(sorted(tiles))
    tiles.append(current_tile)
    return False

def solution(tiles):
    result = ''
    for i in range(1, 10):
        if tiles.count(str(i)) > 3:
            continue
        tiles_with_new_tile = [int(n) for n in sorted(tiles + str(i))]
        if validate(tiles_with_new_tile):
            result += str(i)
    return result


Solve in Python:
### Background

I was reading a [book](http://www.amazon.co.uk/Things-Make-Do-Fourth-Dimension/dp/1846147646/) recently, "Things to Make and Do in the Fourth Dimension" by comedian and mathematician Matt Parker, and in the first chapter of the book Matt talks about problems he likes to solve in his head to take his mind off the fact that he is in his dentist's chair, we've all been there!

The problem he talks about relates to polydivisible numbers, and I thought a kata should be written on the subject as it's quite interesting. (Well it's interesting to me, so there!)

### Polydivisib... huh what?

So what are they?

A polydivisible number is divisible in an unusual way. The first digit is cleanly divisible by `1`, the first two digits are cleanly divisible by `2`, the first three by `3` and so on.

The interesting thing about polydivisiblity is that it relates to the underlying number, but not the base it is written in, so if aliens came to Earth and used base `23` (`11` fingers on one hand and `12` on the other), no matter what squiggles they use to write numbers, they would find the same numbers polydivisible!

### Polydivisibilty Example:

Let's do a worked example to clear up any questions ...

Starting wih the number `1,232` in base `10` then:

```
 1232
 1    /1 = 1    Yay!
 12   /2 = 6    Yay!
 123  /3 = 41   Yay!
 1232 /4 = 308  Yay!
```

Thus `1,232` is a polydivisible number in base `4` and above.

However starting wih the number `123,220` and using base `10` then:

```
 123220
 1      /1 = 1            Yay!
 12     /2 = 6            Yay!
 123    /3 = 41           Yay!
 1232   /4 = 308          Yay!
 12322  /5 = 2464.4       Oh no, that's not a round number!
 123220 /6 = 220536.333r  Oh no, that's not a round number!
```

Thus `123,220` is not a polydivisible base 10 number, but what about in another base?

Again starting wih the number `123,220` and using base `6` then:

```
 base 6   base 10
 1      = 1       -> 1     /1 = 1     Yay!
 12     = 8       -> 8     /2 = 4     Yay!
 123    = 51     ...

CHARS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

def is_polydivisible(s, b):
    divide=1
    while divide<=len(s):
        temp=divide
        index=0
        num=0
        while temp>0:
            num+=CHARS.index(s[index])*(b**(temp-1))
            temp-=1
            index+=1
        if num%divide!=0:
            return False
        divide+=1
        num=0
    return True
def get_polydivisible(n, b):
    count=0
    count2=0
    temp=1
    s=""
    while True:
        if count2>=b**temp:
            temp+=1
        record=count2
        power=temp
        while len(s)<temp:
            some=record//b**(power-1)
            s+=CHARS[some]
            record-=some*(b**(power-1))
            power-=1
        count2+=1
        if is_polydivisible(s, b):
            count+=1
        if count==n:
            return s
        s=""


Solve in Python:
### Background

We **all** know about "balancing parentheses" (plus brackets, braces and chevrons) and even balancing characters that are identical.

Read that last sentence again, I balanced different characters and identical characters twice and you didn't even notice... :)

### Kata
Your challenge in this kata is to write a piece of code to validate that a supplied string is balanced.

You must determine if all that is open is then closed, and nothing is closed which is not already open!

You will be given a string to validate, and a second string, where each pair of characters defines an opening and closing sequence that needs balancing.

You may assume that the second string always has an even number of characters.

### Example
```python
# In this case '(' opens a section, and ')' closes a section
is_balanced("(Sensei says yes!)", "()")       # => True
is_balanced("(Sensei says no!", "()")         # => False

# In this case '(' and '[' open a section, while ')' and ']' close a section
is_balanced("(Sensei [says] yes!)", "()[]")   # => True
is_balanced("(Sensei [says) no!]", "()[]")    # => False

# In this case a single quote (') both opens and closes a section
is_balanced("Sensei says 'yes'!", "''")       # => True
is_balanced("Sensei say's no!", "''")         # => False
```

def is_balanced(source, caps):
    matches = dict([(b,a) for a,b in zip(caps[::2],caps[1::2]) ])
    source = [char for char in source if char in caps]
    stack = []
    for char in source:
        if len(stack) == 0: stack.append(char)
        elif matches.get(char) == stack[-1]: del stack[-1]
        else: stack.append(char)
    return len(stack) == 0


Solve in Python:
### Background
In classical cryptography, the Hill cipher is a polygraphic substitution cipher based on linear algebra. It was invented by Lester S. Hill in 1929.

### Task

This cipher involves a text key which has to be turned into a matrix and text which needs to be encoded. The text key can be of any perfect square length but for the sake of this kata we will focus on keys of length 4 forming a 2x2 matrix.

To encrypt a message using the hill cipher, first of all you need to convert the text key into a key matrix. To do that you will convert the key row wise into a 2x2 matrix. Then you will substitute the letters with their respective positions on the alphabet: A=0, B=1,C=2 and so on till Z=25. So for example if we get the key text as ```cats```, the key matrix will be:

    [[ 2  0]
     [19 18]]

Now the next step is to break the text into pairs of two and convert those pairs into 2x1 matrices. If your text has an odd number of letters then just add a Z next to your last letter. Now again convert those letters into their respective position in the alphabet as above. So for example the text ```Hi``` would be converted into:

    [[7]
     [8]]

Now we need to [multiply](https://www.mathsisfun.com/algebra/matrix-multiplying.html) the key matrix by the text matrix to get our encrypted matrix and then find out the encrypted matrix [modulo](https://en.wikipedia.org/wiki/Modulo_operation) 26:

    [[ 2  0]  *  [[7]  =  [[14]   =  [[14]  mod 26
     [19 18]]     [8]]     [277]]     [17]]

For the final step we just find out the letters at the alphabet position of 14 and 17 which are ```O``` and ```R```. So ```OR``` is our encrypted message for the message ```Hi```

In this kata you will be given a function named ```encrypt``` with the parameters ```text``` and ```key``` and you have to return the encrypted message in all uppercase letters

``` python
encrypt('','azyb') → ''
encrypt('Hi','cats') → 'OR'
encrypt('This is a good day','bbaa') → 'AAAAAAGACAGAYA'
```

Note:
- The text to...

"""by Zakhar M."""
import re
import numpy as np
from math import gcd

ALPHABET = {chr(letters): letters - 65 for letters in range(65, 91)}
REVERSE_ALPHABET = {number_symbol: symbol for symbol, number_symbol in list(ALPHABET.items())}

def checking_key_for_validity(matrix_key, length_alphabet):
    determinant = np.linalg.det(matrix_key)
    nod_determinant_and_length_alphabet = gcd(int(round(determinant)), length_alphabet)

    if nod_determinant_and_length_alphabet == 1 and nod_determinant_and_length_alphabet != 0:
        return True
    return False

def get_matrix_key(key, length_block=2):
    tmp_list = list()
    matrix_key = list()
    length_key = len(key)

    if length_key % 2 != 0:
        return ''

    for symbol in key:
        number_symbol_in_alphabet = ALPHABET[symbol]
        tmp_list.append(number_symbol_in_alphabet)
        length_tmp_list = len(tmp_list)

        if length_tmp_list != length_block:
            continue

        matrix_key.append(tmp_list)
        tmp_list = list()

    return matrix_key

def get_matrix_open_text(open_text, length_blocks=2):
    tmp_list = list()
    matrix_open_text = list()
    pattern_only_letters = re.compile(r'[^a-zA-Z]*')
    prepared_open_text = pattern_only_letters.sub('', open_text).upper()
    length_prepared_open_text = len(prepared_open_text)

    if length_prepared_open_text % 2 != 0:
        prepared_open_text += 'Z'

    for symbol in prepared_open_text:
        number_symbol_in_alphabet = ALPHABET[symbol]
        tmp_list.append(number_symbol_in_alphabet)
        length_tmp_list = len(tmp_list)

        if length_tmp_list != length_blocks:
            continue

        matrix_open_text.append(tmp_list)
        tmp_list = list()

    return matrix_open_text

def smart_mul_matrix(matrix_1, matrix_2):
    result_matrix = list()

    for i in range(len(matrix_1)):
        tmp_sum = 0

        for j in range(len(matrix_2)):
            tmp_sum += (matrix_1[i][j] * matrix_2[j])
        result_matrix.append(tmp_sum % 26)
 ...


Solve in Python:
### Background
One way to order a nested (reddit-style) commenting system is by giving each comment a rank.

Generic comments on a thread start with rank 1 and increment, so the second comment on a thread would have rank 2. A reply to comment 1 will be ranked 1.1, and a reply to comment 1.1 will be ranked 1.1.1 . The second comment to reply to comment 1 would be ranked 1.2 .

Note that since 1.1.1 is a valid rank, the ranks given are of type string.

### Task:
Given a list of comment ranks (strings), order them as a comment thread would appear

### Assumptions:
* there will always be a rank 1 in the given input
* ranks are of type string
* rank numbers are incremented, and not skippped (1.1 could be followed by 1.2, not 1.3)

### Example order:
```
[
  '1',
  '1.1',
  '1.2',
  '1.2.1',
  '2',
  '3',
  '3.1',
  '3.1.1',
  '3.2'
]
```

def sort_ranks(ranks):
  return sorted(ranks, key=lambda s: tuple(int(x) for x in s.split('.'))) #


Solve in Python:
### Combine strings function
```if:coffeescript,haskell,javascript
Create a function named `combineNames` that accepts two parameters (first and last name). The function should return the full name.
```
```if:python,ruby
Create a function named (`combine_names`) that accepts two parameters (first and last name). The function should return the full name.
```
```if:csharp
Create a function named (`Combine_names`) that accepts two parameters (first and last name). The function should return the full name.
```

Example:
```python
combine_names('James', 'Stevens')
```
returns:
```python
'James Stevens'
```

# Create the combine_names function here
def combine_names(a,b):
    return a+' '+b


Solve in Python:
### Context and Definitions

You are in charge of developing a new cool JavaScript library that provides functionality similar to that of [Underscore.js](http://underscorejs.org/).

You have started by adding a new  **list data type** to your library. You came up with a design of a data structure that represents an [algebraic data type](http://en.wikipedia.org/wiki/Algebraic_data_type) as a pair of elements:

```python
class Cons:
  def __init__(self, head, tail):
    self.head = head
    self.tail = tail
```

You are pretty smart, because using this new data type, we can easily build a list of elements. For instance, a list of numbers:

```python
numbers = Cons(1, Cons(2, Cons(3, Cons(4, Cons(5, None)))))
```

In a code review with your boss, you explained him how every *cons cell* contains a "value" in its head, and in its tail it contains either another cons cell or null. We know we have reached the end of the data structure when the tail is null.

So, your boss is pretty excited about this new data structure and wants to know if you will be able to build some more  functionality around it. In a demo you did this week for the rest of your team, in order to illustrate how this works, you showed them a method to transform a list of items of your list data type into a JavaScript array:

```python
  # added to the class implementation:
  def to_array(self):
    tail = self.tail
    new_tail = (tail.to_array() if tail is not None else [])
    return [self.head] + new_tail
```

And they were amazed when you simply did this:

```python
print(numbers.to_array())  # yields [1,2,3,4,5]
```

### The New Requirements

Now, the team is convinced that this is the way to go and they would like to build the library around this cool new data type, but they want you to provide a few more features for them so that they can start using this type in solving some real world problems.

You have been reading about a technique called  [applicative...

class Cons:
    def __init__(self, head, tail):
        self.head = head
        self.tail = tail

    def to_array(self):
        return [self.head] + (self.tail.to_array() if self.tail is not None else [])

    @classmethod
    def from_array(cls, arr):
        if arr:
            return Cons(arr[0], Cons.from_array(arr[1:]))

    def filter(self, fn):
        return Cons.from_array(list(filter(fn, self.to_array())))

    def map(self, fn):
        return Cons.from_array(list(map(fn, self.to_array())))


Solve in Python:
### Count the number of Duplicates

Write a function that will return the count of **distinct case-insensitive** alphabetic characters and numeric digits that occur more than
once in the input string.
The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits.

### Example
"abcde" -> 0             `# no characters repeats more than once`
"aabbcde" -> 2           `# 'a' and 'b'`
"aabBcde" -> 2           ``# 'a' occurs twice and 'b' twice (`b` and `B`)``
"indivisibility" -> 1    `# 'i' occurs six times`
"Indivisibilities" -> 2  `# 'i' occurs seven times and 's' occurs twice`
"aA11" -> 2              `# 'a' and '1'`
"ABBA" -> 2              `# 'A' and 'B' each occur twice`

def duplicate_count(text):
    text = text.lower()
    duplicates = []
    for i in text:
        if text.count(i) > 1 and i not in duplicates:
            duplicates.append(i)
    return len(duplicates)


Solve in Python:
### Description
As hex values can include letters `A` through to `F`, certain English words can be spelled out, such as `CAFE`, `BEEF`, or `FACADE`.
This vocabulary can be extended by using numbers to represent other letters, such as `5EAF00D`, or `DEC0DE5`.

Given a string, your task is to return the decimal sum of all words in the string that can be interpreted as such hex values.

### Example

Working with the string `BAG OF BEES`:
* `BAG` ==> `0` as it is not a valid hex value
* `OF` ==> `0F` ==> `15`
* `BEES` ==> `BEE5` ==> `48869`

So `hex_word_sum('BAG OF BEES')` returns the sum of these, `48884`.

### Notes
* Inputs are all uppercase and contain no punctuation
* `0` can be substituted for `O`
* `5` can be substituted for `S`

def hex_word_sum(string, res = 0):
    s = string.replace('O', '0').replace('S', '5').split()

    for i in s:
        try:
            res += int(i, 16)
        except: pass

    return res


Solve in Python:
### Description:

 Remove all exclamation marks from sentence except at the end.

### Examples

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

def remove(s):
    return s.replace('!', '')+ '!'*(len(s)- len(s.rstrip('!')))


Solve in Python:
### Description:

 Replace all vowel to exclamation mark in the sentence. `aeiouAEIOU` is vowel.

### Examples

```
replace("Hi!") === "H!!"
replace("!Hi! Hi!") === "!H!! H!!"
replace("aeiou") === "!!!!!"
replace("ABCDE") === "!BCD!"
```

def replace_exclamation(s):
    s_list = list(s)
    for i in range(len(s_list)):
        if s_list[i].lower() == "a" or s_list[i].lower() == "e" or s_list[i].lower() == "i" or s_list[i].lower() == "o" or s_list[i].lower() == "u":
            s_list[i] = "!"
    string = ""
    for st in s_list:
        string += st
    return string


Solve in Python:
### Happy Holidays fellow Code Warriors!

Now, Dasher! Now, Dancer! Now, Prancer, and Vixen! On, Comet! On, Cupid! On, Donder and Blitzen! That's the order Santa wanted his reindeer...right? What do you mean he wants them in order by their last names!? Looks like we need your help Code Warrior!

### Sort Santa's Reindeer

Write a function that accepts a sequence of Reindeer names, and returns a sequence with the Reindeer names sorted by their last names.

### Notes:

* It's guaranteed that each string is composed of two words
* In case of two identical last names, keep the original order

### Examples

For this input:

```
[
  "Dasher Tonoyan",
  "Dancer Moore",
  "Prancer Chua",
  "Vixen Hall",
  "Comet Karavani",
  "Cupid Foroutan",
  "Donder Jonker",
  "Blitzen Claus"
]
```

You should return this output:

```
[
  "Prancer Chua",
  "Blitzen Claus",
  "Cupid Foroutan",
  "Vixen Hall",
  "Donder Jonker",
  "Comet Karavani",
  "Dancer Moore",
  "Dasher Tonoyan",
]
```

sort_reindeer=lambda rn: sorted(rn, key=lambda x: x.split()[1])


Solve in Python:
### Introduction and Warm-up (Highly recommended)

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

## Task

**_Given_** an *array/list [] of integers* , **_Find the product of the k maximal_** numbers.
___

### Notes

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

* **_Array/list's numbers_**  *Will be* **_mixture of positives , negatives and zeros_**

* **_Repetition_** of numbers in *the array/list could occur*.
___

### Input >> Output Examples

```
maxProduct ({4, 3, 5}, 2) ==>  return (20)
```

#### _Explanation_:

* **_Since_** *the size (k) equal 2* , then **_the subsequence of size 2_** *whose gives* **_product of maxima_**  is `5 * 4 = 20` .
___

```
maxProduct ({8, 10 , 9, 7}, 3) ==>  return (720)
```

#### _Explanation_:

* **_Since_** *the size (k) equal 3* , then **_the subsequence of size 3_** *whose gives* **_product of maxima_**  is ` 8 * 9 * 10 = 720` .
___

```
maxProduct ({10, 8, 3, 2, 1, 4, 10}, 5) ==> return (9600)
```

#### _Explanation_:

* **_Since_** *the size (k) equal 5* , then **_the subsequence of size 5_** *whose gives* **_product of maxima_**  is ` 10 * 10 * 8 * 4 * 3 = 9600` .
___

```
maxProduct ({-4, -27, -15, -6, -1}, 2) ==> return (4)
```

#### _Explanation_:

* **_Since_** *the size (k) equal 2* , then **_the subsequence of size 2_** *whose gives* **_product of maxima_**  is ` -4 * -1 = 4` .
___

```
maxProduct ({10, 3, -1, -27} , 3)  return (-30)
```

#### _Explanation_:
* **_Since_** *the size (k) equal 3* , then **_the subsequence of size 3_** *whose gives* **_product of maxima_**  is ` 10 * 3 * -1 = -30 ` .
___
___
___
___

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

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

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

##### ALL translations are welcomed

##### Enjoy Learning !!
##### Zizou

max_product = lambda lst, n: __import__('functools').reduce(lambda x,y: x*y, sorted(lst, reverse=True)[:n])


Solve in Python:
### Longest Palindrome

Find the length of the longest substring in the given string `s` that is the same in reverse.

As an example, if the input was “I like racecars that go fast”, the substring (`racecar`) length would be `7`.

If the length of the input string is `0`, the return value must be `0`.

### Example:
```
"a" -> 1
"aab" -> 2
"abcde" -> 1
"zzbaabcd" -> 4
"" -> 0
```

def longest_palindrome (s):
    if s: return max(map(len, filter(palindrome, substrings(s))))
    else: return 0

def palindrome (s):
    return s[::-1] == s

def substrings (s):
    return [s[i:j+1] for i in range(0, len(s)) for j in range(i, len(s))]


Solve in Python:
### Lyrics...

Pyramids are amazing! Both in architectural and mathematical sense. If you have a computer, you can mess with pyramids even if you are not in Egypt at the time. For example, let's consider the following problem. Imagine that you have a pyramid built of numbers, like this one here:

```
   /3/
  \7\ 4
 2 \4\ 6
8 5 \9\ 3
```

### Here comes the task...

Let's say that the *'slide down'* is the maximum sum of consecutive numbers from the top to the bottom of the pyramid. As you can see, the longest *'slide down'* is `3 + 7 + 4 + 9 = 23`

Your task is to write a function `longestSlideDown` (in ruby: `longest_slide_down`) that takes a pyramid representation as argument and returns its' __largest__ *'slide down'*. For example,

```python
longestSlideDown([[3], [7, 4], [2, 4, 6], [8, 5, 9, 3]]) => 23
```

### By the way...

My tests include some extraordinarily high pyramids so as you can guess, brute-force method is a bad idea unless you have a few centuries to waste. You must come up with something more clever than that.

(c) This task is a lyrical version of the __Problem 18__ and/or __Problem 67__ on [ProjectEuler](https://projecteuler.net).

def longest_slide_down(pyramid):
    if len(pyramid) == 1:
        return pyramid[0][0]
    left, current = pyramid[:-1], pyramid[-1]
    pair_sum_g = map(max, zip(current[:-1], current[1:]))
    for i, x in enumerate(pair_sum_g):
        left[-1][i] += x
    return longest_slide_down(left)


Solve in Python:
### Please also check out other katas in [Domino Tiling series](https://www.codewars.com/collections/5d19554d13dba80026a74ff5)!

---

# Task

A domino is a rectangular block with `2` units wide and `1` unit high. A domino can be placed on a grid in two ways: horizontal or vertical.

```
## or #
      #
```

You have infinitely many dominoes, and you want to fill a board that is `2*N` units wide and `5` units high:

```
<---   2N   --->
################
################
################
################
################
```

The task is to find **the number of ways** you can fill the given grid with dominoes.

Since the answer will be very large, please give your answer **modulo 12345787**.

# Examples

```python
five_by_2n(1) == 8
five_by_2n(2) == 95
five_by_2n(3) == 1183
five_by_2n(5) == 185921

five_by_2n(10) == 8228892
five_by_2n(20) == 9942990
five_by_2n(50) == 2308182
five_by_2n(100) == 334896

five_by_2n(1000) == 6032838
five_by_2n(10000) == 2392948
```

# Constraints

`1 <= N <= 10000`

All inputs are valid integers.

# Hint

The reference solution uses eleven mutual recurrence equations.


Solve in Python:
### Please also check out other katas in [Domino Tiling series](https://www.codewars.com/collections/5d19554d13dba80026a74ff5)!

---

# Task

A domino is a rectangular block with `2` units wide and `1` unit high. A domino can be placed on a grid in two ways: horizontal or vertical.

```
## or #
      #
```

You have infinitely many dominoes, and you want to fill a board that is `N` units wide and `2` units high:

```
<---   N   --->
###############
###############
```

The task is to find **the number of ways** you can fill the given grid with dominoes.

# The Twist

However, you can quickly find that the answer is exactly the Fibonacci series (and yeah, CW has already too many of them), so here is a twist:

Now you have infinite supply of dominoes in `K` colors, and you have to fill the given grid **without any two adjacent dominoes having the same color**. Two dominoes are adjacent if they share an edge.

A valid filling of a 2 x 10 board with three colors could be as follows (note that two same-colored dominoes can share a point):

```
1131223312
2231332212
```

Since the answer will be very large, please give your answer **modulo 12345787**.

# Examples

```python
# K == 1: only one color
two_by_n(1, 1) == 1
two_by_n(3, 1) == 0

# K == 2: two colors
two_by_n(1, 2) == 2
two_by_n(4, 2) == 4
two_by_n(7, 2) == 2

# K == 3: three colors
two_by_n(1, 3) == 3
two_by_n(2, 3) == 12
two_by_n(5, 3) == 168 # yes, the numbers grow quite quickly

# You must handle big values
two_by_n(10, 5) == 7802599
two_by_n(20, 10) == 4137177
```

# Constraints

`1 <= N <= 10000`

`1 <= K <= 100`

All inputs are valid integers.


Solve in Python:
### Please also check out other katas in [Domino Tiling series](https://www.codewars.com/collections/5d19554d13dba80026a74ff5)!

---

# Task

A domino is a rectangular block with `2` units wide and `1` unit high. A domino can be placed on a grid in two ways: horizontal or vertical.

```
## or #
      #
```

You have infinitely many dominoes, and you want to fill a board that is `N` units wide and `3` units high:

```
<---   N   --->
###############
###############
###############
```

The task is to find **the number of ways** you can fill the given grid with dominoes.

# The Twist

But you quickly realize that the answer is zero for any odd `N`, because (obviously) you can't cover odd number of cells with dominoes! So you decide to introduce one **unit block** (1 unit wide and 1 unit high) to cover the final gap when needed (you don't need this block when `N` is even).

The following shows some possible tilings for `N = 5`. Note that, unlike my previous Kata, the numbers do not represent the colors (they are just for convenience). Also note that the unit block (marked as 'X') can be placed **anywhere on the board**, making the answers for odd numbers way higher than even ones.

```
11255   1122X   14456
3X267   33447   13356
34467   55667   22X77
```

Since the answer will be very large, please give your answer **modulo 12345787**.

# Examples

```python
# Even input
three_by_n(2) == 3
three_by_n(4) == 11
three_by_n(10) == 571
three_by_n(20) == 413403

# Odd input (the numbers grow much faster than even inputs)
three_by_n(1) == 2
three_by_n(3) == 18
three_by_n(5) == 106
three_by_n(11) == 11542
three_by_n(21) == 3287999

# You must handle big values
three_by_n(9999) == 6311027
three_by_n(10000) == 12003229
```

# Constraints

`1 <= N <= 10000`

All inputs are valid integers.

"""
def three_by_n_without_hole_missing_top(n):
    # the first column can be _11, _12
    assert n%2 == 1
    if n == 1:
        return 1
    return three_by_n_without_hole_missing_top(n-2) \
        + three_by_n_without_hole(n-1)

def three_by_n_without_hole(n):
    # the first column can be 112, 122, 123
    # the first two cases are the same by symmetry
    assert n%2 == 0
    if n == 0:
        return 1
    return three_by_n_without_hole_missing_top(n-1)*2 \
        + three_by_n_without_hole(n-2)

def three_by_n_with_hole_missing_top(n):
    # the first column can be _X1, _1X, _11, _12
    # the second case is impossible because it would have to look like:
    # _225588...
    # 114477....
    # X336699...
    # the fourth case is divided into two cases,
    # depending on whether the next column is X12 or 312
    assert n%2 == 0
    if n == 0:
        return 0
    return three_by_n_without_hole_missing_top(n-1) \
        + three_by_n_with_hole(n-1) \
        + three_by_n_with_hole_missing_top(n-2) \
        + three_by_n_without_hole(n-2)

def three_by_n_with_hole(n):
    # the first column can be X11, X12, 1X2, 11X, 12X, 112, 122, 123
    # by symmetry:
    # case 4 = case 1
    # case 5 = case 2
    # case 7 = case 6
    # note that case 3 is impossible because it would have to look like:
    # 114477....
    # X225588...
    # 336699....
    assert n%2 == 1
    if n == 1:
        return 2
    return three_by_n_without_hole(n-1)*2            \
        + three_by_n_without_hole_missing_top(n-2)*2 \
        + three_by_n_with_hole_missing_top(n-1)*2    \
        + three_by_n_with_hole(n-2)
"""

# naive algorithm
def mat_mul(A,B):
    n = len(A)
    # the top left entry is A[0][0]*B[0][0] + A[0][1]*B[1][0] + ...
    return [[sum(A[i][k]*B[k][j]%12345787 for k in range(n))%12345787 for j in range(n)] for i in range(n)]

# exponentiation by squaring
def mat_pow(A,k):
    n = len(A)
    res = [[0+(i==j) for j in range(n)] for i in range(n)] # A^0
    while k:
        if k%2 == 1:
            res =...


Solve in Python:
### Preface
You are currently working together with a local community to build a school teaching children how to code. First plans have been made and the community wants to decide on the best location for the coding school.
In order to make this decision data about the location of students and potential locations is collected.

### Problem
In order to be able to attract and teach as many students as possible we want to minimize the total traveling distance for potential students. The streets system is organized in a traditional grid system and students can only travel horizontally or vertically (not diagonal).

The locations of interested students is given as an array with the first value of each entry presenting the x coordinate and the second value presenting the y coordinate:
```python
students = [[3,7],[2,2],[14,1], ...];
```
Potential locations are passed as an array of objects with an unique id, a x and y coordinate:
```python
locations = [{"id": 1, "x": 3, "y": 4}, {"id": 2, "x": 8, "y": 2}, ...];
```

Your task is now to evaluate which of the school locations would be best to minimize the distance for all potential students to the school.

The desired output should consist of a string indicating the ID of the best suitable location and the x and y coordinates in the following form:

```
"The best location is number 1 with the coordinates x = 3 and y = 4"
```

def optimum_location(students, locations):
    best = min(locations, key=lambda location: distance(students, location))
    return "The best location is number {id} with the coordinates x = {x} and y = {y}".format(**best)

def distance(students, location):
    return sum(sum(abs(s[i] - location[j]) for i, j in ((0, "x"), (1, "y"))) for s in students)


Solve in Python:
### Problem Context

The [Fibonacci](http://en.wikipedia.org/wiki/Fibonacci_number) sequence is traditionally used to explain tree recursion.

```python
def fibonacci(n):
    if n in [0, 1]:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)
```

This algorithm serves welll its educative purpose but it's [tremendously inefficient](http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html#%_sec_1.2.2), not only because of recursion, but because we invoke the fibonacci function twice, and the right branch of recursion (i.e. `fibonacci(n-2)`) recalculates all the Fibonacci numbers already calculated by the left branch (i.e. `fibonacci(n-1)`).

This algorithm is so inefficient that the time to calculate any Fibonacci number over 50 is simply too much. You may go for a cup of coffee or go take a nap while you wait for the answer. But if you try it here in Code Wars you will most likely get a code timeout before any answers.

For this particular Kata we want to **implement the memoization solution**. This will be cool because it will let us *keep using the tree recursion* algorithm while still keeping it sufficiently optimized to get an answer very rapidly.

The trick of the memoized version is that we will keep a cache data structure (most likely an associative array) where we will store the Fibonacci numbers as we calculate them. When a Fibonacci number is calculated, we first look it up in the cache, if it's not there, we calculate it and put it in the cache, otherwise we returned the cached number.

Refactor the function into a recursive Fibonacci function that using  a memoized data structure avoids the deficiencies of tree recursion Can you make it so the memoization cache is private to this function?

from functools import wraps

# very rudimentary implementation of a cache decorator
# python 3's functools.lru_cache or its backport should be favored
def cache(f):
    _cache = {}
    @wraps(f)
    def wrapped(n):
        if n in _cache:
            return _cache[n]
        else:
            result = f(n)
            _cache[n] = result
            return result
    return wrapped

@cache
def fibonacci(n):
    if n in [0, 1]:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)


Solve in Python:
### Sudoku Background

Sudoku is a game played on a 9x9 grid. The goal of the game is to fill all cells of the grid with digits from 1 to 9, so that each column, each row, and each of the nine 3x3 sub-grids (also known as blocks) contain all of the digits from 1 to 9.
(More info at: http://en.wikipedia.org/wiki/Sudoku)

### Sudoku Solution Validator

Write a function `validSolution`/`ValidateSolution`/`valid_solution()` that accepts a 2D array representing a Sudoku board, and returns true if it is a valid solution, or false otherwise. The cells of the sudoku board may also contain 0's, which will represent empty cells. Boards containing one or more zeroes are considered to be invalid solutions.

The board is always 9 cells by 9 cells, and every cell only contains integers from 0 to 9.

### Examples

```
validSolution([
  [5, 3, 4, 6, 7, 8, 9, 1, 2],
  [6, 7, 2, 1, 9, 5, 3, 4, 8],
  [1, 9, 8, 3, 4, 2, 5, 6, 7],
  [8, 5, 9, 7, 6, 1, 4, 2, 3],
  [4, 2, 6, 8, 5, 3, 7, 9, 1],
  [7, 1, 3, 9, 2, 4, 8, 5, 6],
  [9, 6, 1, 5, 3, 7, 2, 8, 4],
  [2, 8, 7, 4, 1, 9, 6, 3, 5],
  [3, 4, 5, 2, 8, 6, 1, 7, 9]
]); // => true
```

```
validSolution([
  [5, 3, 4, 6, 7, 8, 9, 1, 2],
  [6, 7, 2, 1, 9, 0, 3, 4, 8],
  [1, 0, 0, 3, 4, 2, 5, 6, 0],
  [8, 5, 9, 7, 6, 1, 0, 2, 0],
  [4, 2, 6, 8, 5, 3, 7, 9, 1],
  [7, 1, 3, 9, 2, 4, 8, 5, 6],
  [9, 0, 1, 5, 3, 7, 2, 1, 4],
  [2, 8, 7, 4, 1, 9, 6, 3, 5],
  [3, 0, 0, 4, 8, 1, 1, 7, 9]
]); // => false
```

# Accessors
def get_row(board, row_index):
    return board[row_index]

def get_col(board, col_index):
    return [row[col_index] for row in board]

def get_subgrid(board, base_x, base_y):
    # Returns elements (array) in a 3x3 subgrid
    # base_x,base_y are the x,y coordinates of the top-left element in the 3x3 subgrid
    result = []
    for x in range(0, 3):
        for y in range(0, 3):
            result.append(board[base_x + x][base_y + y])
    return result

class InvalidSudokuSet(Exception):
    pass

def validate_9(arr, identifier="Group"):
    # Validates any 9 elements
    if len(arr) != 9:
        raise InvalidSudokuSet("{} has length {} (not 9): {}".format(identifier, len(arr), arr))

    for number in range(1, 10):
        if number not in arr:
            raise InvalidSudokuSet("{} is missing '{}': {}".format(identifier, number, arr))

def validate_dimensions(board):
    if len(board) != 9:
        raise InvalidSudokuSet("Board contains {} rows:\n{}".format(len(board), board))
    for row in board:
        if len(row) != 9:
            raise InvalidSudokuSet("Row does not have 9 columns:\n{}".format(board))

def validate_rows(board):
    for index in range(0, 9):
        validate_9(get_row(board, index), "Row")

def validate_columns(board):
    for index in range(0, 9):
        validate_9(get_col(board, index), "Column")

def validate_subgrids(board):
    for x in range(0, 3):
        for y in range(0, 3):
            subgrid = get_subgrid(board, x * 3, y *3)
            validate_9(subgrid, identifier="3x3 Subgrid")

def validSolution(board):
    try:
        validate_dimensions(board)
        validate_rows(board)
        validate_columns(board)
        validate_subgrids(board)

    except InvalidSudokuSet as e:
        print("Invalid board:\n{}\n".format(board))
        print(e)
        return False

    print("Valid board:\n{}".format(board))
    return True


Solve in Python:
### Task

Yes, your eyes are no problem, this is toLoverCase (), not toLowerCase (), we want to make the world full of love.

### What do we need to do?

You need to add a prototype function to the String, the name is toLoverCase. Function can convert the letters in the string, converted to "L", "O", "V", "E", if not the letter, don't change it.

### How to convert? :

```
"love!".toLoverCase()="EVOL!"
```

more example see the testcases.

### Series:
 - [Bug in Apple](http://www.codewars.com/kata/56fe97b3cc08ca00e4000dc9)
 - [Father and Son](http://www.codewars.com/kata/56fe9a0c11086cd842000008)
 - [Jumping Dutch act](http://www.codewars.com/kata/570bcd9715944a2c8e000009)
 - [Planting Trees](http://www.codewars.com/kata/5710443187a36a9cee0005a1)
 - [Give me the equation](http://www.codewars.com/kata/56fe9b65cc08cafbc5000de3)
 - [Find the murderer](http://www.codewars.com/kata/570f3fc5b29c702c5500043e)
 - [Reading a Book](http://www.codewars.com/kata/570ca6a520c69f39dd0016d4)
 - [Eat watermelon](http://www.codewars.com/kata/570df12ce6e9282a7d000947)
 - [Special factor](http://www.codewars.com/kata/570e5d0b93214b1a950015b1)
 - [Guess the Hat](http://www.codewars.com/kata/570ef7a834e61306da00035b)
 - [Symmetric Sort](http://www.codewars.com/kata/5705aeb041e5befba20010ba)
 - [Are they symmetrical?](http://www.codewars.com/kata/5705cc3161944b10fd0004ba)
 - [Max Value](http://www.codewars.com/kata/570771871df89cf59b000742)
 - [Trypophobia](http://www.codewars.com/kata/56fe9ffbc25bf33fff000f7c)
 - [Virus in Apple](http://www.codewars.com/kata/5700af83d1acef83fd000048)
 - [Balance Attraction](http://www.codewars.com/kata/57033601e55d30d3e0000633)
 - [Remove screws I](http://www.codewars.com/kata/5710a50d336aed828100055a)
 - [Remove screws II](http://www.codewars.com/kata/5710a8fd336aed00d9000594)
 - [Regular expression compression](http://www.codewars.com/kata/570bae4b0237999e940016e9)
 - [Collatz Array(Split or merge)](http://www.codewars.com/kata/56fe9d579b7bb6b027000001)
 - [Tidy up the...

def to_lover_case(stg):
    table = str.maketrans("abcdefghijklmnopqrstuvwxyz", f"{'LOVE' * 6}LO")
    return stg.lower().translate(table)


Solve in Python:
### Task

Your main goal is to find two numbers(` >= 0 `), greatest common divisor of wich will be `divisor` and number of iterations, taken by Euclids algorithm will be `iterations`.

### Euclid's GCD

```CSharp
BigInteger FindGCD(BigInteger a, BigInteger b) {
  // Swaping `a` and `b`
  if (a < b) {
    a += b;
    b = a - b;
    a = a - b;
  }

  while (b > 0) {
    // Iteration of calculation
    BigInteger c = a % b;
    a = b;
    b = c;
  }

  // `a` - is greates common divisor now
  return a;
}
```

### Restrictions

Your program should work with numbers

`0 < divisor < 1000`

`0 <= iterations <= 50'000`

def find_initial_numbers (divisor, iterations):
    a, b = divisor, 0
    for _ in range(iterations + (1 if iterations else 0)):
        a, b = a + b, a
    return a, b


Solve in Python:
### Task
 Each day a plant is growing by `upSpeed` meters. Each night that plant's height decreases by `downSpeed` meters due to the lack of sun heat. Initially, plant is 0 meters tall. We plant the seed at the beginning of a day. We want to know when the height of the plant will reach a certain level.

### Example

 For `upSpeed = 100, downSpeed = 10 and desiredHeight = 910`, the output should be `10`.

 ```
 After day 1 --> 100
 After night 1 --> 90
 After day 2 --> 190
 After night 2 --> 180
 After day 3 --> 280
 After night 3 --> 270
 After day 4 --> 370
 After night 4 --> 360
 After day 5 --> 460
 After night 5 --> 450
 After day 6 --> 550
 After night 6 --> 540
 After day 7 --> 640
 After night 7 --> 630
 After day 8 --> 730
 After night 8 --> 720
 After day 9 --> 820
 After night 9 --> 810
 After day 10 --> 910
 ```

 For `upSpeed = 10, downSpeed = 9 and desiredHeight = 4`, the output should be `1`.

 Because the plant reach to the desired height at day 1(10 meters).

 ```
 After day 1 --> 10
 ```

### Input/Output

```if-not:sql
 - `[input]` integer `upSpeed`

    A positive integer representing the daily growth.

    Constraints: `5 ≤ upSpeed ≤ 100.`

 - `[input]` integer `downSpeed`

    A positive integer representing the nightly decline.

    Constraints: `2 ≤ downSpeed < upSpeed.`

 - `[input]` integer `desiredHeight`

    A positive integer representing the threshold.

    Constraints: `4 ≤ desiredHeight ≤ 1000.`

 - `[output]` an integer

    The number of days that it will take for the plant to reach/pass desiredHeight (including the last day in the total count).
```
```if:sql
## Input

~~~
-----------------------------------------
|     Table     |    Column      | Type |
|---------------+----------------+------|
| growing_plant | down_speed     | int  |
|               | up_speed       | int  |
|               | desired_height | int  |
-----------------------------------------
~~~

### Columns
* `up_speed`: A positive integer representing the daily growth. Constraints: `5 ≤ up_speed ≤...

def growing_plant(upSpeed, downSpeed, desiredHeight):
    progress = upSpeed - downSpeed
    total = 1
    while upSpeed < desiredHeight:
        upSpeed += progress
        total += 1
    return total


Solve in Python:
### Task
 King Arthur and his knights are having a New Years party. Last year Lancelot was jealous of Arthur, because Arthur had a date and Lancelot did not, and they started a duel.

 To prevent this from happening again, Arthur wants to make sure that there are at least as many women as men at this year's party. He gave you a list of integers of all the party goers.

 Arthur needs you to return true if he needs to invite more women or false if he is all set.

### Input/Output

 - `[input]` integer array `L` (`$a` in PHP)

  An array (guaranteed non-associative in PHP) representing the genders of the attendees, where `-1` represents `women` and `1` represents `men`.

  `2 <= L.length <= 50`

- `[output]` a boolean value

  `true` if Arthur need to invite more women, `false` otherwise.

def invite_more_women(arr):
    if sum(arr) >=1:
        return sum(arr) >=1
    else: return bool({})


Solve in Python:
### Task
The __dot product__ is usually encountered in linear algebra or scientific computing. It's also called __scalar product__ or __inner product__ sometimes:

> In mathematics, the __dot product__, or __scalar product__ (or sometimes __inner product__ in the context of Euclidean space), is an algebraic operation that takes two equal-length sequences of numbers (usually coordinate vectors) and returns a single number. [Wikipedia](https://en.wikipedia.org/w/index.php?title=Dot_product&oldid=629717691)

In our case, we define the dot product algebraically for two vectors `a = [a1, a2, …, an]`, `b = [b1, b2, …, bn]` as

    dot a b = a1 * b1 + a2 * b2 + … + an * bn.
Your task is to find permutations of `a` and `b`, such that `dot a b` is minimal, and return that value. For example, the dot product of `[1,2,3]` and `[4,0,1]` is minimal if we switch `0` and `1` in the second vector.

### Examples
```python
min_dot([1,2,3,4,5], [0,1,1,1,0] ) = 6
min_dot([1,2,3,4,5], [0,0,1,1,-4]) = -17
min_dot([1,3,5]    , [4,-2,1]    ) = -3
```

### Remarks
If the list or array is empty, `minDot` should return 0. All arrays or lists will have the same length. Also, for the dynamically typed languages, all inputs will be valid lists or arrays, you don't need to check for `undefined`, `null` etc.

Note: This kata is inspired by [GCJ 2008](https://code.google.com/codejam/contest/32016/dashboard#s=p0).

def min_dot(a, b):
    return sum(x * y for (x, y) in zip(sorted(a), sorted(b, reverse = True)))


Solve in Python:
### Task
You've just moved into a perfectly straight street with exactly ```n``` identical houses on either side of the road. Naturally, you would like to find out the house number of the people on the other side of the street. The street looks something like this:

--------------------
### Street
```
1|   |6
3|   |4
5|   |2
```

Evens increase on the right; odds decrease on the left. House numbers start at ```1``` and increase without gaps.
When ```n = 3```, ```1``` is opposite ```6```, ```3``` opposite ```4```, and ```5``` opposite ```2```.

-----------------
### Example
Given your house number ```address``` and length of street ```n```, give the house number on the opposite side of the street.

```CoffeeScript
overTheRoad(address, n)
overTheRoad(1, 3) = 6
overTheRoad(3, 3) = 4
overTheRoad(2, 3) = 5
overTheRoad(3, 5) = 8
```

```python
over_the_road(address, n)
over_the_road(1, 3) = 6
over_the_road(3, 3) = 4
over_the_road(2, 3) = 5
over_the_road(3, 5) = 8
```

Both n and address could get upto 500 billion with over 200 random tests.

def over_the_road(a, n):
    return -(a-2*n-1)


Solve in Python:
### Task:

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

If the Argument is `0` or a Negative Integer then it should return `""` i.e. empty string.

### Examples:

`pattern(9)`:

    123456789
    234567891
    345678912
    456789123
    567891234
    678912345
    789123456
    891234567
    912345678

`pattern(5)`:

    12345
    23451
    34512
    45123
    51234

Note: There are no spaces in the pattern

Hint: Use `\n` in string to jump to next line

from itertools import chain

def pattern(n):
    line = list(i + 1 for i in range(n))
    return "\n".join("".join(str(x) for x in chain(line[i:], line[:i])) for i in range(n))


Solve in Python:
### Task:

You have to write a function `pattern` which returns the following Pattern(See Examples) upto (2n-1) rows, where n is parameter.

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

#### Parameters:

    pattern(        n        );
                    ^
                    |
             Term upto which
           Basic Pattern(this)
                should be
                 created

#### Rules/Note:
* If `n < 1` then it should return "" i.e. empty string.
* `The length of each line is same`, and is equal to the length of longest line in the pattern i.e (2n-1).
* Range of Parameters (for the sake of CW Compiler) :
  + `n ∈ (-∞,100]`

### Examples:

* pattern(5):

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

* pattern(10):

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

* pattern(15):

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


Solve in Python:
### Task:

Your job is to take a pair of parametric equations, passed in as strings, and convert them into a single rectangular equation by eliminating the parameter. Both parametric halves will represent linear equations of x as a function of time and y as a function of time respectively.

The format of the final equation must be `Ax + By = C` or `Ax - By = C` where A and B must be positive and A, B, and C are integers. The final equation also needs to have the lowest possible whole coefficients. Omit coefficients equal to one.

The method is called `para_to_rect` or `EquationsManager.paraToRect` and takes in two strings in the form `x = at +(or -) b` and `y = ct +(or -) d` respectively, where `a` and `c` must be integers, and `b` and `d` must be positive integers. If `a` or `c` is omitted, the coefficient of _t_ is obviously assumed to be 1 (see final case in the example tests). There will NEVER be double signs in the equations inputted (For example: `"x = -12t + -18"` and `"y = -12t - -18"` won't show up.)

### Examples:

```python
para_to_rect("x = 12t + 18", "y = 8t + 7") => "2x - 3y = 15"
```

> __CALCULATION:__
  x = 12t + 18
  y = 8t + 7
  2x = 24t + 36
  3y = 24t + 21
  2x - 3y = (24t + 36) - (24t + 21)
  2x - 3y = 15

```python
para_to_rect("x = -12t - 18", "y = 8t + 7") => "2x + 3y = -15"
```

> __CALCULATION:__
  x = -12t - 18
  y = 8t + 7
  2x = -24t - 36
  3y = 24t + 21
  2x + 3y = (-24t - 36) + (24t + 21)
  2x + 3y = -15

```python
para_to_rect("x = -t + 12", "y = 12t - 1") => "12x + y = 143"
```

> __CALCULATION:__
  x = -t + 12
  y = 12t - 1
  12x = -12t + 144
  y   = 12t  - 1
  12x + y = 143

More examples in the sample test cases.

### Notes:

As you can see above, sometimes you'll need to add the two parametric equations after multiplying by the necessary values; sometimes you'll need to subtract them – just get rid of the _t_!

def extract(eq):
    k, b = eq.split('t')
    k = k[3:].strip()
    k = (int(k) if k!='-' else -1) if k else 1
    b = b.strip()
    b = (-1 if b[0]=='-' else 1)*int(b[1:].strip()) if b else 0
    return k, b

def quotient(x):
    return '' if x==1 else '-' if x==-1 else str(x)

from math import gcd

def para_to_rect(eqn1, eqn2):
    a,b = extract(eqn1)
    k,d = extract(eqn2)
    l = -a
    m = k*b-a*d
    g = gcd(gcd(k,l),m)
    if k*g<0:
        g = -g
    k //= g
    l //= g
    m //= g
    return f'{quotient(k)}x {"+-"[l<0]} {quotient(abs(l))}y = {m}'


Solve in Python:
### The Problem

Consider a flat board with pegs sticking out of one side. If you stretched a rubber band across the outermost pegs what is the set of pegs such that all other pegs are contained within the shape formed by the rubber band?

![alt text](https://upload.wikimedia.org/wikipedia/commons/b/bc/ConvexHull.png)

More specifically, for this kata you will be given a list of points represented as ```[x,y]``` co-ordinates. Your aim will be to return a sublist containing points that form the perimeter of a polygon that encloses all other points contained within the original list.

### Notes:

The tests may include duplicate and/or co-linear points. Co-linear points are a set of points which fall on the same straight line. Neither should be included in your returned sublist

For simplicity, there will always be at least 3 points

### Help:

Check out wikipedia's page on [convex hulls](https://en.wikipedia.org/wiki/Convex_hull)

```if:python
Note for python users: `scipy` module has been disabled.
```

import math

# Check for left turns in constant time
def is_ccw_turn(p0, p1, p2):
    return (p1[0] - p0[0]) * (p2[1] - p0[1]) - (p2[0] - p0[0]) * (p1[1] - p0[1]) > 0

"""
Iteratively generate a hull by finding items with the maximum distance from the current hull, adding them, and repeating.
Currently very inefficient.
"""
def quickhull(points):

    def dist(a, b, c):
        A = b[1]-a[1]
        B = a[0]-b[0]
        C = a[1]*b[0]-a[0]*b[1]
        return abs(A*c[0]+B*c[1]+C)

    def triangle_area(a, b, c):
        return a[0] * (b[1] - c[1]) + b[0] * (c[1] - a[1]) + c[0] * (a[1] - b[1])

    def quickhull_recurse(a, b, targets, indent=1):
        # Remove colinear points
        targets = [p for p in targets if dist(a, b, p) != 0]
        # If no targets exist, be done
        if len(targets) == 0:
            return []
        max_dist = max([dist(a, b, p) for p in targets])
        m = min([p for p in targets if dist(a, b, p) == max_dist])
        l_targets = quickhull_recurse(a, m, [p for p in targets if not is_ccw_turn(m, a, p)], indent+1)
        r_targets = quickhull_recurse(m, b, [p for p in targets if not is_ccw_turn(b, m, p)], indent+1)
        return l_targets + [m] + r_targets

    # Grab two extreme points
    least, most = min(points), max(points)
    # Split into those points above and below
    points = [p for p in points if p != most and p != least]
    top = quickhull_recurse(least, most, [p for p in points if is_ccw_turn(least, most, p)])
    bot = quickhull_recurse(most, least, [p for p in points if not is_ccw_turn(least, most, p)])
    # Generate the final result
    return [least] + top + [most] + bot

"""
Generate a merged hull by splitting the hull arbitrarily, generating two parting hulls, and reconciling.
First, remove all points in hull 2's inner edge, if the centroid of hull 1 is outside hull 2.
Then, reconcile all points into a single queue, ordered by angle, then distance.
Finally, run a graham scan on this new monotone ring.
DOESN'T CURRENTLY RUN TOO...


Solve in Python:
### The Story:
Bob is working as a bus driver. However, he has become extremely popular amongst the city's residents. With so many passengers wanting to get aboard his bus, he sometimes has to face the problem of not enough space left on the bus! He wants you to write a simple program telling him if he will be able to fit all the passengers.

### Task Overview:

You have to write a function that accepts three parameters:
* `cap` is the amount of people the bus can hold excluding the driver.
* `on` is the number of people on the bus.
* `wait` is the number of people waiting to get on to the bus.

If there is enough space, return 0, and if there isn't, return the number of passengers he can't take.

### Usage Examples:

```python
enough(10, 5, 5)
0 # He can fit all 5 passengers
enough(100, 60, 50)
10 # He can't fit 10 out of 50 waiting
```

```if:csharp
Documentation:
Kata.Enough Method (Int32, Int32, Int32)

Returns the number of passengers the bus cannot fit, or 0 if the bus can fit every passenger.

Syntax

public
static
int Enough(
int cap,
    int on,
int wait
    )

Parameters

cap

Type: System.Int32
The amount of people that can fit on the bus excluding the driver.

on

Type: System.Int32
The amount of people on the bus excluding the driver.

wait

Type: System.Int32
The amount of people waiting to enter the bus.

Return Value

Type: System.Int32
  An integer representing how many passengers cannot fit on the bus, or 0 if every passenger can fit on the bus.

```

enough = lambda cap, on, wait: 0 if cap - on - wait >= 0 else abs(cap - on - wait)


Solve in Python:
### The problem

How many zeroes are at the **end** of the [factorial](https://en.wikipedia.org/wiki/Factorial) of `10`? 10! = 3628800, i.e. there are `2` zeroes.
16! (or 0x10!) in [hexadecimal](https://en.wikipedia.org/wiki/Hexadecimal) would be 0x130777758000, which has `3` zeroes.

### Scalability

Unfortunately, machine integer numbers has not enough precision for larger values. Floating point numbers drop the tail we need. We can fall back to arbitrary-precision ones - built-ins or from a library, but calculating the full product isn't an efficient way to find just the _tail_ of a factorial. Calculating `100'000!` in compiled language takes around 10 seconds. `1'000'000!` would be around 10 minutes, even using efficient [Karatsuba algorithm](https://en.wikipedia.org/wiki/Karatsuba_algorithm)

### Your task

is to write a function, which will find the number of zeroes at the end of `(number)` factorial in arbitrary [radix](https://en.wikipedia.org/wiki/Radix) = `base` for larger numbers.

- `base` is an integer from 2 to 256
- `number` is an integer from 1 to 1'000'000

**Note** Second argument: number is always declared, passed and displayed as a regular _decimal_ number. If you see a test described as `42! in base 20` it's 4210 **not** 4220 = 8210.

def zeroes (base, number):
    pzeros = []
    for p in range(2, base+1):
        e = 0
        while base % p == 0:
            base /= p
            e += 1
        if e:
            f, m = 0, number
            while m:
                m /= p
                f += m
            pzeros.append(f / e)
    return min(pzeros)


Solve in Python:
### Tongues

Gandalf's writings have long been available for study, but no one has yet figured out what language they are written in. Recently, due to programming work by a hacker known only by the code name ROT13, it has been discovered that Gandalf used nothing but a simple letter substitution scheme, and further, that it is its own inverse|the same operation scrambles the message as unscrambles it.

This operation is performed by replacing vowels in the sequence `'a' 'i' 'y' 'e' 'o' 'u'` with the vowel three advanced, cyclicly, while preserving case (i.e., lower or upper).

Similarly, consonants are replaced from the sequence `'b' 'k' 'x' 'z' 'n' 'h' 'd' 'c' 'w' 'g' 'p' 'v' 'j' 'q' 't' 's' 'r' 'l' 'm' 'f'` by advancing ten letters.

So for instance the phrase `'One ring to rule them all.'` translates to `'Ita dotf ni dyca nsaw ecc.'`

The fascinating thing about this transformation is that the resulting language yields pronounceable words.  For this problem, you will write code to translate Gandalf's manuscripts into plain text.

Your job is to write a function that decodes Gandalf's writings.

### Input

The function will be passed a string for the function to decode.  Each string will contain up to 100 characters, representing some text written by Gandalf. All characters will be plain ASCII, in the range space (32) to tilde (126).

### Output

For each string passed to the decode function return its translation.

def tongues(code):
    map1 = 'aiyeoubkxznhdcwgpvjqtsrlmf'
    map2 = 'eouaiypvjqtsrlmfbkxznhdcwg'
    return code.translate(str.maketrans(map1+map1.upper(), map2+map2.upper()))


Solve in Python:
### Unfinished Loop - Bug Fixing #1

Oh no, Timmy's created an infinite loop! Help Timmy find and fix the bug in his unfinished for loop!

def create_array(n):
    res=[x+1 for x in range(n)]
    return res


Solve in Python:
### Vaccinations for children under 5
You have been put in charge of administrating vaccinations for children in your local area. Write a function that will generate a list of vaccines for each child presented for vaccination, based on the child's age and vaccination history, and the month of the year.
#### The function takes three parameters: age, status and month
- The parameter 'age' will be given in weeks up to 16 weeks, and thereafter in months. You can assume that children presented will be scheduled for vaccination (eg '16 weeks', '12 months' etc).
- The parameter 'status' indicates if the child has missed a scheduled vaccination, and the argument will be a string that says 'up-to-date', or a scheduled stage (eg '8 weeks') that has been missed, in which case you need to add any missing shots to the list. Only one missed vaccination stage will be passed in per function call.
- If the month is 'september', 'october' or 'november' add 'offer fluVaccine' to the list.
- Make sure there are no duplicates in the returned list, and sort it alphabetically.

#### Example input and output
~~~~
input     ('12 weeks', 'up-to-date', 'december')
output    ['fiveInOne', 'rotavirus']

input     ('12 months', '16 weeks', 'june')
output     ['fiveInOne', 'hibMenC', 'measlesMumpsRubella', 'meningitisB', 'pneumococcal']

input     ('40 months', '12 months', 'october')
output    ['hibMenC', 'measlesMumpsRubella', 'meningitisB', 'offer fluVaccine', 'preSchoolBooster']
~~~~

#### To save you typing it up, here is the vaccinations list
~~~~
fiveInOne : ['8 weeks', '12 weeks', '16 weeks'],
//Protects against: diphtheria, tetanus, whooping cough, polio and Hib (Haemophilus influenzae type b)
pneumococcal : ['8 weeks', '16 weeks'],
//Protects against: some types of pneumococcal infection
rotavirus : ['8 weeks', '12 weeks'],
//Protects against: rotavirus infection, a common cause of childhood diarrhoea and sickness
meningitisB : ['8 weeks', '16 weeks', '12 months'],
//Protects against: meningitis caused by meningococcal type B...

from itertools import chain

def vaccine_list(age, status, month):
    flu_months = ['september','october','november']
    vac_sched = {'8 weeks': ['fiveInOne', 'pneumococcal', 'rotavirus', 'meningitisB'],
                   '12 weeks': ['fiveInOne', 'rotavirus'],
                   '16 weeks': ['fiveInOne', 'pneumococcal', 'meningitisB'],
                   '12 months': ['meningitisB', 'hibMenC', 'measlesMumpsRubella'],
                   '40 months': ['measlesMumpsRubella', 'preSchoolBooster']}

    if status == 'up-to-date':
              status = age

    vac_time = list(vac_sched.keys())
    vacs_toDo = [v for k,v in vac_sched.items() if k in [status, age]]

    vac_list = list(set(list(chain.from_iterable(vacs_toDo))))

    if month in flu_months:
              vac_list.append('offer fluVaccine')

    return sorted(vac_list)


Solve in Python:
### What is simplifying a square root?

If you have a number, like 80, for example, you would start by finding the greatest perfect square divisible by 80. In this case, that's 16. Find the square root of 16, and multiply it by 80 / 16. Answer = 4 √5.

##### The above example:

![simplify_roots_example.png](https://i.postimg.cc/gjv2NwCm/simplify-roots-example.png)

### Task:

Your job is to write two functions, `simplify`, and `desimplify`, that simplify and desimplify square roots, respectively. (Desimplify isn't a word, but I couldn't come up with a better way to put it.) `simplify` will take an integer and return a string like "x sqrt y", and `desimplify` will take a string like "x sqrt y" and return an integer. For `simplify`, if a square root cannot be simplified, return "sqrt y".

_Do not modify the input._

### Some examples:

```python
simplify(1)  #=> "1"
simplify(2)  #=> "sqrt 2"
simplify(3)  #=> "sqrt 3"
simplify(8)  #=> "2 sqrt 2"
simplify(15) #=> "sqrt 15"
simplify(16) #=> "4"
simplify(18) #=> "3 sqrt 2"
simplify(20) #=> "2 sqrt 5"
simplify(24) #=> "2 sqrt 6"
simplify(32) #=> "4 sqrt 2"

desimplify("1")        #=> 1
desimplify("sqrt 2")   #=> 2
desimplify("sqrt 3")   #=> 3
desimplify("2 sqrt 2") #=> 8
desimplify("sqrt 15")  #=> 15
desimplify("4")        #=> 16
desimplify("3 sqrt 2") #=> 18
desimplify("2 sqrt 5") #=> 20
desimplify("2 sqrt 6") #=> 24
desimplify("4 sqrt 2") #=> 32
```

Also check out my other creations — [Square Roots: Approximation](https://www.codewars.com/kata/square-roots-approximation), [Square and Cubic Factors](https://www.codewars.com/kata/square-and-cubic-factors), [Keep the Order](https://www.codewars.com/kata/keep-the-order), [Naming Files](https://www.codewars.com/kata/naming-files), [Elections: Weighted Average](https://www.codewars.com/kata/elections-weighted-average), [Identify Case](https://www.codewars.com/kata/identify-case), [Split Without Loss](https://www.codewars.com/kata/split-without-loss), [Adding...

def simplify(n):
    if (n ** 0.5) % 1 == 0:
        return f"{int(n**0.5)}"
    d = 1
    r = n
    for i in range(n//2, 1,-1):
        if n % i == 0 and (i**0.5) % 1 == 0:
            r = n // i
            d = int(i**0.5)
            break
    return f"{d} sqrt {r}" if d > 1 else f"sqrt {r}"

def desimplify(s):
    if s.find("sqrt") == -1:
        return int(s) ** 2
    elif s.count(" ") == 1:
        return int(s[s.index(" ")+1: ])
    else:
        n1 = int(s[:s.index(" ")])
        n2 = int(s[s.rindex(" ")+1: ])
        return n1**2 * n2


Solve in Python:
### self_converge
`Goal`: Given a number (with a minimum of 3 digits), return the number of iterations it takes to arrive at a derived number that converges on to itself, as per the following [Kaprekar][Kaprekar] routine. As a learning exercise, come up with a solution that uses recursion. The
following steps would be applicable to a number that originally had
exactly 4 digits.

0. Initialize a counter to count the number of iterations
1. Take any four-digit number `n`, using at least two different digits.
2. Arrange the digits in descending and then in ascending order to get two four-digit numbers, adding leading zeros if necessary.
    - Add as many zeroes so that the width of the original number is maintained.
3. Subtract the smaller number from the bigger number. Let us call this `nseq`.
4. Check if `nseq` (the remainder) from Step 4 equals the previous value of `n`. If not, increment the iteration counter and go back to step 2 and perform it on the `nseq`.

If the number of digits to start with was more than 4, convergence occurs on to a `cycle` of numbers. Therefore in Step 5, detect this cycle by comparing to not only the previous value, but to all previous values of `n`.
  - If there is a match, then return the count of iterations
  - If the sequence_number collapses to zero, then return -1

[Kaprekar]: http://mathworld.wolfram.com/KaprekarRoutine.html

### Converge values
While 3-digit numbers converge to the same unique number `k` which is also 3 digits long, all 4-digit numbers also converge to the same unique value `k1` which is 4 digits long. However, 5 digit numbers converge to any one of the following values: `53955, 59994, 61974, 62964, 63954, 71973, 74943, 75933, 82962, 83952`.

### Example
`1234`  ->   `4`
```
1. 4321 - 1234 =  3087 /
2. 8730 - 378  =  8352 /
3. 8532 - 2358 =  6174 /
4. 7641 - 1467 =  6174 // same as previous
```
`414` -> `5`
```
1. 441 - 144 =  297 /
2. 972 - 279 =  693 /
3. 963 - 369 =  594 /
4. 954 - 459 =  495 /
5. 954 - 459 =  495 // same as...

def self_converge(number):
  digits = len(str(number))
  if digits < 3 or number % int('1' * digits) == 0: return -1
  fmtstr = '%%0%dd' % digits
  log = [ number ]
  while True:
    nstr = fmtstr % number
    low = int(''.join(sorted(nstr)))
    high = int(''.join(sorted(nstr, reverse=True)))
    nextn = high - low
    if nextn in log: return len(log)
    log.append(nextn)
    number = nextn


Solve in Python:
#### Background:

A linear regression line has an equation in the form `$Y = a + bX$`, where `$X$` is the explanatory variable and `$Y$` is the dependent variable. The parameter `$b$` represents the *slope* of the line, while `$a$` is called the *intercept* (the value of `$y$` when `$x = 0$`).

For more details visit the related [wikipedia page](http://en.wikipedia.org/wiki/Simple_linear_regression).

---
---
#### Task:
The function that you have to write accepts two list/array, `$x$` and `$y$`,  representing the coordinates of the points to regress (so that, for example, the first point has coordinates (`x[0], y[0]`)).

Your function should return a tuple (in Python) or an array (any other language) of two elements: `a` (intercept) and `b` (slope) in this order.

You must round your result to the first 4 decimal digits

#### Formula:

`$x_i$` and `$y_i$` is `$x$` and `$y$` co-ordinate of `$i$`-th point;
`$n$` is length of input.

`$a =  \dfrac{\sum x_i^2\cdot \sum y_i - \sum x_i \cdot\sum x_iy_i}{n\sum x_i^2 - (\sum x_i)^2}$`

`$b =  \dfrac{n\sum x_i y_i - \sum x_i \cdot \sum y_i}{n\sum x^2_i - (\sum x_i)^2}$`
#### Examples:

```python
regressionLine([25,30,35,40,45,50], [78,70,65,58,48,42]) == (114.381, -1.4457)

regressionLine([56,42,72,36,63,47,55,49,38,42,68,60], [147,125,160,118,149,128,150,145,115,140,152,155]) == (80.7777, 1.138)
```
----

def regressionLine(x, y):
    n, sx, sy = len(x), sum(x), sum(y)
    sxy = sum(i * j for i, j in zip(x, y))
    sx_2, s_x2 = sx ** 2, sum(i * i for i in x)
    a = (s_x2 * sy - sx * sxy) / (n * s_x2 - sx_2)
    b = (n * sxy - sx * sy) / (n * s_x2 - sx_2)
    return round(a, 4), round(b, 4)


Solve in Python:
#### Task:

Your job here is to implement a function `factors`, which takes a number `n`, and outputs an array of arrays comprised of two
parts, `sq` and `cb`. The part `sq` will contain all the numbers that, when squared, yield a number which is a factor of `n`,
while the `cb` part will contain all the numbers that, when cubed, yield a number which is a factor of `n`.  Discard all `1`s
from both arrays.

Both `sq` and `cb` should be sorted in ascending order.

#### What it looks like:

```python
factors(int) #=> [
  sq (all the numbers that can be squared to give a factor of n) : list,
  cb (all the numbers that can be cubed   to give a factor of n) : list
]
```

#### Some examples:

Also check out my other creations — [Keep the Order](https://www.codewars.com/kata/keep-the-order), [Naming Files](https://www.codewars.com/kata/naming-files), [Elections: Weighted Average](https://www.codewars.com/kata/elections-weighted-average), [Identify Case](https://www.codewars.com/kata/identify-case), [Split Without Loss](https://www.codewars.com/kata/split-without-loss), [Adding Fractions](https://www.codewars.com/kata/adding-fractions),
[Random Integers](https://www.codewars.com/kata/random-integers), [Implement String#transpose](https://www.codewars.com/kata/implement-string-number-transpose), [Implement Array#transpose!](https://www.codewars.com/kata/implement-array-number-transpose), [Arrays and Procs #1](https://www.codewars.com/kata/arrays-and-procs-number-1), and [Arrays and Procs #2](https://www.codewars.com/kata/arrays-and-procs-number-2).

If you notice any issues or have any suggestions/comments whatsoever, please don't hesitate to mark an issue or just comment. Thanks!

def factors(n):
    sq = lambda x: x**2
    cb = lambda x: x**3
    return [[x for x in range(2, n) if n % sq(x) == 0], [x for x in range(2, n) if n % cb(x) == 0]]


Solve in Python:
#### Task:

Your job here is to implement a method, `approx_root` in Ruby/Python/Crystal and `approxRoot` in JavaScript/CoffeeScript, that takes one argument, `n`, and returns the approximate square root of that number, rounded to the nearest hundredth and computed in the following manner.

1.      Start with `n = 213` (as an example).
2.      To approximate the square root of n, we will first find the greatest perfect square that is below or equal to `n`. (In this example, that would be 196, or 14 squared.) We will call the square root of this number (which means sqrt 196, or 14) `base`.
3.      Then, we will take the lowest perfect square that is greater than or equal to `n`. (In this example, that would be 225, or 15 squared.)
4.      Next, subtract 196 (greatest perfect square less than or equal to `n`) from `n`. (213 - 196 = **17**) We will call this value `diff_gn`.
5.      Find the difference between the lowest perfect square greater than or equal to `n` and the greatest perfect square less than or equal to `n`. (225 – 196 = **29**) We will call this value `diff_lg`.
6.      Your final answer is `base` + (`diff_gn` / `diff_lg`). In this example: 14 + (17 / 29) which is 14.59, rounded to the nearest hundredth.

Just to clarify, if the input is a perfect square itself, you should return the exact square of the input.

In case you are curious, the approximation (computed like above) for 213 rounded to four decimal places is 14.5862. The actual square root of 213 is 14.5945.

Inputs will always be positive whole numbers. If you are having trouble understanding it, let me know with a comment, or take a look at the second group of the example cases.

#### Some examples:

```python
approx_root(400) #=> 20
approx_root(401) #=>
  # smallest perfect square above 401 is 441 or 21 squared
  # greatest perfect square below 401 is 400 or 20 squared
  # difference between 441 and 400 is 41
  # difference between 401 and 400 is 1
  # answer is 20 + (1 / 41) which becomes 20.02, rounded to the nearest hundredth
  #...

def approx_root(n):
    b = int(n ** 0.5)
    diff_gn = n - b**2
    diff_lg = (b+1)**2 - b**2
    return round(b + (diff_gn / diff_lg), 2)


Solve in Python:
#### Task:

Your job here is to write a function (`keepOrder` in JS/CoffeeScript, `keep_order` in Ruby/Crystal/Python, `keeporder` in Julia), which takes a sorted array `ary` and a value `val`, and returns the lowest index where you could insert `val` to maintain the sorted-ness of the array. The input array will always be sorted in ascending order. It may contain duplicates.

_Do not modify the input._

#### Some examples:

```python
keep_order([1, 2, 3, 4, 7], 5) #=> 4
                      ^(index 4)
keep_order([1, 2, 3, 4, 7], 0) #=> 0
          ^(index 0)
keep_order([1, 1, 2, 2, 2], 2) #=> 2
                ^(index 2)
```

Also check out my other creations — [Naming Files](https://www.codewars.com/kata/naming-files), [Elections: Weighted Average](https://www.codewars.com/kata/elections-weighted-average), [Identify Case](https://www.codewars.com/kata/identify-case), [Split Without Loss](https://www.codewars.com/kata/split-without-loss), [Adding Fractions](https://www.codewars.com/kata/adding-fractions),
[Random Integers](https://www.codewars.com/kata/random-integers), [Implement String#transpose](https://www.codewars.com/kata/implement-string-number-transpose), [Implement Array#transpose!](https://www.codewars.com/kata/implement-array-number-transpose), [Arrays and Procs #1](https://www.codewars.com/kata/arrays-and-procs-number-1), and [Arrays and Procs #2](https://www.codewars.com/kata/arrays-and-procs-number-2).

If you notice any issues or have any suggestions/comments whatsoever, please don't hesitate to mark an issue or just comment. Thanks!

def keep_order(ary, val):

    if val not in ary:

        ary.append(val)

    ary.sort()

    return ary.index(val)


Solve in Python:
###BACKGROUND:
Jacob recently decided to get healthy and lose some weight. He did a lot of reading and research and after focusing on steady exercise and a healthy diet for several months, was able to shed over 50 pounds! Now he wants to share his success, and has decided to tell his friends and family how much weight they could expect to lose if they used the same plan he followed.

Lots of people are really excited about Jacob's program and they want to know how much weight they would lose if they followed his plan. Unfortunately, he's really bad at math, so he's turned to you to help write a program that will calculate the expected weight loss for a particular person, given their weight and how long they think they want to continue the plan.

###TECHNICAL DETAILS:
Jacob's weight loss protocol, if followed closely, yields loss according to a simple formulae, depending on gender. Men can expect to lose 1.5% of their current body weight each week they stay on plan. Women can expect to lose 1.2%. (Children are advised to eat whatever they want, and make sure to play outside as much as they can!)

###TASK:
Write a function that takes as input:
```
- The person's gender ('M' or 'F');
- Their current weight (in pounds);
- How long they want to stay true to the protocol (in weeks);
```
and then returns the expected weight at the end of the program.

###NOTES:
Weights (both input and output) should be decimals, rounded to the nearest tenth.
Duration (input) should be a whole number (integer). If it is not, the function should round to the nearest whole number.
When doing input parameter validity checks, evaluate them in order or your code will not pass final tests.

def lose_weight(gender, weight, duration):
    if gender not in ('M','F'):
        return 'Invalid gender'
    if weight <= 0:
        return 'Invalid weight'
    if duration <= 0:
        return 'Invalid duration'
    factor = 0.985 if gender == 'M' else 0.988
    expected_weight = factor**duration * weight
    return round(expected_weight,1)


Solve in Python:
###Instructions

A time period starting from ```'hh:mm'``` lasting until ```'hh:mm'``` is stored in an array:
```
['08:14', '11:34']
```
A set of different time periods is then stored in a 2D Array like so, each in its own sub-array:
```
[['08:14','11:34'], ['08:16','08:18'], ['22:18','01:14'], ['09:30','10:32'], ['04:23','05:11'], ['11:48','13:48'], ['01:12','01:14'], ['01:13','08:15']]
```
Write a function that will take a 2D Array like the above as argument and return a 2D Array of the argument's sub-arrays sorted in ascending order.

Take note of the following:

* The first time period starts at the earliest time  possible ```('00:00'+)```.
* The next time period is the one that starts the soonest **after** the prior time period finishes. If several time periods begin at the same hour, pick the first one showing up in the original array.
* The next time period can start the same time the last one finishes.

This:
```
[['08:14','11:34'], ['08:16','08:18'], ['13:48','01:14'], ['09:30','10:32'], ['04:23','05:11'], ['11:48','13:48'], ['01:12','01:14'], ['01:13','08:15']]
```
Should return:
```
[['01:12','01:14'], ['04:23','05:11'], ['08:14','11:34'], ['11:48','13:48'], ['13:48','01:14'], ['08:16','08:18'], ['09:30','10:32'], ['01:13','08:15']]
```

def sort_time(arr):
    if len(arr) == 0:
        return []
    r_max = '23:59'
    r_min = '00:00'
    rr = arr[:]
    ret = []
    k = 0
    for i in range(len(arr)):
        for j in range(len(rr)):
            if r_min <= rr[j][0] < r_max:
                r_max = rr[j][0]
                k = j
                if r_max == r_min:
                    break
        ret.append(rr[k])
        r_min = rr[k][1]
        r_max = '23:59'
        rr.pop(k)
        k == 0
        if rr and max(rr)[0] < r_min:
            r_min = min(rr)[0]
    return ret


Solve in Python:
###Instructions

Write a function that takes a negative or positive integer, which represents the number of minutes before (-) or after (+) Sunday midnight, and returns the current day of the week and the current time in 24hr format ('hh:mm') as a string.

```python
day_and_time(0)       should return 'Sunday 00:00'
day_and_time(-3)      should return 'Saturday 23:57'
day_and_time(45)      should return 'Sunday 00:45'
day_and_time(759)     should return 'Sunday 12:39'
day_and_time(1236)    should return 'Sunday 20:36'
day_and_time(1447)    should return 'Monday 00:07'
day_and_time(7832)    should return 'Friday 10:32'
day_and_time(18876)   should return 'Saturday 02:36'
day_and_time(259180)  should return 'Thursday 23:40'
day_and_time(-349000) should return 'Tuesday 15:20'
```

def day_and_time(mins):
    dow = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
    return "{} {:02d}:{:02d}".format(dow[(mins // 1440) % 7], (mins // 60) % 24, mins % 60)


Solve in Python:
###Introduction

The [I Ching](https://en.wikipedia.org/wiki/I_Ching) (Yijing, or Book of Changes) is an ancient Chinese book of sixty-four hexagrams.
A hexagram is a figure composed of six stacked horizontal lines, where each line is either Yang (an unbroken line) or Yin (a broken line):
```
---------    ---- ----    ---------
---- ----    ---- ----    ---------
---- ----    ---- ----    ---------
---------    ---- ----    ---- ----
---------    ---------    ---- ----
---- ----    ---- ----    ---------
```
The book is commonly used as an oracle. After asking it a question about one's present scenario,
each line is determined by random methods to be Yang or Yin. The resulting hexagram is then interpreted by the querent as a symbol of their current situation, and how it might unfold.

This kata will consult the I Ching using the three coin method.

###Instructions

A coin is flipped three times and lands heads
or tails. The three results are used to
determine a line as being either:
```
3 tails          ----x----  Yin (Moving Line*)
2 tails 1 heads  ---------  Yang
1 tails 2 heads  ---- ----  Yin
3 heads          ----o----  Yang (Moving Line*)

*See bottom of description if curious.
```
This process is repeated six times to determine
each line of the hexagram. The results of these
operations are then stored in a 2D Array like so:
In each array the first index will always be the number of the line ('one' is the bottom line, and 'six' the top), and the other three values will be the results of the coin flips that belong to that line as heads ('h') and tails ('t').

Write a function that will take a 2D Array like the above as argument and return its hexagram as a string. Each line of the hexagram should begin on a new line.

should return:
```
---------
---------
----x----
----o----
---- ----
---- ----
```
You are welcome to consult your new oracle program with a question before pressing submit. You can compare your result [here](http://www.ichingfortune.com/hexagrams.php). The last...


Solve in Python:
###Lucky number

Write a function to find if a number is lucky or not. If the sum of all digits is 0 or multiple of 9 then the number is lucky.

`1892376 => 1+8+9+2+3+7+6 = 36`. 36 is divisble by 9, hence number is lucky.

Function will return `true` for lucky numbers and `false` for others.

def is_lucky(n):
    sum = 0
    for number in str(n):
        sum += int(number)
    return sum % 9 == 0


Solve in Python:
###Story
Sometimes we are faced with problems when we have a big nested dictionary with which it's hard to work. Now, we need to solve this problem by writing a function that will flatten a given dictionary.

###Info
Python dictionaries are a convenient data type to store and process configurations. They allow you to store data by keys to create nested structures. You are given a dictionary where the keys are strings and the values are strings or dictionaries. The goal is flatten the dictionary, but save the structures in the keys. The result should be a dictionary without the nested dictionaries. The keys should contain paths that contain the parent keys from the original dictionary. The keys in the path are separated by a `/`. If a value is an empty dictionary, then it should be replaced by an empty string `""`.

###Examples
```python
{
    "name": {
        "first": "One",
        "last": "Drone"
    },
    "job": "scout",
    "recent": {},
    "additional": {
        "place": {
            "zone": "1",
            "cell": "2"
        }
    }
}
```
The result will be:
```python
{"name/first": "One",           #one parent
 "name/last": "Drone",
 "job": "scout",                #root key
 "recent": "",                  #empty dict
 "additional/place/zone": "1",  #third level
 "additional/place/cell": "2"}
```

***`Input: An original dictionary as a dict.`***
***`Output: The flattened dictionary as a dict.`***
***`Precondition:
Keys in a dictionary are non-empty strings.
Values in a dictionary are strings or dicts.
root_dictionary != {}`***

```python
flatten({"key": "value"}) == {"key": "value"}
flatten({"key": {"deeper": {"more": {"enough": "value"}}}}) == {"key/deeper/more/enough": "value"}
flatten({"empty": {}}) == {"empty": ""}
```

def flatten(d):
    result = {}
    for key, value in d.items():
        if value and isinstance(value, dict):
            for k, v in flatten(value).items():
                result[key + '/' + k] = v
        else:
            result[key] = value or ''
    return result


from itertools import cycle, islice

def f(n):
    it = cycle('1234567890')
    xs = ''.join(islice(it, 0, n-1))
    return xs + next(it) + xs[::-1]

def pattern(n):
    m = n * 2 - 1
    return '\n'.join(
        '{:^{}}'.format(f(i), m)
        for i in range(1, n+1)
    )


def pattern(n):
    p = ' ' * (n - 1) + ''.join(str(x % 10) for x in range(1, n + 1)) + ' ' * (n - 1)
    return "\n".join(p[x:x + 2 * n - 1] for x in range(n))


Solve in Python:
###Task:

You have to write a function `pattern` which creates the following pattern (see examples) up to the desired number of rows.

* If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string.

* If any even number is passed as argument then the pattern should last upto the largest odd number which is smaller than the passed even number.

###Examples:

pattern(9):

    1
    333
    55555
    7777777
    999999999

pattern(6):

    1
    333
    55555

```Note: There are no spaces in the pattern```

```Hint: Use \n in string to jump to next line```

def pattern(n):
    string = ""
    a = n;
    if a % 2 == 0:
        a -= 1;
    for x in range (1, a + 1):
        if x % 2 != 0:
            string += str(x) * x

            if x != a:
                string += "\n"
    return string

    # Happy Coding ^_^


Solve in Python:
##Background - the Collatz Conjecture:

Imagine you are given a positive integer, `n`, then:

* if `n` is even, calculate: `n / 2`
* if `n` is odd, calculate: `3 * n + 1`

Repeat until your answer is `1`. The Collatz conjecture states that performing this operation repeatedly, you will always eventually reach `1`.

You can try creating Collatz sequences with [this](http://www.codewars.com/kata/5286b2e162056fd0cb000c20) kata. For further information, see the [wiki page](https://en.wikipedia.org/wiki/Collatz_conjecture).

##Now! Your task:

**Given an array of positive integers, return the integer whose Collatz sequence is the longest.**

Example:

```python
longest_collatz([2, 4, 3])==3
```

Explanation: The Collatz sequence for `2` has a length of `1`, the sequence for `4` has a length of `2`, and the sequence for `3` has a length of `7`. So from our array, the integer `3` is the one with the longest Collatz sequence.

Hence, your function should return `3`.

##Note:

There may be more than one answer, i.e. two or more integers produce the longest Collatz sequence, because they happen to have sequences of the same length. **In this case, your function should return the integer that appears first in the array.**

Example:
Given an array: `[2, 5, 32]`, both `5` and `32` have Collatz sequences of length 5. These are also the longest sequences from our array.

In this case, our function returns `5`, because `5` comes before `32` in our array.

def longest_collatz(lst):
    return max(lst, key=seq_len)

def seq_len(n):
    count = 0
    while n > 1:
        n = (3 * n + 1) if n % 2 else (n // 2)
        count += 1
    return count

# two-liner
#seq_len = lambda n: 0 if n == 1 else 1 + seq_len(3 * n + 1 if n % 2 else n // 2)
#longest_collatz = lambda lst: max(lst, key=seq_len)


Solve in Python:
##Overview

Write a helper function that takes in a Time object and converts it to a more human-readable format. You need only go up to '_ weeks ago'.
```python
to_pretty(0) => "just now"

to_pretty(40000) => "11 hours ago"
```
##Specifics
 - The output will be an amount of time, t, included in one of the following phrases: "just now", "[t] seconds ago", "[t] minutes ago", "[t] hours ago", "[t] days ago", "[t] weeks ago".
 - You will have to handle the singular cases. That is, when t = 1, the phrasing will be one of "a second ago", "a minute ago", "an hour ago", "a day ago", "a week ago".
 - The amount of time is always rounded down to the nearest integer. For example, if the amount of time is actually 11.73 hours ago, the return value will be "11 hours ago".
 - Only times in the past will be given, with the range "just now" to "52 weeks ago"

CONFIG = [
    ('',"week",3600*24*7),
    ('',"day",3600*24),
    ('n',"hour",3600),
    ('',"minute",60),
    ('',"second",1)
]

def to_pretty(s):
    return next((out(one,t,s//n) for one,t,n in CONFIG if s//n), "just now")

def out(one,t,n):
    return f'{n==1 and "a"+one or n} {t}{n>1 and "s" or ""} ago'


Solve in Python:
##Task:

You have to write a function **pattern** which creates the following pattern upto n number of rows.

* If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string.

* If any odd number is passed as argument then the pattern should last upto the largest even number which is smaller than the passed odd number.

* If the argument is 1 then also it should return "".

##Examples:

pattern(8):

    22
    4444
    666666
    88888888

pattern(5):

    22
    4444

```Note: There are no spaces in the pattern```

```Hint: Use \n in string to jump to next line```

def pattern(n):
    return '\n'.join(str(i) * i for i in range(2, n//2*2 + 1, 2))


Solve in Python:
##Task:

You have to write a function **pattern** which creates the following pattern upto n number of rows. *If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string.*

##Pattern:

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

##Examples:

pattern(4):

    4
    43
    432
    4321

pattern(6):

    6
    65
    654
    6543
    65432
    654321

```Note: There are no blank spaces```

```Hint: Use \n in string to jump to next line```

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


Solve in Python:
##Task:

You have to write a function **pattern** which creates the following pattern upto n number of rows. *If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string.*

##Examples:

pattern(4):

    1234
    234
    34
    4

pattern(6):

    123456
    23456
    3456
    456
    56
    6

```Note: There are no blank spaces```

```Hint: Use \n in string to jump to next line```

def pattern(n):
    return '\n'.join(''.join(str(i + 1) for i in range(n)[j:]) for j in range(n))


Solve in Python:
##Task:
You have to write a function `add` which takes two binary numbers as strings and returns their sum as a string.

##Note:
* You are `not allowed to convert binary to decimal & vice versa`.
* The sum should contain `No leading zeroes`.

##Examples:
```
add('111','10'); => '1001'
add('1101','101'); => '10010'
add('1101','10111') => '100100'
```

def add(a,b):
    out = ""
    carry = 0

    a = a.lstrip("0")
    b = b.lstrip("0")

    max_l = max(len(a), len(b))
    a = a.rjust(max_l, "0")
    b = b.rjust(max_l, "0")

    for i in range(1, max_l + 1):
        s, carry = carry, 0
        s += 1 if a[-i] == "1" else 0
        s += 1 if b[-i] == "1" else 0

        carry = s > 1
        out += "01"[s%2]

    out += "1"*carry
    return out[::-1] if len(out) > 0 else "0"


Solve in Python:
#Adding values of arrays in a shifted way

You have to write a method, that gets two parameter:

```markdown
1. An array of arrays with int-numbers
2. The shifting value
```

#The method should add the values of the arrays to one new array.

The arrays in the array will all have the same size and this size will always be greater than 0.
The shifting value is always a value from 0 up to the size of the arrays.
There are always arrays in the array, so you do not need to check for null or empty.

#1. Example:
```
[[1,2,3,4,5,6], [7,7,7,7,7,-7]], 0

1,2,3,4,5,6
7,7,7,7,7,-7

--> [8,9,10,11,12,-1]
```

#2. Example
```
[[1,2,3,4,5,6], [7,7,7,7,7,7]], 3

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

--> [1,2,3,11,12,13,7,7,7]
```

#3. Example
```
[[1,2,3,4,5,6], [7,7,7,-7,7,7], [1,1,1,1,1,1]], 3

1,2,3,4,5,6
      7,7,7,-7,7,7
            1,1,1,1,1,1

--> [1,2,3,11,12,13,-6,8,8,1,1,1]
```

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.

from itertools import zip_longest

def sum_arrays(arrays, shift):
    shifted = [([0] * shift * i) + array for i, array in enumerate(arrays)]
    return [sum(nums) for nums in zip_longest(*shifted, fillvalue=0)]


Solve in Python:
#Bubbleing around

Since everybody hates chaos and loves sorted lists we should implement some more sorting algorithms. Your task is to implement a Bubble sort (for some help look at https://en.wikipedia.org/wiki/Bubble_sort) and return a list of snapshots after **each change** of the initial list.

e.g.

If the initial list would be l=[1,2,4,3] my algorithm rotates l[2] and l[3] and after that it adds [1,2,3,4] to the result, which is a list of snapshots.
```
[1,2,4,3] should return [ [1,2,3,4] ]
[2,1,4,3] should return [ [1,2,4,3], [1,2,3,4] ]
[1,2,3,4] should return []
```

def bubble(a):
    if a == None or len(a) < 2 :
        return []
    swapped = True
    i = 0
    r = []
    while i < len(a) - 1 and swapped:
        swapped = False
        for j in range(len(a) - i - 1):
            if a[j] > a[j + 1]:
                a[j], a[j+1] = a[j+1], a[j]
                r.append(list(a))
                swapped = True
        i += 1
    return r