Solve in Python:
Hi guys, welcome to introduction to DocTesting.

The kata is composed of two parts; in part (1) we write three small functions, and in part (2) we write a few doc tests for those functions.

Lets talk about the functions first...

    The reverse_list function takes a list and returns the reverse of it.
    If given an empty list, simply return an empty list.

The second function...

    The sum_list function takes a list as input and adds up all the values,
    returning an integer. If the list is empty, return 0.

The third function...

    The head_of_list function simply returns the first item in the list.
    If the list is empty return None.

Each of these functions can be easily written with a single line of code; there are some tests for correctness but no tests for effciency.

Once you have implemented all three of these functions you can move onto phase two, which is writing doc tests. If you haven't written doc tests before then I suggest you check out the following documentation:
https://docs.python.org/3/library/doctest.html

To complete this kata all you have to do is write **EXACTLY TWO** doc tests for each of the three functions (any more/less than that and you will fail the tests).

Here is an example:

    def double(y):
      """Function returns y * 2
      >>> double(2)
      4
      """
      return y * 2

In the example above we have a function called 'double' and a single doctest. When we run the doctest module Python will check if double(2) equals 4. If it does not, then the doctest module will flag up an error.

Please note that this is intended as a beginners introduction to docstrings, if you try to do something clever (such as writing doc tests to catch exceptions, or tinkering with the 'option flags'), you will probably fail a test or two. This is due to how the tests are written.

Oh and one last thing, don't try and get too 'cheeky' and try something like:

    """
    >>> True
    True
    """

such a solution is (a) not in the spirit of things and (b) I got tests for...

def reverse_list(x):
    """Takes an list and returns the reverse of it.
    If x is empty, return [].

    >>> reverse_list([])
    []
    >>> reverse_list([5, 4,3, 2, 1])
    [1, 2, 3, 4, 5]
    """
    return x[::-1]

def sum_list(x):
    """Takes a list, and returns the sum of that list.
    If x is empty list, return 0.

    >>> sum_list([])
    0
    >>> sum_list([1, 2, 3, 4, 5])
    15
    """
    return sum(x)

def head_of_list(x):
    """Takes a list, returns the first item in that list.
    If x is empty, return None

    >>> head_of_list([]) is None
    True
    >>> head_of_list([1, 2, 3, 4, 5])
    1
    """
    return x[0] if x else None


Solve in Python:
Hi there!
You have to implement the

`String get_column_title(int num) // syntax depends on programming language`

function that takes an integer number (index of the Excel column) and returns the string represents the title of this column.

#Intro
In the MS Excel lines are numbered by decimals, columns - by sets of letters.

For example, the first column has the title "A", second column - "B", 26th - "Z", 27th - "AA".

"BA"(53) comes after "AZ"(52), "AAA" comes after "ZZ".

Excel? Columns? More details [here](https://en.wikipedia.org/wiki/Microsoft_Excel)

#Input
It takes only one argument - column decimal index number.
Argument `num` is a natural number.

#Output
Output is the upper-case string represents the title of column. It contains the English letters: A..Z

#Errors
For cases `num < 1` your function should throw/raise `IndexError`. In case of non-integer argument you should throw/raise `TypeError`.

In Java, you should throw `Exceptions`.

Nothing should be returned in Haskell.

#Examples
Python, Ruby:
```
>>> get_column_title(52)
"AZ"
>>> get_column_title(1337)
"AYK"
>>> get_column_title(432778)
"XPEH"
>>> get_column_title()
TypeError:
>>> get_column_title("123")
TypeError:
>>> get_column_title(0)
IndexError:
```
JS, Java:
```
>>> getColumnTitle(52)
"AZ"
>>> getColumnTitle(1337)
"AYK"
>>> getColumnTitle(432778)
"XPEH"
>>> getColumnTitle()
TypeError:
>>> getColumnTitle("123")
TypeError:
>>> getColumnTitle(0)
IndexError:
```

#Hint
The difference between the 26-digits notation and Excel columns numeration that in the first system, after "Z" there are "BA", "BB", ..., while in the Excel columns scale there is a range of 26 elements: AA, AB, ... , AZ between Z and BA.

It is as if in the decimal notation was the following order: 0, 1, 2, .., 9, 00, 01, 02, .., 09, 10, 11, .., 19, 20..29..99, 000, 001 and so on.

#Also
The task is really sapid and hard. If you're stuck - write to the discussion board, there are many smart people willing to help.

upper = __import__("string").ascii_uppercase.__getitem__

def get_column_title(num=None):
    if not isinstance(num, int): raise TypeError()
    if num < 1: raise IndexError()
    res = []
    while num:
        num, r = divmod(num-1, 26)
        res.append(r)
    return ''.join(map(upper, reversed(res)))


Solve in Python:
Hi! Welcome to my first kata.

In this kata the task is to take a list of integers (positive and negative) and split them according to a simple rule; those ints greater than or equal to the key, and those ints less than the key (the itself key will always be positive).

However, in this kata the goal is to sort the numbers IN PLACE, so DON'T go messing around with the order in with the numbers appear.

You are to return a nested list. If the list is empty, simply return an empty list.

Confused? Okay, let me walk you through an example...

    The input is: [1, 1, 1, 0, 0, 6, 10, 5, 10], the key is: 6
Okay so the first five numbers are less than the key, 6, so we group them together.

    [1, 1, 1, 0, 0]
The next two numbers, 6 & 10, are both >= 6 to they belong in a seperate group, which we will add to the first group. Like so:

    [[1, 1, 1, 0, 0], [6, 10]]
The next two numbers are 5 & 10. Since the key is 6 these two numbers form seperate groups, which we will add to the previous result. like so:

    [[1, 1, 1, 0, 0], [6, 10], [5], [10]]
And voila! We're done.

Here are a few more basic examples:

    group_ints([1, 0], key= 0)
    --> [[1,0]]

    group_ints([1, 0, -1, 5], key= 0)
    --> [[1, 0], [-1], [5]]

    group_ints([1, 0, -1, 5], key= 5)
    --> [[1, 0, -1], [5]]

Good luck guys/gals!

def group_ints(lst, key=0):
    if not lst: return []
    l, index = [[lst[0]]], 0
    for x in lst[1:]:
        if l[index][-1] < key and x < key:
            l[index].append(x)
        elif l[index][-1] >= key and x >= key:
            l[index].append(x)
        else:
            l.append([x])
            index += 1
    return l


Solve in Python:
Hilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, including zero and negative integers. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert himself, decides he wants to shuffle the guests around because he thinks this will create a vacancy (a room without a guest).

For any integer $k$ and positive integer $n$, let $k\bmod n$ denote the remainder when $k$ is divided by $n$. More formally, $r=k\bmod n$ is the smallest non-negative integer such that $k-r$ is divisible by $n$. It always holds that $0\le k\bmod n\le n-1$. For example, $100\bmod 12=4$ and $(-1337)\bmod 3=1$.

Then the shuffling works as follows. There is an array of $n$ integers $a_0,a_1,\ldots,a_{n-1}$. Then for each integer $k$, the guest in room $k$ is moved to room number $k+a_{k\bmod n}$.

After this shuffling process, determine if there is still exactly one guest assigned to each room. That is, there are no vacancies or rooms with multiple guests.

-----Input-----

Each test consists of multiple test cases. The first line contains a single integer $t$ ($1\le t\le 10^4$) — the number of test cases. Next $2t$ lines contain descriptions of test cases.

The first line of each test case contains a single integer $n$ ($1\le n\le 2\cdot 10^5$) — the length of the array.

The second line of each test case contains $n$ integers $a_0,a_1,\ldots,a_{n-1}$ ($-10^9\le a_i\le 10^9$).

It is guaranteed that the sum of $n$ over all test cases does not exceed $2\cdot 10^5$.

-----Output-----

For each test case, output a single line containing "YES" if there is exactly one guest assigned to each room after the shuffling process, or "NO" otherwise. You can print each letter in any case (upper or lower).

-----Example-----
Input
6
1
14
2
1 -1
4
5 5 5 1
3
3 2 1
2
0 1
5
-239 -2 -100 -3 -11

Output
YES
YES
YES
NO
NO
YES

-----Note-----

In the first test case, every guest is shifted by $14$...

import sys
input = sys.stdin.readline

t = int(input())
out = []
for i in range(t):
    n = int(input())
    l = list([int(x) % n for x in input().split()])

    taken = [False] * n
    for i in range(n):
        taken[(i + l[i]) % n] = True

    for i in range(n):
        if not taken[i]:
            out.append('NO')
            break
    else:
        out.append('YES')
print('\n'.join(out))


Solve in Python:
Ho ho! So you think you know integers, do you? Well then, young wizard, tell us what the Nth digit of the [Champernowne constant](https://en.wikipedia.org/wiki/Champernowne_constant) is!

The constant proceeds like this: `0.12345678910111213141516...`

I hope you see the pattern!

Conjure a function that will accept an integer, `n`, and return the (one-indexed) `n`th digit of Champernowne's constant. Can you get it to run in _constant_ time?

For example:

`n = 1` should return `0` (the very first digit)

`n = 2` should return `1` (we ignore the period character since it's not a digit!)

`n = 20` should return `4` (that's the `4` in the number `14`, 20th in sequence)

For any invalid values, such as `0` and below, or non-integers, return... `NaN`!

I hope (for your sake) that you've been practicing your mathemagical spells, because a naïve solution will _not_ be fast enough to compete in this championship!

Invoke with _precision_, and be wary of rounding errors in the realms of enormity!

May the best integer win!

def champernowneDigit(n):

    result=float("NaN")
    if type(n)==int and n>0:
        if n<=10:
            result=n-1
        else:
            i=1
            c=10
            while n>c:
                i+=1
                c=c+i*9*10**(i-1)

            number=(n-c)//i+10**i-1
            reste=(n-c)%i
            if reste:
                number+=1
            result=int(str(number)[reste-1])
    return result


Solve in Python:
Ho, Ho, Ho!
It's Christmas time and our friendly grandpa Santa Claus is busy distributing gifts to all the nice children. With the rising population, Santa's workload every year gets increased and he seeks your help to wrap the gifts with fancy wrapping papers while he gets them distributed.
Everything was going great until you realised that you'll fall short of wrapping paper. But luckily, you get a very innovative idea, that will allow you to pack all the remaining gifts without worrying about lack of wrapping paper. Any guesses what the idea is? Using ice for wrapping, obviously! That's the only thing available at the North Pole.
Now, in order to reduce your trips to the ice factory, you decide to write a program that helps you visualize how much ice is needed for a particular gift.

-----Input:-----
Input will consist of a single line with size $n$.

-----Output:-----
Print the ice wrapped gift box for the given size.

-----Constraints-----
- $0 \leq n \leq 1000$

-----Sample Input:-----
4

-----Sample Output:-----
4 4 4 4 4 4 4
4 3 3 3 3 3 4
4 3 2 2 2 3 4
4 3 2 1 2 3 4
4 3 2 2 2 3 4
4 3 3 3 3 3 4
4 4 4 4 4 4 4

try:
    num = int(input())

    MAX = 1000
    def prints(a, size):
        for i in range(size):
            for j in range(size):
                print(a[i][j], end = " ")
            print()
    def innerPattern(n):
        size = 2 * n - 1
        front = 0
        back = size - 1
        a = [[0 for i in range(MAX)]for i in range(MAX)]
        while (n != 0):
            for i in range(front, back + 1):
                for j in range(front, back + 1):
                    if (i == front or i == back or j == front or j == back):
                        a[i][j] = n
            front += 1
            back -= 1
            n -= 1
        prints(a, size)

    innerPattern(num)
except:
    pass


Solve in Python:
Hofstadter sequences are a family of related integer sequences, among which the first ones were described by an American professor Douglas Hofstadter in his book Gödel, Escher, Bach.

### Task
Today we will be implementing the rather chaotic recursive sequence of integers called Hofstadter Q.
The Hofstadter Q is defined as:

As the author states in the aforementioned book:It is reminiscent of the Fibonacci definition in that each new value is a sum of two
previous values-but not of the immediately previous two values. Instead, the two
immediately previous values tell how far to count back to obtain the numbers to be added
to make the new value.
The function produces the starting sequence:
`1, 1, 2, 3, 3, 4, 5, 5, 6 . . .`
Test info: 100 random tests, n is always positive
Good luck!

li = [1, 1]
while len(li) != 1000 : li.append(li[-li[-1]] + li[-li[-2]])
hofstadter_Q=lambda n:li[n-1]


Solve in Python:
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.

As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:  There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.  The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least l_{i} and at most r_{i} have fought for the right to continue taking part in the tournament.  After the i-th fight among all participants of the fight only one knight won — the knight number x_{i}, he continued participating in the tournament. Other knights left the tournament.  The winner of the last (the m-th) fight (the knight number x_{m}) became the winner of the tournament.

You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.

Write the code that calculates for each knight, the name of the knight that beat him.

-----Input-----

The first line contains two integers n, m (2 ≤ n ≤ 3·10^5; 1 ≤ m ≤ 3·10^5) — the number of knights and the number of fights. Each of the following m lines contains three integers l_{i}, r_{i}, x_{i} (1 ≤ l_{i} < r_{i} ≤ n; l_{i} ≤ x_{i} ≤ r_{i}) — the description of the i-th fight.

It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.

-----Output-----

Print n integers. If the i-th knight lost, then the i-th number...

def main():
    n, m = list(map(int, input().split()))
    alive, winner = list(range(1, n + 3)), [0] * (n + 2)
    for _ in range(m):
        l, r, x = list(map(int, input().split()))
        while l < x:
            if winner[l]:
                alive[l], l = x, alive[l]
            else:
                alive[l] = winner[l] = x
                l += 1
        l += 1
        r += 1
        while l < r:
            if winner[l]:
                alive[l], l = r, alive[l]
            else:
                alive[l], winner[l] = r, x
                l += 1
    print(' '.join(map(str, winner[1: -1])))

def __starting_point():
    main()

__starting_point()


Solve in Python:
Hooray! Polycarp turned $n$ years old! The Technocup Team sincerely congratulates Polycarp!

Polycarp celebrated all of his $n$ birthdays: from the $1$-th to the $n$-th. At the moment, he is wondering: how many times he turned beautiful number of years?

According to Polycarp, a positive integer is beautiful if it consists of only one digit repeated one or more times. For example, the following numbers are beautiful: $1$, $77$, $777$, $44$ and $999999$. The following numbers are not beautiful: $12$, $11110$, $6969$ and $987654321$.

Of course, Polycarpus uses the decimal numeral system (i.e. radix is 10).

Help Polycarpus to find the number of numbers from $1$ to $n$ (inclusive) that are beautiful.

-----Input-----

The first line contains an integer $t$ ($1 \le t \le 10^4$) — the number of test cases in the input. Then $t$ test cases follow.

Each test case consists of one line, which contains a positive integer $n$ ($1 \le n \le 10^9$) — how many years Polycarp has turned.

-----Output-----

Print $t$ integers — the answers to the given test cases in the order they are written in the test. Each answer is an integer: the number of beautiful years between $1$ and $n$, inclusive.

-----Example-----
Input
6
18
1
9
100500
33
1000000000

Output
10
1
9
45
12
81

-----Note-----

In the first test case of the example beautiful years are $1$, $2$, $3$, $4$, $5$, $6$, $7$, $8$, $9$ and $11$.

n = int(input())
for i in range(n):
    num = int(input())
    temp = 1
    res = 0
    temp1 = 1
    slog = 1
    slog_temp = 11
    while(temp <= num):
        if(temp < (10 ** temp1)):
            temp += slog
            res += 1
        else:
            temp = slog_temp
            temp1 += 1
            slog = slog_temp
            slog_temp = slog_temp + (10 ** temp1)
    print(res)


Solve in Python:
How can you tell an extrovert from an
introvert at NSA? Va gur ryringbef,
gur rkgebireg ybbxf ng gur BGURE thl'f fubrf.

I found this joke on USENET, but the punchline is scrambled. Maybe you can decipher it?
According to Wikipedia, ROT13 (http://en.wikipedia.org/wiki/ROT13) is frequently used to obfuscate jokes on USENET.

Hint: For this task you're only supposed to substitue characters. Not spaces, punctuation, numbers etc.
Test examples:
```
rot13("EBG13 rknzcyr.") == "ROT13 example.";
rot13("This is my first ROT13 excercise!" == "Guvf vf zl svefg EBG13 rkprepvfr!"
```

def rot13(message):
    index = {}
    az=[chr(i) for i in range(ord("a"),ord("z")+1)]
    AZ=[chr(i) for i in range(ord("A"),ord("Z")+1)]
    azT = az[13:]+az[0:13]
    AZT = AZ[13:]+AZ[0:13]
    t={a:b for a,b in zip(az+AZ,azT+AZT)}

    return "".join([t.get(i,i) for  i in message])


Solve in Python:
How many bees are in the beehive?

* bees can be facing UP, DOWN, LEFT, or RIGHT
* bees can share parts of other bees

Examples

Ex1
```
bee.bee
.e..e..
.b..eeb
```
*Answer: 5*

Ex2
```
bee.bee
e.e.e.e
eeb.eeb
```
*Answer: 8*

# Notes

* The hive may be empty or null/None/nil/...
* Python: the hive is passed as a list of lists (not a list of strings)

def how_many_bees(hive):
    if not hive:
        return 0
    count=0
    for i in range(len(hive)):
        for j in range(len(hive[i])-2):
            compare="".join(hive[i][j:j+3])
            if compare=="bee" or compare=="eeb":
                count+=1
    for i in range(len(hive)-2):
        for j in range(len(hive[i])):
            compare=hive[i][j]+hive[i+1][j]+hive[i+2][j]
            if compare=="bee" or compare=="eeb":
                count+=1
    return count


Solve in Python:
How many days are we represented in a foreign country?

My colleagues make business trips to a foreign country. We must find the number of days our company is represented in a country. Every day that one or more colleagues are present in the country is a day that the company is represented. A single day cannot count for more than one day.

Write a function that recieves a list of pairs and returns the number of days that the company is represented in the foreign country. The first number of the pair is the number of the day of arrival and the second number of the pair is the day of departure of someone who travels, i.e. 1 january is number 1 and 31 of december is 365.

Example:
```python
days_represented([[10,17],[200,207]])
```

Returns 16 because there are two trips of 8 days, which add up to 16.

Happy coding and rank this kata if you wish ;-)

def days_represented(trips):
    accumulator = set()
    for a,b in trips:
        accumulator |= set(range(a, b+1))
    return len(accumulator)


Solve in Python:
How many licks does it take to get to the tootsie roll center of a tootsie pop?

A group of engineering students from Purdue University reported that its licking machine, modeled after a human tongue, took an average of 364 licks to get to the center of a Tootsie Pop. Twenty of the group's volunteers assumed the licking challenge-unassisted by machinery-and averaged 252 licks each to the center.

Your task, if you choose to accept it, is to write a function that will return the number of licks it took to get to the tootsie roll center of a tootsie pop, given some environmental variables.

Everyone knows it's harder to lick a tootsie pop in cold weather but it's easier if the sun is out. You will be given an object of environmental conditions for each trial paired with a value that will increase or decrease the number of licks. The environmental conditions all apply to the same trial.

Assuming that it would normally take 252 licks to get to the tootsie roll center of a tootsie pop, return the new total of licks along with the condition that proved to be most challenging (causing the most added licks) in that trial.

Example:
```
totalLicks({ "freezing temps": 10, "clear skies": -2 });
```
Should return:
```
"It took 260 licks to get to the tootsie roll center of a tootsie pop. The toughest challenge was freezing temps."
```
Other cases:
If there are no challenges, the toughest challenge sentence should be omitted. If there are multiple challenges with the highest toughest amount, the first one presented will be the toughest.
If an environment variable is present, it will be either a positive or negative integer. No need to validate.

Check out my other 80's Kids Katas:

80's Kids #1: How Many Licks Does It Take
80's Kids #2: Help Alf Find His Spaceship
80's Kids #3: Punky Brewster's Socks
80's Kids #4: Legends of the Hidden Temple
80's Kids #5: You Can't Do That on Television
80's Kids #6: Rock 'Em, Sock 'Em Robots
80's Kids #7: She's a Small Wonder
80's Kids #8: The Secret World of Alex Mack
80's Kids #9:...

from operator import itemgetter

TOTAL_LICKS = 252

def total_licks(env):
    message = ('It took %d licks to get to the tootsie roll center of a tootsie pop.' %
               (TOTAL_LICKS + sum(env.values())))

    if env:
        toughest_challenge = max(iter(env.items()), key=itemgetter(1))
        if toughest_challenge[1] > 0:
            message += ' The toughest challenge was %s.' % toughest_challenge[0]

    return message


Solve in Python:
How much bigger is a 16-inch pizza compared to an 8-inch pizza? A more pragmatic question is: How many 8-inch pizzas "fit" in a 16-incher?

The answer, as it turns out, is exactly four 8-inch pizzas. For sizes that don't correspond to a round number of 8-inchers, you must round the number of slices (one 8-inch pizza = 8 slices), e.g.:

```python
how_many_pizzas(16) -> "pizzas: 4, slices: 0"
how_many_pizzas(12) -> "pizzas: 2, slices: 2"
how_many_pizzas(8) -> "pizzas: 1, slices: 0"
how_many_pizzas(6) -> "pizzas: 0, slices: 4"
how_many_pizzas(0) -> "pizzas: 0, slices: 0"
```
Get coding quick, so you can choose the ideal size for your next meal!

def how_many_pizzas(n):
    area = n * n
    eight_area = 64
    total_pizzas = int(area/eight_area)
    slices = 0
    if area % eight_area != 0:
        slices = int((area - (total_pizzas * eight_area))/8)
    return "pizzas: {}, slices: {}".format(total_pizzas, slices)


Solve in Python:
Humpy, the little elephant, has his birthday coming up. He invited all his cousins but doesn’t know how many of them are really coming as some of them are having exams coming up. He will only get to know how many of them are coming on the day of his birthday.

He ordered sugarcane for his party, of length L.

Humpy’s mom decided that she will be dividing the sugarcane among Humty and his friends in a way such that they get the sugarcane in ratio of their ages.

Your task is to determine whether it is possible to serve sugarcane to everyone as integral multiples of their ages.

-----INPUT-----
First line of input contains an integer N, denoting the number of test cases.

Then N test cases follow.

The first line of each test case contains three integers K, L and E. K denoting the number of friends coming; L denoting the length of the sugarcane and E denoting the age of the little elephant. Next line has  K  space separated integers denoting the age of friends who came to the party.

-----OUTPUT-----

For each test case, output “YES” (without quotes) if everyone gets their part as integral multiples of their ages; otherwise output “NO”(without quotes).

-----CONSTRAINTS-----

- 1 <= T<=30
- 1 <= K<=1000
- 1 <= L<=1000000
- 1 <= E<=100000
- 1 <= Age of Cousins<=100000

-----Example-----
Input:
2
4 10 2
2 2 3 1
4 12 3
6 5 7 3

Output:
YES
NO

for __ in range(eval(input())):
 n, l, e = list(map(int, input().split()))
 a = list(map(int, input().split()))
 if l%(sum(a) + e)==0: print('YES')
 else: print('NO')


Solve in Python:
I always thought that my old friend John was rather richer than he looked, but I never knew exactly how much money he actually had. One day (as I was plying him with questions) he said:

* "Imagine I have between `m` and `n` Zloty..." (or did he say Quetzal? I can't remember!)
* "If I were to buy **9** cars costing `c` each, I'd only have 1 Zloty (or was it Meticals?) left."
* "And if I were to buy **7** boats at `b` each, I'd only have 2 Ringglets (or was it Zloty?) left."

Could you tell me in each possible case:

1. how much money `f` he could possibly have ?
2. the cost `c` of a car?
3. the cost `b` of a boat?

So, I will have a better idea about his fortune. Note that if `m-n` is big enough, you might have a lot of possible answers.

Each answer should be given as `["M: f", "B: b", "C: c"]` and all the answers as `[ ["M: f", "B: b", "C: c"], ... ]`. "M" stands for money, "B" for boats, "C" for cars.

**Note:** `m, n, f, b, c` are positive integers, where `0 <= m <= n` or `m >= n >= 0`. `m` and `n` are inclusive.

## Examples:
```
howmuch(1, 100)      => [["M: 37", "B: 5", "C: 4"], ["M: 100", "B: 14", "C: 11"]]
howmuch(1000, 1100)  => [["M: 1045", "B: 149", "C: 116"]]
howmuch(10000, 9950) => [["M: 9991", "B: 1427", "C: 1110"]]
howmuch(0, 200)      => [["M: 37", "B: 5", "C: 4"], ["M: 100", "B: 14", "C: 11"], ["M: 163", "B: 23", "C: 18"]]
```

Explanation of the results for `howmuch(1, 100)`:

* In the first answer his possible fortune is **37**:
 * so he can buy 7 boats each worth 5: `37 - 7 * 5 = 2`
 * or he can buy 9 cars worth 4 each: `37 - 9 * 4 = 1`
* The second possible answer is **100**:
 * he can buy 7 boats each worth 14: `100 - 7 * 14 = 2`
 * or he can buy 9 cars worth 11: `100 - 9 * 11 = 1`

# Note
See "Sample Tests" to know the format of the return.

def howmuch(m, n):
    return [['M: {}'.format(i), 'B: {}'.format(int((i-2)/7)), 'C: {}'.format(int((i-1)/9))]  for i in [i for i in range(min(m,n), max(m+1,n+1)) if i%9 == 1 and i%7 == 2]]


Solve in Python:
I assume most of you are familiar with the ancient legend of the rice (but I see wikipedia suggests [wheat](https://en.wikipedia.org/wiki/Wheat_and_chessboard_problem), for some reason) problem, but a quick recap for you: a young man asks as a compensation only `1` grain of rice for the first square, `2` grains for the second, `4` for the third, `8` for the fourth and so on, always doubling the previous.

Your task is pretty straightforward (but not necessarily easy): given an amount of grains, you need to return up to which square of the chessboard one should count in order to get at least as many.

As usual, a few examples might be way better than thousands of words from me:

```python
squares_needed(0) == 0
squares_needed(1) == 1
squares_needed(2) == 2
squares_needed(3) == 2
squares_needed(4) == 3
```

Input is always going to be valid/reasonable: ie: a non negative number; extra cookie for *not* using a loop to compute square-by-square (at least not directly) and instead trying a smarter approach [hint: some peculiar operator]; a trick converting the number might also work: impress me!

def squares_needed(grains):
    s = 0
    cells = 0
    grains_in_cell = 1
    while s < grains:
      s += grains_in_cell
      grains_in_cell *= 2
      cells += 1
    return cells


Solve in Python:
I found this interesting interview question just today:

> *8 coins are given where all the coins have equal weight, except one. The odd one weights less than the others, not being of pure gold. In the worst case, how many iterations are actually needed to find the odd one out on a two plates scale*.

I am asking you then to tell me what is the *minimum* amount of weighings it will take to measure `n` coins in every possible occurrence (including worst case scenario, ie: without relying on luck at all).

`n` is guaranteed to be a positive integer.

***Tip:*** being able to think *recursively* might help here :p

***Note:*** albeit this is more clearly a logical than a coding problem, do not underestimate (or under-rank) the kata for requiring not necessarily wizard-class coding skills: a good coder is a master of pattern recognition and subsequent optimization ;)

from math import log, ceil

def how_many_measurements(n):
    return ceil(log(n, 3))


Solve in Python:
I have started studying electronics recently, and I came up with a circuit made up of 2 LEDs and 3 buttons.

Here 's how it works: 2 buttons (`red` and `blue`) are connected to the LEDs (`red` and `blue` respectively). Buttons pressing pattern will be remembered and represented through the LEDs when the third button is pressed.

 - Only one LED can blink at a time.
 - The LED will only blink once even if the button is held down.
 - The button must be released to be pressed again.
 - If a button is pressed while the other button is being held down, it will be ignored.
 - If two buttons are pressed simultaneously, the red button will be preferred.
 - If a button is released while the other is being held down, the other 's LED will blink.
 - `0` is up and `1` is down.
 - The two inputs will always have the same length.

Here is an example:

```Python
Red:  "10011010"
Blue: "10110111"
#=> "RBRB"

Red:  "01001000"
Blue: "01011100"
#=> "RB"

Red:  "01101000"
Blue: "00111000"
#=> "RB"
```

PS:

This is my first time making a kata, so there may be some errors.
You may report to me if the description is too confusing.
Sorry for my poor grammar.

def button_sequences(*seqRB):
    wasR, wasB, seq = 0, 0, []
    for r,b in zip(*map(lambda s: map(int,s),seqRB)):
        what             = 'BR'[r]                                            # Ensure precedence of red button
        realeaseOneofTwo = wasR+wasB == 2 and r+b == 1 and what != seq[-1]    # Only if the remaining button isn't already archived
        freshPress       = not (wasR+wasB) and r+b
        switchButtons    = b+r==1 and (wasR,wasB)==(b,r)

        if realeaseOneofTwo or freshPress or switchButtons:
            seq.append(what)
        wasR,wasB = r,b

    return ''.join(seq)


Solve in Python:
I have the `par` value for each hole on a golf course and my stroke `score` on each hole. I have them stored as strings, because I wrote them down on a sheet of paper.  Right now, I'm using those strings to calculate my golf score by hand: take the difference between my actual `score` and the `par` of the hole, and add up the results for all 18 holes.

For example:
* If I took 7 shots on a hole where the par was 5, my score would be: 7 - 5 = 2
* If I got a hole-in-one where the par was 4, my score would be: 1 - 4 = -3.

Doing all this math by hand is really hard! Can you help make my life easier?

## Task Overview

Complete the function which accepts two strings and calculates the golf score of a game. Both strings will be of length 18, and each character in the string will be a number between 1 and 9 inclusive.

def golf_score_calculator(par_string, score_string):
    score = 0
    for i in range(0,18):
        score -= int(par_string[i]) - int(score_string[i])
    return score


Solve in Python:
I love Fibonacci numbers in general, but I must admit I love some more than others.

I would like for you to write me a function that when given a number (n)  returns the n-th number in the Fibonacci Sequence.

For example:

```python
   nth_fib(4) == 2
```

Because 2 is the 4th number in the Fibonacci Sequence.

For reference, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two.

def nth_fib(n):
  n -= 1
  if n == 0: return 0
  if n == 1: return 1
  a, b, p, q = 1, 0, 0, 1

  while n > 0:
    if n % 2 == 0:
      tp = p
      p = p ** 2 + q ** 2
      q = 2 * tp * q + q ** 2
      n //= 2
    else:
      ta = a
      a = b * q + a * q + a * p
      b = b * p + ta * q
      n -= 1
  return b


Solve in Python:
I need some help with my math homework. I have a number of problems I need to return the derivative for.

They will all be of the form:
ax^b,
A and B are both integers, but can be positive or negative.
Note:
  - if b is 1, then the equation will be ax.
  - if b is 0, then the equation will be 0.

Examples:
  3x^3   -> 9x^2
  3x^2   -> 6x
  3x     -> 3
  3      -> 0
  3x^-1  -> -3x^-2
  -3x^-2 -> 6x^-3

If you don't remember how derivatives work, here's a link with some basic rules: https://www.mathsisfun.com/calculus/derivatives-rules.html

def get_derivative(string):
    if string.endswith('x'):
        return string.split('x')[0]
    elif len(string) == 1:
        return '0'
    else:
        s = list(map(int, string.split("x^")))
        second = s[1] - 1
        return f"{s[0] * s[1]}x{'^' + str(second) if second != 1 else ''}"


Solve in Python:
I need to save some money to buy a gift. I think I can do something like that:

First week (W0) I save nothing on Sunday, 1 on Monday, 2 on Tuesday... 6 on Saturday,
second week (W1) 2 on Monday... 7 on Saturday and so on according to the table below where the days are numbered from 0 to 6.

Can you tell me how much I will have for my gift on Saturday evening after I have saved 12? (Your function finance(6) should return 168 which is the sum of the savings in the table).

Imagine now that we live on planet XY140Z-n where the days of the week are numbered from 0 to n (integer n > 0) and where
I save from week number 0 to week number n included (in the table below n = 6).

How much money would I have at the end of my financing plan on planet XY140Z-n?

  -- |Su|Mo|Tu|We|Th|Fr|Sa|
   --|--|--|--|--|--|--|--|
  W6 |  |  |  |  |  |  |12|
  W5 |  |  |  |  |  |10|11|
  W4 |  |  |  |  |8 |9 |10|
  W3 |  |  |  |6 |7 |8 |9 |
  W2 |  |  |4 |5 |6 |7 |8 |
  W1 |  |2 |3 |4 |5 |6 |7 |
  W0 |0 |1 |2 |3 |4 |5 |6 |

#Example:
```
finance(5) --> 105
finance(6) --> 168
finance(7) --> 252
finance(5000) --> 62537505000
```
#Hint:
try to avoid nested loops

def finance(n):
    savings = 0
    for weeks in range(n+1):
        for days in range(weeks,n+1):
            savings += weeks + days
    return savings


Solve in Python:
I started this as a joke among friends, telling that converting numbers to other integer bases is for n00bs, while an actual coder at least converts numbers to more complex bases like [pi (or π or however you wish to spell it in your language)](http://en.wikipedia.org/wiki/Pi), so they dared me proving I was better.

And I did it in few hours, discovering that what I started as a joke actually has [some math ground and application (particularly the conversion to base pi, it seems)](http://en.wikipedia.org/wiki/Non-integer_representation).

That said, now I am daring you to do the same, that is to build a function so that it takes a **number** (any number, you are warned!) and optionally the **number of decimals** (default: 0) and a **base** (default: pi), returning the proper conversion **as a string**:

#Note
In Java there is no easy way with optional parameters so all three parameters will be given; the same in C# because, as of now, the used version is not known.

```python
converter(13) #returns '103'
converter(13,3) #returns '103.010'
converter(-13,0,2) #returns '-1101'
```

I know most of the world uses a comma as a [decimal mark](http://en.wikipedia.org/wiki/Decimal_mark), but as English language and culture are *de facto* the Esperanto of us coders, we will stick to our common glorious traditions and uses, adopting the trivial dot (".") as decimal separator; if the absolute value of the result is <1, you have of course to put one (and only one) leading 0 before the decimal separator.

Finally, you may assume that decimals if provided will always be >= 0 and that no test base will be smaller than 2 (because, you know, converting to base 1 is pretty lame) or greater than 36; as usual, for digits greater than 9 you can use uppercase alphabet letter, so your base of numeration is going to be: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'.

That is my first 3-languages-kata, so I count on you all to give me extensive feedback, no matter how harsh it may sound, so to improve myself even further :)

from math import pi
import math

def converter(n, decimals=0, base=pi):
    print(n)
    print(decimals)
    print(base)
    negative = False
    retVal = ""
    if n == 0:
        left = 0
    else:
        if n < 0:
            n = n * -1
            negative = True
            retVal = "-"
        left = math.floor(math.log(abs(n))/math.log(base))
    charList = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
    for p in range(left,0-decimals-1,-1):
        if p == -1:
            retVal += "."
        coeff = math.pow(base,p)
        print("XXXXXXXX")
        print(n)
        print(coeff)
        print("XXXXXXXX")
        print((math.floor(n/coeff)))
        retVal += charList[math.floor(n/coeff)]
        n = n-math.floor(n/coeff)*coeff
    print(retVal)
    return retVal


Solve in Python:
I will give you two strings. I want you to transform stringOne into stringTwo one letter at a time.

Example:

from collections import OrderedDict

def mutate_my_strings(s1,s2):
    return '\n'.join(OrderedDict.fromkeys((s2[:i] + s1[i:] for i in range(len(s1) + 1)))) + '\n'


Solve in Python:
I'm afraid you're in a rather unfortunate situation. You've injured your leg, and are unable to walk, and a number of zombies are shuffling towards you, intent on eating your brains. Luckily, you're a crack shot, and have your trusty rifle to hand.

The zombies start at `range` metres, and move at 0.5 metres per second. Each second, you first shoot one zombie, and then the remaining zombies shamble forwards another 0.5 metres.

If any zombies manage to get to 0 metres, you get eaten. If you run out of ammo before shooting all the zombies, you'll also get eaten. To keep things simple, we can ignore any time spent reloading.

Write a function that accepts the total number of zombies, a range in metres, and the number of bullets you have.

If you shoot all the zombies, return "You shot all X zombies."
If you get eaten before killing all the zombies, and before running out of ammo, return "You shot X zombies before being eaten: overwhelmed."
If you run out of ammo before shooting all the zombies, return "You shot X zombies before being eaten: ran out of ammo."

(If you run out of ammo at the same time as the remaining zombies reach you, return "You shot X zombies before being eaten: overwhelmed.".)

Good luck! (I think you're going to need it.)

def zombie_shootout(zombies, distance, ammo):
    sa = ammo - zombies
    sd = distance*2 - zombies
    if sa<0 or sd<0:
        if sd > sa:
            return f'You shot {ammo} zombies before being eaten: ran out of ammo.'
        else:
            return f'You shot {distance*2} zombies before being eaten: overwhelmed.'
    return f'You shot all {zombies} zombies.'


Solve in Python:
I'm new to coding and now I want to get the sum of two arrays...actually the sum of all their elements. I'll appreciate for your help.

P.S. Each array includes only integer numbers. Output is a number too.

def array_plus_array(arr1,arr2):
    arr1sum = 0
    arr2sum = 0
    for i in arr1:
        arr1sum += i
    for i in arr2:
        arr2sum += i
    return arr1sum + arr2sum


Solve in Python:
I'm sure you're familiar with factorials – that is, the product of an integer and all the integers below it.

For example, `5! = 120`, as `5 * 4 * 3 * 2 * 1 = 120`

Your challenge is to create a function that takes any number and returns the number that it is a factorial of. So, if your function receives `120`, it should return `"5!"` (as a string).

Of course, not every number is a factorial of another. In this case, your function would return `"None"` (as a string).

### Examples

* `120` will return `"5!"`
* `24` will return `"4!"`
* `150` will return `"None"`

def reverse_factorial(num):
    c = f = 1
    while f < num:
        c += 1
        f *= c
    return 'None' if f > num else "%d!" %c


Solve in Python:
I've got a crazy mental illness.
I dislike numbers a lot. But it's a little complicated:
The number I'm afraid of depends on which day of the week it is...
This is a concrete description of my mental illness:

Monday     --> 12

Tuesday    --> numbers greater than 95

Wednesday  --> 34

Thursday   --> 0

Friday     --> numbers divisible by 2

Saturday   --> 56

Sunday     --> 666 or -666

Write a function which takes a string (day of the week) and an integer (number to be tested) so it tells the doctor if I'm afraid or not. (return a boolean)


Solve in Python:
IIST is thinking of acquiring some land nearby to build its new state of the art labs. The land it has chosen incidentaly has some abandoned college buildings which IIST wants to use. The administration decide the value of the building based on the amount of work that has to be done to get it in shape (lower amount of work, higher value). The security experts want to tear down some of the buildings and use the bricks to build a boundary wall.

The director has chosen you to write a program which determines the buildings which needs to be demolished to maximise the value while fulfilling the above criterion.

Input Format:

The first line contains the number of test cases, T.

The next T cases contains information about hypothetical plots.

Each test case starts with a single integer n, 2 ≤ n ≤ 15, the number of abandoned buildings in the plot. The buildings are identified by consecutive integers 1 to n. Each of the subsequent lines contains 4 integers x_i , y_i , v_i , l_i that describe a single building. (x_i, y_i) is the position of the building in the plane, v_i is its value, and l_i is the length of boundary wall that can be built using the bricks from the building. v_i and l_i are between 0 and 10,000.

Output Format:

For each test case, compute a subset of the buildings such that, using the bricks from the buildings from that subset, the remaining buildings can be enclosed in a single boundary. Find the subset with a minimum value. If more than one such minimum-value subset exists, choose one with the smallest number of buildings.

Display, as shown below, the identity of each building to be demolished, and the length of the excess boundary (accurate to two fractional digits).

Sample Input:

2

6

0 0 8 3

1 4 3 2

2 1 7 1

4 1 2 3

3 5 4 6

2 3 9 8

3

3 0 10 2

5 5 20 25

7 -3 30 32

Sample Output:

2 4 5

3.16

2

15.00

import math
from itertools import permutations as p
def diff(li1, li2):
    li_dif = [i for i in li1 if i not in li2]
    return li_dif
def segments(b):
        """A sequence of (x,y) numeric coordinates pairs """
        poly = [(i[0],i[1]) for i in b]
        return zip(poly, poly[1:] + [poly[0]])
def perimeter(poly):
    """A sequence of (x,y) numeric coordinates pairs """
    return abs(sum(math.hypot(x0-x1,y0-y1) for ((x0, y0), (x1, y1)) in segments(poly)))
def av(b):
    return sum([i[3] for i in b])
def val(b):
    return sum([i[2] for i in b])
for _ in range(int(input())):
    b = []
    for _ in range(int(input())):
        b.append(list(map(int,input().split())))
    perm = []
    for i in range(1,len(b)):
        for e in p(b,i):
            perm.append(e)
    perm.sort(key=lambda x:val(x))
    yes = []
    for i in perm:
        if av(i)>=perimeter(diff(b,i)):
            good = val(i)
            yes.append(i)
            break
    #yes.sort(key = lambda x: len(x))
    print(" ".join([str(b.index(i)+1) for i in yes[0]]))
    x = round(av(yes[0])-perimeter(diff(b,yes[0])),2)
    print(f'{x:.2f}')


Solve in Python:
Iahub got bored, so he invented a game to be played on paper.
 He writes n integers a1, a2, ..., an. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≤ i ≤ j ≤ n) and flips all values ak for which their positions are in range [i, j] (that is i ≤ k ≤ j). Flip the value of x means to apply operation x = 1 - x.
 The goal of the game is that after exactly one move to obtain the maximum number of ones. Write a program to solve the little game of Iahub.
```
@param {Array} line of the input there are n integers: a1, a2, ..., an. 1 ≤ n ≤ 100. It is guaranteed that each of those n values is either 0 or 1
@return {Integer} the maximal number of 1s that can be obtained after exactly one move
```
Examples :
```
[1, 0, 0, 1, 0, 0]  =>  5
[1, 0, 0, 1]  =>  4

```
Note:
 In the first case, flip the segment from 2 to 6 (i = 2, j = 6). That flip changes the sequence, it becomes: [1 1 1 0 1 1]. So, it contains four ones. There is no way to make the whole sequence equal to [1 1 1 1 1 1].
 In the second case, flipping only the second and the third element (i = 2, j = 3) will turn all numbers into 1.

(c)ll931110 & fchirica

def flipping_game(a):
    current = best = 0
    for n in a:
        current = max(0, current - (n or -1))
        best = max(best, current)
    return sum(a) + (best or -1)


Solve in Python:
Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of milk that they can give. A cow facing left sees all the cows with lower indices than her index, and a cow facing right sees all the cows with higher indices than her index. A cow that got scared once can get scared again (and lose one more unit of milk). A cow that has been milked once cannot get scared and lose any more milk. You can assume that a cow never loses all the milk she can give (a cow gives an infinitely amount of milk).

Iahub can decide the order in which he milks the cows. But he must milk each cow exactly once. Iahub wants to lose as little milk as possible. Print the minimum amount of milk that is lost.

-----Input-----

The first line contains an integer n (1 ≤ n ≤ 200000). The second line contains n integers a_1, a_2, ..., a_{n}, where a_{i} is 0 if the cow number i is facing left, and 1 if it is facing right.

-----Output-----

Print a single integer, the minimum amount of lost milk.

Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

-----Examples-----
Input
4
0 0 1 0

Output
1
Input
5
1 0 1 0 1

Output
3

-----Note-----

In the first sample Iahub milks the cows in the following order: cow 3, cow 4, cow 2, cow 1. When he milks cow 3, cow 4 loses 1 unit of milk. After that, no more milk is lost.

__author__ = 'Pavel Mavrin'

n = int(input())
a = [int(x) for x in input().split()]

s = 0
res = 0
for i in a:
    if i == 0:
        res += s
    else:
        s += 1

print(res)


Solve in Python:
Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees.

The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value init_{i}, which is either 0 or 1. The root of the tree is node 1.

One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node x. Right after someone has picked node x, the value of node x flips, the values of sons of x remain the same, the values of sons of sons of x flips, the values of sons of sons of sons of x remain the same and so on.

The goal of the game is to get each node i to have value goal_{i}, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations.

-----Input-----

The first line contains an integer n (1 ≤ n ≤ 10^5). Each of the next n - 1 lines contains two integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n; u_{i} ≠ v_{i}) meaning there is an edge between nodes u_{i} and v_{i}.

The next line contains n integer numbers, the i-th of them corresponds to init_{i} (init_{i} is either 0 or 1). The following line also contains n integer numbers, the i-th number corresponds to goal_{i} (goal_{i} is either 0 or 1).

-----Output-----

In the first line output an integer number cnt, representing the minimal number of operations you perform. Each of the next cnt lines should contain an integer x_{i}, representing that you pick a node x_{i}.

-----Examples-----
Input
10
2 1
3 1
4 2
5 1
6 2
7 5
8 6
9 8
10 5
1 0 1 1 0 1 0 1 0 1
1 0 1 0 0 1 1 1 0 1

Output
2
4
7

# Made By Mostafa_Khaled
bot = True
n = int(input())

p = [[] for i in range(n + 1)]

for i in range(n - 1):

    a, b = list(map(int, input().split()))

    p[a].append(b)

    p[b].append(a)

u, v = ' ' + input()[:: 2], ' ' + input()[:: 2]

s, q = [(1, 0, 0, 0)], []

while s:

    a, k, i, j = s.pop()

    if k:

        if i != (u[a] != v[a]):

            q.append(a)

            i = 1 - i

    else:

        if j != (u[a] != v[a]):

            q.append(a)

            j = 1 - j

    k = 1 - k

    for b in p[a]:

        p[b].remove(a)

        s.append((b, k, i, j))

print(len(q))

print('\n'.join(map(str, q)))

# Made By Mostafa_Khaled


Solve in Python:
Iahub likes trees very much. Recently he discovered an interesting tree named propagating tree. The tree consists of n nodes numbered from 1 to n, each node i having an initial value a_{i}. The root of the tree is node 1.

This tree has a special property: when a value val is added to a value of node i, the value -val is added to values of all the children of node i. Note that when you add value -val to a child of node i, you also add -(-val) to all children of the child of node i and so on. Look an example explanation to understand better how it works.

This tree supports two types of queries:

  "1 x val" — val is added to the value of node x;  "2 x" — print the current value of node x.

In order to help Iahub understand the tree better, you must answer m queries of the preceding type.

-----Input-----

The first line contains two integers n and m (1 ≤ n, m ≤ 200000). The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 1000). Each of the next n–1 lines contains two integers v_{i} and u_{i} (1 ≤ v_{i}, u_{i} ≤ n), meaning that there is an edge between nodes v_{i} and u_{i}.

Each of the next m lines contains a query in the format described above. It is guaranteed that the following constraints hold for all queries: 1 ≤ x ≤ n, 1 ≤ val ≤ 1000.

-----Output-----

For each query of type two (print the value of node x) you must print the answer to the query on a separate line. The queries must be answered in the order given in the input.

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

Output
3
3
0

-----Note-----

The values of the nodes are [1, 2, 1, 1, 2] at the beginning.

Then value 3 is added to node 2. It propagates and value -3 is added to it's sons, node 4 and node 5. Then it cannot propagate any more. So the values of the nodes are [1, 5, 1,  - 2,  - 1].

Then value 2 is added to node 1. It propagates and value -2 is added to it's sons, node 2 and node 3. From node 2 it propagates again, adding value 2 to it's sons, node 4 and node 5. Node 3 has no...

class BIT():
    """区間加算、一点取得クエリをそれぞれO(logN)で応えるデータ構造を構築する
    add: 区間[begin, end)にvalを加える
    get_val: i番目(0-indexed)の値を求める
    """
    def __init__(self, n):
        self.n = n
        self.bit = [0] * (n + 1)

    def get_val(self, i):
        i = i + 1
        s = 0
        while i <= self.n:
            s += self.bit[i]
            i += i & -i
        return s

    def _add(self, i, val):
        while i > 0:
            self.bit[i] += val
            i -= i & -i

    def add(self, i, j, val):
        self._add(j, val)
        self._add(i, -val)

from collections import deque
import sys
input = sys.stdin.readline

def eular_tour(tree: list, root: int):
    """頂点に対するオイラーツアーを行う
    posの部分木に区間[begin[pos], end[pos])が対応する
    """
    n = len(tree)
    res = []
    begin = [-1] * n
    end = [-1] * n
    visited = [False] * n
    visited[root] = True
    q = deque([root])
    while q:
        pos = q.pop()
        res.append(pos)
        end[pos] = len(res)
        if begin[pos] == -1:
            begin[pos] = len(res) - 1
        for next_pos in tree[pos]:
            if visited[next_pos]:
                continue
            else:
                visited[next_pos] = True
                q.append(pos)
                q.append(next_pos)

    return res, begin, end

n, q = map(int, input().split())
init_cost = list(map(int, input().split()))
info = [list(map(int, input().split())) for i in range(n-1)]
query = [list(map(int, input().split())) for i in range(q)]

tree = [[] for i in range(n)]
for i in range(n-1):
    a, b = info[i]
    a -= 1
    b -= 1
    tree[a].append(b)
    tree[b].append(a)

res, begin, end = eular_tour(tree, 0)
even_res = []
odd_res = []
for i in range(len(res)):
    if i % 2 == 0:
        even_res.append(res[i])
    else:
        odd_res.append(res[i])

even_bit = BIT(len(even_res))
odd_bit = BIT(len(odd_res))

for i in range(q):
    if query[i][0] == 1:
        _, pos, cost = query[i]
        pos -= 1
        if begin[pos] % 2 == 0:
            even_bit.add(begin[pos] // 2, (end[pos] +...


Solve in Python:
If Give an integer N . Write a program to obtain the sum of the first and last digits of this number.

-----Input-----

The first line contains an integer T, the total number of test cases. Then follow T lines, each line contains an integer N.

-----Output-----
For each test case, display the sum of first and last digits of N in a new line.

-----Constraints-----
- 1 ≤ T ≤ 1000
- 1 ≤ N ≤ 1000000

-----Example-----
Input
3
1234
124894
242323

Output
5
5
5

# cook your dish here
for _ in range(int(input())):

 n=str(input())
 print(int(n[0])+int(n[-1]))


Solve in Python:
If I give you a date, can you tell me what day that date is? For example, december 8th, 2015 is a tuesday.

Your job is to write the function ```day(d)```
which takes a string representation of a date as input, in the format YYYYMMDD. The example would be "20151208". The function needs to output the string representation of the day, so in this case ```"Tuesday"```.

Your function should be able to handle dates ranging from January first, 1582 (the year the Gregorian Calendar was introduced) to December 31st, 9999. You will not be given invalid dates. Remember to take leap years into account.

from dateutil import parser
import calendar
def day(date):
    return calendar.day_name[parser.parse(date).weekday()]


Solve in Python:
If n is the numerator and d the denominator of a fraction, that fraction is defined a (reduced) proper fraction if and only if GCD(n,d)==1.

For example `5/16` is a proper fraction, while `6/16` is not, as both 6 and 16 are divisible by 2, thus the fraction can be reduced to `3/8`.

Now, if you consider a given number d, how many proper fractions can be built using d as a denominator?

For example, let's assume that d is 15: you can build a total of 8 different proper fractions between 0 and 1 with it: 1/15, 2/15, 4/15, 7/15, 8/15, 11/15, 13/15 and 14/15.

You are to build a function that computes how many proper fractions you can build with a given denominator:
```python
proper_fractions(1)==0
proper_fractions(2)==1
proper_fractions(5)==4
proper_fractions(15)==8
proper_fractions(25)==20
```

Be ready to handle big numbers.

Edit: to be extra precise, the term should be "reduced" fractions, thanks to [girianshiido](http://www.codewars.com/users/girianshiido) for pointing this out and sorry for the use of an improper word :)

import math
def proper_fractions(n) :
    divisors,final,unique,i  = [],[],[],1
    while i <= math.sqrt(n):
        if (n % i == 0) :
            if (n / i == i) :divisors.append(i)
            else :divisors.extend([i , n/i])
        i = i + 1
    divisors.sort()
    if len(divisors)<=2:return n-1
    divisors.pop(0),divisors.pop()
    for num,item in enumerate(divisors):
        for x in divisors[0:num]:
            if not(item%x):break
        else:unique.append(item)

    for num,item in enumerate(unique):
        cache = n/item
        for x in unique[0:num]:
            cache = cache-(cache/x)
        final.append(cache)
    return(n-sum(final))


Solve in Python:
If the first day of the month is a Friday, it is likely that the month will have an `Extended Weekend`. That is, it could have five Fridays, five Saturdays and five Sundays.

In this Kata, you will be given a start year and an end year. Your task will be to find months that have extended weekends and return:
```
- The first and last month in the range that has an extended weekend
- The number of months that have extended weekends in the range, inclusive of start year and end year.
```

For example:
```python
solve(2016,2020) = ("Jan","May",5). #The months are: Jan 2016, Jul 2016, Dec 2017, Mar 2019, May 2020
```

More examples in test cases. Good luck!

If you found this Kata easy, please try [myjinxin2015](https://www.codewars.com/users/myjinxin2015) challenge version [here](https://www.codewars.com/kata/extended-weekends-challenge-edition)

import calendar as c
def solve(a, b):
    weeks = [j for i in range(a, b+1) for j in [1,3,5,7,8,10,12] if c.monthrange(i, j) == (4, 31)]
    return (c.month_name[weeks[0]][:3], c.month_name[weeks[-1]][:3], len(weeks))


Solve in Python:
If this challenge is too easy for you, check out:
https://www.codewars.com/kata/5cc89c182777b00001b3e6a2

___

Upside-Down Pyramid Addition is the process of taking a list of numbers and consecutively adding them together until you reach one number.

When given the numbers `2, 1, 1` the following process occurs:
```
 2   1   1
   3   2
     5
```

This ends in the number `5`.

___

### YOUR TASK

Given the right side of an Upside-Down Pyramid (Ascending), write a function that will return the original list.

### EXAMPLE

```python
reverse([5, 2, 1]) == [2, 1, 1]
```

NOTE: The Upside-Down Pyramid will never be empty and will always consist of positive integers ONLY.

def reverse(right):
    lastr = []
    while right:
        lastr.append(right[-1])
        right = [a-b for a, b in zip(right, right[1:])]
    return lastr[::-1]


Solve in Python:
If we alternate the vowels and consonants in the string `"have"`, we get the following list, arranged alphabetically:
`['ahev', 'aveh', 'ehav', 'evah', 'vahe', 'veha']`. These are the only possibilities in which vowels and consonants are alternated. The first element, `ahev`, is alphabetically lowest.

Given a string:
* alternate the vowels and consonants and return the lexicographically lowest element in the list
* If any two or more vowels or consonants must follow each other, return `"failed"`
* if the number of vowels and consonants are equal, the first letter of the result must be a vowel.

Examples:

```Haskell
solve("codewars") = "failed". However you alternate vowels and consonants, two consonants must follow each other
solve("oruder") = "edorur"
solve("orudere") = "ederoru". This is the only option that allows you to alternate vowels & consonants.
```

```if c:
In C, return an allocated string even if the response is "failed".
```

Vowels will be any of "aeiou". Input will be a lowercase string, no spaces. See test cases for more examples.

Good luck!

If you like this Kata, please try:

[Consonant value](https://www.codewars.com/kata/59c633e7dcc4053512000073)

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

def solve(s):
    vow, con = [], []
    for c in s:
        if c in 'aeiou':
            vow.append(c)
        else:
            con.append(c)

    len_v, len_c = len(vow), len(con)

    if len_v - len_c in [0, 1]:
        return ''.join(v+c for v, c in zip(sorted(vow), sorted(con) + ['']))
    elif len_v - len_c == -1:
        return ''.join(v+c for v, c in zip(sorted(con), sorted(vow) + ['']))

    return 'failed'


Solve in Python:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Finish the solution so that it returns the sum of all the multiples of 3 or 5 **below** the number passed in.

> Note: If the number is a multiple of **both** 3 and 5, only count it *once*.
> Also, if a number is negative, return 0(for languages that do have them)

###### *Courtesy of projecteuler.net*

def solution(number):
  return sum(set(range(0,number,3)) | set(range(0,number,5)))


Solve in Python:
If we multiply the integer      `717 (n)` by `7 (k)`, the result will be equal to `5019`.

Consider all the possible ways that this last number may be split as a string and calculate their corresponding sum obtained by adding the substrings as integers. When we add all of them up,... surprise, we got the original number `717`:

```
Partitions as string                Total Sums
['5', '019']                        5 + 19 = 24
['50', '19']                       50 + 19 = 69
['501', '9']                      501 + 9 = 510
['5', '0', '19']                5 + 0 + 19 = 24
['5', '01', '9']                 5 + 1 + 9 = 15
['50', '1', '9']                50 + 1 + 9 = 60
['5', '0', '1', '9']         5 + 0 + 1 + 9 = 15
                            ____________________
                              Big Total:    717
                            ____________________
```
In fact, `717` is one of the few integers that has such property with a factor `k = 7`.

Changing the factor `k`, for example to `k = 3`, we may see that the integer `40104` fulfills this property.

Given an integer `start_value` and an integer `k`, output the smallest integer `n`, but higher than `start_value`, that fulfills the above explained properties.

If by chance, `start_value`, fulfills the property, do not return `start_value` as a result, only the next integer. Perhaps you may find this assertion redundant if you understood well the requirement of the kata: "output the smallest integer `n`, but higher than `start_value`"

The values for `k` in the input may be one of these: `3, 4, 5, 7`

### Features of the random tests

If you want to understand the style and features of the random tests, see the *Notes* at the end of these instructions.

The random tests are classified in three parts.

- Random tests each with one of the possible values of `k` and a random `start_value` in the interval `[100, 1300]`
- Random tests each with a `start_value` in a larger interval for each value of `k`, as follows:
 - for `k = 3`, a random `start value` in the range...

def check(n):
    r,l = 0, 0
    while n:
        n,v = divmod(n, 10)
        x = 0
        for i in range(l):
            x += 10**i*2**(l-i-1)
        r += r + v*x + v*10**l
        l += 1
    return r

def next_higher(start_value, k):
    for i in range(start_value+1, start_value+30000):
        if check(i*k)-i-i*k == 0:
            return i


Solve in Python:
If we write out the digits of "60" as English words we get "sixzero"; the number of letters in "sixzero" is seven. The number of letters in "seven" is five. The number of letters in "five" is four. The number of letters in "four" is four: we have reached a stable equilibrium.

Note: for integers larger than 9, write out the names of each digit in a single word (instead of the proper name of the number in English). For example, write 12 as "onetwo" (instead of twelve), and 999 as "nineninenine" (instead of nine hundred and ninety-nine).

For any integer between 0 and 999, return an array showing the path from that integer to a stable equilibrium:

numbers = 'zero one two three four five six seven eight nine'.split()

def f(n):  return ''.join(numbers[int(i)] for i in str(n))

def numbers_of_letters(n):
    ans = [f(n)]
    while ans[-1]!='four':
        ans.append(f(len(ans[-1])))
    return ans


Solve in Python:
If you can't sleep, just count sheep!!

## Task:
Given a non-negative integer, `3` for example, return a string with a murmur: `"1 sheep...2 sheep...3 sheep..."`.  Input will always be valid, i.e. no negative integers.

def count_sheep(n):
    total = ""
    x = 0
    for i in range(n):
        x += 1
        total += str(x)+" sheep..."

    return total


Solve in Python:
If you finish this kata, you can try [Insane Coloured Triangles](http://www.codewars.com/kata/insane-coloured-triangles) by Bubbler, which is a ***much*** harder version of this one.

A coloured triangle is created from a row of colours, each of which is red, green or blue. Successive rows, each containing one fewer colour than the last, are generated by considering the two touching colours in the previous row. If these colours are identical, the same colour is used in the new row. If they are different, the missing colour is used in the new row. This is continued until the final row, with only a single colour, is generated.

The different possibilities are:
```
Colour here:        G G        B G        R G        B R
Becomes colour:      G          R          B          G
```

With a bigger example:
```
R R G B R G B B
 R B R G B R B
  G G B R G G
   G R G B G
    B B R R
     B G R
      R B
       G
```

You will be given the first row of the triangle as a string and its your job to return the final colour which would appear in the bottom row as a string. In the case of the example above, you would the given `RRGBRGBB` you should return `G`.

* The input string will only contain the uppercase letters `R, G, B` and there will be at least one letter so you do not have to test for invalid input.
* If you are only given one colour as the input, return that colour.

*Adapted from the 2017 British Informatics Olympiad*

conv = {
     'RR':'R', 'GG':'G', 'BB':'B',
     'RG':'B', 'GR':'B', 'RB':'G',
     'BR':'G', 'BG':'R', 'GB':'R'
}

def triangle(row):
    def dec(row):
        return ''.join(conv[row[x:x+2]] for x in range(len(row)-1))
    while len(row)-1:
        row = dec(row)
    return row


Solve in Python:
If you have completed the Tribonacci sequence kata, you would know by now that mister Fibonacci has at least a bigger brother. If not, give it a quick look to get how things work.

Well, time to expand the family a little more: think of a Quadribonacci starting with a signature of 4 elements and each following element is the sum of the 4 previous, a Pentabonacci (well *Cinquebonacci* would probably sound a bit more italian, but it would also sound really awful) with a signature of 5 elements and each following element is the sum of the 5 previous, and so on.

Well, guess what? You have to build a Xbonacci function that takes a **signature** of X elements *- and remember each next element is the sum of the last X elements -* and returns the first **n** elements of the so seeded sequence.

```
xbonacci {1,1,1,1} 10 = {1,1,1,1,4,7,13,25,49,94}
xbonacci {0,0,0,0,1} 10 = {0,0,0,0,1,1,2,4,8,16}
xbonacci {1,0,0,0,0,0,1} 10 = {1,0,0,0,0,0,1,2,3,6}
xbonacci {1,1} produces the Fibonacci sequence
```

def Xbonacci(signature,n):
    output, x = signature[:n], len(signature)
    while len(output) < n:
        output.append(sum(output[-x:]))
    return output


Solve in Python:
If you have not ever heard the term **Arithmetic Progrossion**, refer to:
http://www.codewars.com/kata/find-the-missing-term-in-an-arithmetic-progression/python

And here is an unordered version. Try if you can survive lists of **MASSIVE** numbers (which means time limit should be considered). :D

Note: Don't be afraid that the minimum or the maximum element in the list is missing, e.g. [4, 6, 3, 5, 2] is missing 1 or 7, but this case is excluded from the kata.

Example:

```python
find([3, 9, 1, 11, 13, 5]) # => 7
```

def find(seq):
    a,b,c = max(seq), min(seq), len(seq)
    z = list(range(b, a, (a-b)//c))
    return list(set(z)-set(seq))[0]


Solve in Python:
If you like Taco Bell, you will be familiar with their signature doritos locos taco. They're very good.

Why can't everything be a taco? We're going to attempt that here, turning every word we find into the taco bell recipe with each ingredient.

We want to input a word as a string, and return a list representing that word as a taco.

***Key***

all vowels (except 'y') = beef

t = tomato

l = lettuce

c = cheese

g = guacamole

s = salsa

***NOTE***
We do not care about case here. 'S' is therefore equivalent to 's' in our taco.

Ignore all other letters; we don't want our taco uneccesarily clustered or else it will be too difficult to eat.

Note that no matter what ingredients are passed, our taco will always have a shell.

t=dict(zip('.tlcgsaeiou','shell tomato lettuce cheese guacamole salsa'.split()+['beef']*5))
tacofy=lambda s:[t[c]for c in'.%s.'%s.lower()if c in t]


Solve in Python:
If you like cryptography and playing cards, have also a look at the kata [Card-Chameleon, a Cipher with Playing cards](http://www.codewars.com/kata/card-chameleon-a-cipher-with-playing-cards).

As a secret agent, you need a method to transmit a message to another secret agent. But an encrypted text written on a notebook will be suspicious if you get caught. A simple deck of playing cards, however, is everything but suspicious...

With a deck of 52 playing cards, there are `52!` different possible permutations to order it. And `52!` is equal to `80658175170943878571660636856403766975289505440883277824000000000000`. That's a number with [68 digits](https://www.wolframalpha.com/input/?i=52!)!

There are so many different possible permutations, we can affirm that if you shuffle the cards well and put them back together to form a deck, you are the first one in history to get this particular order. The number of possible permutations in a deck of cards is higher than the estimated number of atoms in planet Earth (which is a number with about [50 digits](https://www.wolframalpha.com/input/?i=number+of+atoms+in+earth)).

With a way to associate a permutation of the cards to a sequence of characters, we can hide a message in the deck by ordering it correctly.

---

# Correspondence between message and permutation

## Message

To compose our message, we will use an alphabet containing 27 characters: the space and the letters from A to Z. We give them the following values:

`" " = 0, A = 1, B = 2, ..., Z = 26`

We now have a [numeral system](https://en.wikipedia.org/wiki/Numeral_system) with a base equal to 27. We can compute a numeric value corresponding to any message:

`"A " = 27`
`"AA" = 28`
`"AB" = 29`
`"ABC" = 786`
etc.

## Permutation

Now we need a way to attribute a unique number to each of the possible [permutations](https://en.wikipedia.org/wiki/Permutation) of our deck of playing cards.

There are few methods to [enumerate...

from math import factorial

class PlayingCards:

    def __init__(self):

        self.chars = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ'

        self.ranks = 'A23456789TJQK'
        self.suits = 'CDHS'
        self.cards = [rank + suit for suit in self.suits for rank in self.ranks]

    def encode(self, message):

        if any(ch not in self.chars for ch in message):
            return None

        char_vals = {v: i for i, v in enumerate(self.chars)}
        perm_ind = sum(int(self.n_to_base_27(char_vals[ch])*27**(len(message) - i - 1)) for i, ch in enumerate(message))

        if perm_ind >= factorial(52):
            return None

        return self.card_permutation(perm_ind)

    def decode(self, deck):

        if not all(card in self.cards for card in deck) or len(set(deck)) != 52:
            return None

        val_chars = {i: v for i, v in enumerate(self.chars)}
        lex_index = 0

        for i in range(len(deck)):
            s = 0
            for j, v in enumerate(deck[i + 1:]):
                if self.cards.index(v) < self.cards.index(deck[i]):
                    s += 1
            lex_index += s*factorial(len(deck) - i - 1)

        char_arr = []
        while lex_index:
            lex_index, i = divmod(lex_index, 27)
            char_arr.append(val_chars[i])

        return ''.join(char_arr[::-1])

    @staticmethod
    def n_to_base_27(n):

        if n == 0:
            return 0
        d = []
        while n:
            d.append(n%27)
            n //= 27
        return int(''.join(map(str, d[::-1])))

    def card_permutation(self, k):

        factorial_arr = [1]
        for i in range(2, 52):
            factorial_arr.append(factorial_arr[-1] * i)

        permutation = []
        res = list(range(52))

        while factorial_arr:
            factorial = factorial_arr.pop()
            n, k = divmod(k, factorial)
            permutation.append(res[n])
           ...


Solve in Python:
If　`a = 1, b = 2, c = 3 ... z = 26`

Then `l + o + v + e = 54`

and `f + r + i + e + n + d + s + h + i + p = 108`

So `friendship` is twice stronger than `love` :-)

The input will always be in lowercase and never be empty.

def words_to_marks(s):
    return sum(ord(n)-96 for n in s)


Solve in Python:
Igor the analyst has adopted n little bunnies. As we all know, bunnies love carrots. Thus, Igor has bought a carrot to be shared between his bunnies. Igor wants to treat all the bunnies equally, and thus he wants to cut the carrot into n pieces of equal area.

Formally, the carrot can be viewed as an isosceles triangle with base length equal to 1 and height equal to h. Igor wants to make n - 1 cuts parallel to the base to cut the carrot into n pieces. He wants to make sure that all n pieces have the same area. Can you help Igor determine where to cut the carrot so that each piece have equal area?

 [Image] Illustration to the first example.

-----Input-----

The first and only line of input contains two space-separated integers, n and h (2 ≤ n ≤ 1000, 1 ≤ h ≤ 10^5).

-----Output-----

The output should contain n - 1 real numbers x_1, x_2, ..., x_{n} - 1. The number x_{i} denotes that the i-th cut must be made x_{i} units away from the apex of the carrot. In addition, 0 < x_1 < x_2 < ... < x_{n} - 1 < h must hold.

Your output will be considered correct if absolute or relative error of every number in your output doesn't exceed 10^{ - 6}.

Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if $\frac{|a - b|}{\operatorname{max}(1, b)} \leq 10^{-6}$.

-----Examples-----
Input
3 2

Output
1.154700538379 1.632993161855

Input
2 100000

Output
70710.678118654752

-----Note-----

Definition of isosceles triangle: https://en.wikipedia.org/wiki/Isosceles_triangle.

n, h = list(map(float, input().split(' ')))
print(' '.join(['%.12f' % (((k + 1) / n) ** 0.5 * h) for k in range(int(n) - 1)]))


Solve in Python:
Imagine a funnel filled with letters. The bottom letter drops out of the funnel and onto a conveyor belt:

```
  \b,c/  -->   \b,c/
   \a/   -->    \ /
                 a
-------     -------
```
If there are two letters above a gap, the smaller letter falls into the gap.
```
  \b,c/   -->   \  c/
   \ /    -->    \b/
a            a
-------      -------
```
Of course, this can create a new gap, which must also be filled in the same way:
```
  \f,e,d/  -->  \f, ,d/
   \  c/   -->   \e,c/
    \b/           \b/
   a            a
  -------      -------
```
Once all the gaps above it have been filled, the bottom letter drops out of the funnel and onto the conveyorbelt. The process continues until all letters have fallen onto the conveyor. (New letters fall onto the end of the existing string)

**KATA GOAL: Return the string on the conveyorbelt after all letters have fallen**.
```
\f, ,d/      \f, ,d/   --> etc -->    \     /
 \e,c/        \e,c/    --> etc -->     \   /
  \b/    -->   \ /     --> etc -->      \ /
a           a   b                   abcdef
-------     -------                 -------
```
All letters in the funnel will be unique i.e. in every comparison one letter will be strictly smaller than the other. The funnel will be presented as a nested list, e.g:
```
[["d","a","c"],
   ["b","e"],
     ["f"]]
```
The value of a letter is defined by its codepoint. Note: this means all capital letters are defined as smaller than all lower-case letters, but your language's comparison operator will probably treat it that way automatically.

The funnels will always be "nice" -- every layer will have 1 item more than the layer below, and every layer will be full, and generally there's no funny business or surprises to consider. The only characters used are standard uppercase and lowercase letters A-Z and a-z. The tests go up to 9 layer funnel.

### Fully Worked Example
```
\d,a,c/      \d,a,c/      \d,a,c/ -->  \d   c/
 \b,e/        \b,e/  -->   \  e/  -->   \a,e/
  \f/   -->    \ /  ...

def funnel_out(funnel):
    ans = ""
    while funnel[-1][0] != "~":
        ans += funnel[-1][0]
        i, funnel[-1][0] = 0, "~"
        for d in range(len(funnel)-1, 0, -1):
            iUp = min((i, i+1), key=lambda x: funnel[d-1][x])
            funnel[d][i], funnel[d-1][iUp] = funnel[d-1][iUp], funnel[d][i]
            i = iUp
    return ans


Solve in Python:
Imagine a triangle of numbers which follows this pattern:

 * Starting with the number "1", "1" is positioned at the top of the triangle. As this is the 1st row, it can only support a single number.
 * The 2nd row can support the next 2 numbers: "2" and "3"
 * Likewise, the 3rd row, can only support the next 3 numbers: "4", "5", "6"
 * And so on; this pattern continues.

```
    1
   2 3
  4 5 6
 7 8 9 10
...
```

Given N, return the sum of all numbers on the Nth Row:

1 <= N <= 10,000


Solve in Python:
Imagine if there were no order of operations. Instead, you would do the problem from left to right. For example, the equation `$a +b  *c /d$` would become `$(((a+b)*c)//d)$` (`Math.floor(((a+b)*c)/d)` in JS). Return `None`/`null` (depending on your language) if the equation is `""`.

### Task:

Given an equation with a random amount of spaces greater than or equal to zero between each number and operation, return the result without order of operations. Note that if two numbers are spaces apart, act as if they were one number: `1   3` = `13`. However, if given something `% 0` or something `/ 0`, return `None/null`.

More about order of operations: [here](https://en.wikipedia.org/wiki/Order_of_operations#:~:text=In%20the%20United%20States%2C%20the,Excuse%20My%20Dear%20Aunt%20Sally%22.)

### Key:

- `^` represents `**`

```if:python
- `/` represents `//` or `math.floor` because the result will always be an integer
```

```if:javascript
- `/` should always be rounded down(`Math.floor`) because the result will always be an integer
```

### Operations allowed:
 `+, -, * , /, ^, %`

### Example:

`no_order(2 + 3 - 4 * 1 ^ 3) returns 1`

because:
```
  2 + 3 - 4 * 1 ^ 3
= 2 + 3 - 4 * 1 ^ 3
= 5 - 4 * 1 ^ 3
= 1 * 1 ^ 3
= 1 ^ 3
= 1
```

from re import compile
from functools import reduce
from operator import add, sub, mul, floordiv as div, pow, mod

REGEX = compile(r"^\d+|[^\d]\d+").findall
D = {'+':add, '-':sub, '*':mul, '/':div, '^':pow, '%':mod}

def no_order(equation):
    L = REGEX(equation.replace(" ", ""))
    try:
        return reduce(lambda x,y: D[y[0]](x, int(y[1:])), L[1:], int(L[0]))
    except:
        return None


Solve in Python:
Imagine that you are given two sticks. You want to end up with three sticks of equal length. You are allowed to cut either or both of the sticks to accomplish this, and can throw away leftover pieces.

Write a function, maxlen, that takes the lengths of the two sticks (L1 and L2, both positive values), that will return the maximum length you can make the three sticks.

def maxlen(L1, L2):
    a, b = sorted([L1, L2])
    if b < 2*a:
        return b / 2
    elif 2*a < b < 3*a:
        return a
    else:
        return b / 3


Solve in Python:
Imagine that you have an array of 3 integers each representing a different person. Each number can be 0, 1, or 2 which represents the number of hands that person holds up.

Now imagine there is a sequence which follows these rules:
* None of the people have their arms raised at first
* Firstly, a person raises 1 hand; then they raise the second hand; after that they put both hands down - these steps form a cycle
* Person #1 performs these steps all the time, person #2 advances only after person #1 puts their hands down, and person #3 advances only after person #2 puts their hands down

The first 10 steps of the sequence represented as a table are:

```
Step   P1   P2   P3
--------------------
 0     0    0    0
 1     1    0    0
 2     2    0    0
 3     0    1    0
 4     1    1    0
 5     2    1    0
 6     0    2    0
 7     1    2    0
 8     2    2    0
 9     0    0    1
```

Given a number, return an array with the number of hands raised by each person at that step.

import math
def get_positions(n):
    return (n%3,math.floor((n/3)%3), math.floor((n/9)%3))


Solve in Python:
Imagine the following situations:

- A truck loading cargo
- A shopper on a budget
- A thief stealing from a house using a large bag
- A child eating candy very quickly

All of these are examples of ***The Knapsack Problem***, where there are more things that you ***want*** to take with you than you ***can*** take with you.

The Problem
===

Given a container with a certain capacity and an assortment of discrete items with various sizes and values (and an infinite supply of each item), determine the combination of items that fits within the container and maximizes the value of the collection.

However, **DO NOT** attempt to solve the problem **EXACTLY!** (we will do that in Part 2)

The Simplification
===

Because the optimal collection of items is **MUCH** more difficult to determine than a nearly-optimal collection, this kata will only focus on one specific nearly-optimal solution: the greedy solution. The greedy solution is that which always adds an item to the collection if it has the highest value-to-size ratio.

For example, if a "greedy thief" with a 10-Liter knapsack sees two types of items

- a 6-Liter item worth $9 (1.5 $/L)

- a 5-Liter item worth $5 (1.0 $/L)

the thief will take 1 of the 6-Liter items instead of 2 of the 5-Liter items. Although this means the thief will only profit $9 instead of $10, the decision algorithm is much simpler. Maybe the thief is bad at math.

Now, go be bad at math!

The Kata
===

Write the function `knapsack` that takes two parameters, `capacity` and `items`, and returns a list of quantities.

`capacity` will be a positive number

`items` will be an array of arrays of positive numbers that gives the items' sizes and values in the form [[size 1, value 1], [size 2, value 2], ...]

`knapsack` will return an array of integers that specifies the quantity of each item to take according to the greedy solution (the order of the quantities must match the order of `items`)

def knapsack(capacity, items):
    r = [0] * len(items)
    for i, item in sorted(enumerate(items), key=lambda x: x[1][1] / float(x[1][0]), reverse=True):
        while capacity >= item[0]:
            capacity -= item[0]
            r[i] += 1
    return r


Solve in Python:
Imagine there's a big cube consisting of n^3 small cubes. Calculate, how many small cubes are not visible from outside.

For example, if we have a cube which has 4 cubes in a row, then the function should return 8, because there are 8 cubes inside our cube (2 cubes in each dimension)

def not_visible_cubes(n):
    return (n-2) ** 3 if n > 2 else 0


Solve in Python:
Imagine two rings with numbers on them. The inner ring spins clockwise (decreasing by 1 each spin) and the outer ring spins counter clockwise (increasing by 1 each spin). We start with both rings aligned on 0 at the top, and on each move we spin each ring one increment. How many moves will it take before both rings show the same number at the top again?

The inner ring has integers from 0 to innerMax and the outer ring has integers from 0 to outerMax, where innerMax and outerMax are integers >= 1.

```
e.g. if innerMax is 2 and outerMax is 3 then after
1 move: inner = 2, outer = 1
2 moves: inner = 1, outer = 2
3 moves: inner = 0, outer = 3
4 moves: inner = 2, outer = 0
5 moves: inner = 1, outer = 1
Therefore it takes 5 moves for the two rings to reach the same number
Therefore spinningRings(2, 3) = 5
```
```
e.g. if innerMax is 3 and outerMax is 2 then after
1 move: inner = 3, outer = 1
2 moves: inner = 2, outer = 2
Therefore it takes 2 moves for the two rings to reach the same number
spinningRings(3, 2) = 2
```

---

for a bigger challenge, check out the [Performance Version](https://www.codewars.com/kata/59b0b7cd2a00d219ab0000c5) of this kata by @Voile

def spinning_rings(inner_max, outer_max):
    innerList = [0] + [i for i in range(inner_max, 0, -1)]
    outerList = [0] + [i for i in range(1, outer_max+1)]

    tries = 1
    while True:
        if innerList[tries % (inner_max+1)] == outerList[tries % (outer_max+1)]:
            return tries
            break
        tries += 1


Solve in Python:
Imagine you start on the 5th floor of a building, then travel down to the 2nd floor, then back up to the 8th floor. You have travelled a total of 3 + 6 = 9 floors of distance.

Given an array representing a series of floors you must reach by elevator, return an integer representing the total distance travelled for visiting each floor in the array in order.

```
// simple examples
elevatorDistance([5,2,8]) = 9
elevatorDistance([1,2,3]) = 2
elevatorDistance([7,1,7,1]) = 18

// if two consecutive floors are the same,
//distance travelled between them is 0
elevatorDistance([3,3]) = 0
```

Array will always contain at least 2 floors. Random tests will contain 2-20 elements in array, and floor values between 0 and 30.

def elevator_distance(array):
    return sum(abs(array[i+1] - array[i]) for i in range(len(array)-1))


Solve in Python:
Implement `String#digit?` (in Java `StringUtils.isDigit(String)`), which should return `true` if given object is a digit (0-9), `false` otherwise.

from re import search
is_digit = lambda n : bool(search(r"(^[0-9]$)(?!\s)", n))


Solve in Python:
Implement `String#ipv4_address?`, which should return true if given object is an IPv4 address - four numbers (0-255) separated by dots.

It should only accept addresses in canonical representation, so no leading `0`s, spaces etc.

def ipv4_address(address):
    return address.count(".")==3 and all([str.isdigit(s) and s==str(int(s)) and int(s)>=0 and int(s)<256 for s in address.split(".")])


Solve in Python:
Implement `String#parse_mana_cost`, which parses [Magic: the Gathering mana costs](http://mtgsalvation.gamepedia.com/Mana_cost) expressed as a string and returns a `Hash` with keys being kinds of mana, and values being the numbers.

Don't include any mana types equal to zero.

Format is:

* optionally natural number representing total amount of generic mana (use key `*`)
* optionally followed by any combination of `w`, `u`, `b`, `r`, `g` (case insensitive in input, return lower case in output), each representing one mana of specific color.

If case of Strings not following specified format, return `nil/null/None`.

import re
def parse_mana_cost(m):
    if not m : return {}
    if not re.match(r'^[\dwubrg]+$',m,re.I) or '\n' in m : return
    r1,r = re.findall(r'[wubrg]',m,re.I), re.search(r'^[0-9]*',m)
    r,d = r.group() if r else '',{}
    if r!='0' and r : d['*'] = int(r)
    for i in m[len(r):] : d[i.lower()] = d.get(i.lower(),0)+1
    return d


Solve in Python:
Implement `String#to_cents`, which should parse prices expressed as `$1.23` and return number of cents, or in case of bad format return `nil`.

import re
def to_cents(amount):
  return int(re.sub("\D", "", amount)) if re.match("\$\d*\.\d{2}\Z", amount) else None


Solve in Python:
Implement `String#whitespace?(str)` (Ruby), `String.prototype.whitespace(str)` (JavaScript), `String::whitespace(str)` (CoffeeScript), or `whitespace(str)` (Python), which should return `true/True` if given object consists exclusively of zero or more whitespace characters, `false/False` otherwise.

def whitespace(string):
    return True if not string else string.isspace()


Solve in Python:
Implement `String.eight_bit_signed_number?` (Ruby), `String.eightBitSignedNumber()` (Python), `eight_bit_signed_number()` (JS) or `StringUtils.isSignedEightBitNumber(String)` (Java) which should return `true/True` if given object is a number representable by 8 bit signed integer (-128 to -1 or 0 to 127), `false/False` otherwise.

It should only accept numbers in canonical representation, so no leading `+`, extra `0`s, spaces etc.

def signed_eight_bit_number(s):
    try:
        return -128 <= int(s) <= 127 and str(int(s)) == s
    except ValueError:
        return False


Solve in Python:
Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +, -, *, / operators and empty spaces  . The integer division should truncate toward zero.

Example 1:

Input: "3+2*2"
Output: 7

Example 2:

Input: " 3/2 "
Output: 1

Example 3:

Input: " 3+5 / 2 "
Output: 5

Note:

       You may assume that the given expression is always valid.
       Do not use the eval built-in library function.

class Solution:
     def calculate(self, s):
         """
         :type s: str
         :rtype: int
         """

         if not s:
             return 0

         pre_op = '+'
         stack = [0]
         cur_num = 0
         digits = '0123456789'
         s += '#'

         for c in s:
             if c == ' ':
                 continue

             if c in digits:
                 cur_num = cur_num * 10 + int(c)
                 continue

             if pre_op == '-':
                 cur_num *= -1
             elif pre_op == '*':
                 cur_num *= stack.pop()
             elif pre_op == '/':
                 if cur_num == 0:
                     return None

                 pre_num = stack.pop()
                 flag = 1 if pre_num > 0 else -1
                 cur_num = abs(pre_num) // cur_num * flag

             stack.append(cur_num)
             pre_op = c
             cur_num = 0

         return sum(stack)


Solve in Python:
Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces  .

Example 1:

Input: "1 + 1"
Output: 2

Example 2:

Input: " 2-1 + 2 "
Output: 3

Example 3:

Input: "(1+(4+5+2)-3)+(6+8)"
Output: 23
Note:

       You may assume that the given expression is always valid.
       Do not use the eval built-in library function.

class Solution:
     def calculate(self, s):
         """
         :type s: str
         :rtype: int
         """
         if not s:
             return 0

         res=0
         sign=1

         stack=[1]

         num=0

         for c in s:

             if c <='9' and c>='0':
                 num=num*10+ord(c)-ord('0')
                 #print(num)
             elif c in '+-':
                 res+=sign*num
                 #print(res)
                 if c=='+':
                    #print(stack)
                    sign=stack[-1]
                 else:
                    sign=stack[-1]*(-1)
                 num=0
             elif c=='(':
                 stack.append(sign)
             elif c==')':
                 stack.pop()
         #print('outsideloop',res)
         res+=sign*num

         return res


Solve in Python:
Implement a class/function, which should parse time expressed as `HH:MM:SS`, or `null/nil/None` otherwise.

Any extra characters, or minutes/seconds higher than 59 make the input invalid, and so should return `null/nil/None`.

import re
def to_seconds(time):
    match=re.fullmatch(r'(\d{2}):([0-5][0-9]):([0-5][0-9])',time)
    return int(match.group(1))*3600+int(match.group(2))*60+int(match.group(3)) if match else None


Solve in Python:
Implement a data structure supporting the following operations:

Inc(Key) - Inserts a new key  with value 1. Or increments an existing key by 1. Key is guaranteed to be a non-empty string.
Dec(Key) - If Key's value is 1, remove it from the data structure. Otherwise decrements an existing key by 1. If the key does not exist, this function does nothing. Key is guaranteed to be a non-empty string.
GetMaxKey() - Returns one of the keys with maximal value. If no element exists, return an empty string "".
GetMinKey() - Returns one of the keys with minimal value. If no element exists, return an empty string "".

Challenge: Perform all these in O(1) time complexity.

 class Node:
     def __init__(self, cnt):
         self.count = cnt
         self.prev = None
         self.next = None

 class AllOne(object):

     def __init__(self):
         """
         Initialize your data structure here.
         """
         #Key:count, Value:set of key who has been incremented by 'count' time
         self.count_key_map = {}
         #Key:key, Value: the number of counts of this key
         self.key_count_map = {}
         #Key: the count, Value: the node
         self.count_node_map = {}

         #initialize the linkedlist with dummy node
         self.head = Node(0)
         self.tail = Node(float('inf'))
         self.head.next = self.tail
         self.tail.prev = self.head

         self.count_node_map[0] = self.head
         self.count_node_map[float('inf')] = self.tail

     def inc(self, key):
         """
         Inserts a new key <Key> with value 1. Or increments an existing key by 1.
         :type key: str
         :rtype: void
         """
         if key not in self.key_count_map:
             self.key_count_map[key]=0

         prev_count=self.key_count_map[key]
         prev_node=self.count_node_map[prev_count]

         self.key_count_map[key]+=1

         if prev_node.next.count!=self.key_count_map[key]:
             new_node=Node(self.key_count_map[key])
             self.insert(prev_node,new_node)
             self.count_key_map[self.key_count_map[key]]=set()
             self.count_node_map[self.key_count_map[key]]=new_node

         self.count_key_map[self.key_count_map[key]].add(key)

         if prev_count!=0:

            self.count_key_map[prev_count].remove(key)
            if len(self.count_key_map[prev_count])==0:
                self.count_node_map.pop(prev_count)
                self.count_key_map.pop(prev_count)
                self.delete(prev_node)

     def dec(self, key):
         """
         Decrements an existing key...


Solve in Python:
Implement a function called makeAcronym that returns the first letters of each word in a passed in string.

Make sure the letters returned are uppercase.

If the value passed in is not a string return 'Not a string'.

If the value passed in is a string which contains characters other than spaces and alphabet letters, return 'Not letters'.

If the string is empty, just return the string itself: "".

**EXAMPLES:**
```
'Hello codewarrior' -> 'HC'

'a42' -> 'Not letters'

42 -> 'Not a string'

[2,12] -> 'Not a string'

{name: 'Abraham'} -> 'Not a string'
```

def make_acronym(phrase):
    if not isinstance(phrase, str):
        return 'Not a string'
    words = phrase.split();
    if not all(i.isalpha() for i in words):
        return 'Not letters'
    return ''.join(p[0] for p in words).upper()


Solve in Python:
Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition.

The binary number returned should be a string.

def add_binary(a,b):
    return str(bin(a+b))[2:]


Solve in Python:
Implement a function that normalizes out of range sequence indexes (converts them to 'in range' indexes) by making them repeatedly 'loop' around the array. The function should then return the value at that index. Indexes that are not out of range should be handled normally and indexes to empty sequences should return undefined/None depending on the language.

For positive numbers that are out of range, they loop around starting at the beginning, so

```python
norm_index_test(seq, len(seq))     # Returns first element
norm_index_test(seq, len(seq) + 1) # Returns second element
norm_index_test(seq, len(seq) + 2) # Returns third element
# And so on...
norm_index_test(seq, len(seq) * 2) # Returns first element
```

For negative numbers, they loop starting from the end, so

```python norm_index_test(seq, len(seq))
norm_index_test(seq, -1)        # Returns last element
norm_index_test(seq, -2)        # Returns second to last element
norm_index_test(seq, -3)        # Returns third to last element
# And so on...
norm_index_test(seq, -len(seq)) # Returns first element
```

def norm_index_test(seq, n):
    try:
        return seq[n% len(seq)]
    except ZeroDivisionError:
        return None


Solve in Python:
Implement a function that returns the minimal and the maximal value of a list (in this order).

# Computational complexity of 1.5n
def get_min_max(seq):
    seq = iter(seq)
    seq_min = seq_max = next(seq)

    while True:
        try:
            a = next(seq)
        except StopIteration:
            break

        b = next(seq, seq_min)
        if a > b:
            seq_min = min(b, seq_min)
            seq_max = max(a, seq_max)
        else:
            seq_min = min(a, seq_min)
            seq_max = max(b, seq_max)

    return seq_min, seq_max


Solve in Python:
Implement a function to calculate the sum of the numerical values in a nested list. For example :

```python
sum_nested([1, [2, [3, [4]]]]) -> 10
```

def sum_nested(lst):
    return sum(sum_nested(e) if type(e) is list else e for e in lst)