Solve in Python:
You're fed up about changing the version of your software manually. Instead, you will create a little script that will make it for you.

# Exercice

Create a function `nextVersion`, that will take a string in parameter, and will return a string containing the next version number.

For example:

# Rules

All numbers, except the first one, must be lower than 10: if there are, you have to set them to 0 and increment the next number in sequence.

You can assume all tests inputs to be valid.

def next_version(version):
    if "." not in version: return str(int(version) + 1)
    v = [i for i in version.split(".")]
    minor_version = False

    for index in reversed(list(range(len(v)))):
        if index == len(v)-1 :
            if int(v[index]) < 9 :
                v[index] = str(int(v[index]) + 1)
                return ".".join(v)
            else:
                minor_version = True
                v[index] = "0"
                continue

        if minor_version:
            v[index] = str(int(v[index]) + 1)

            if int(v[index]) != 10 or index == 0 :
                return ".".join(v)
            else:
                minor_version = True
                v[index] = "0"
                continue


Solve in Python:
You're given a mystery `puzzlebox` object. Examine it to make the tests pass and solve this kata.

def answer(puzzlebox):
    #print(puzzlebox.key)
    k=puzzlebox.key
    print(puzzlebox.lock(k))
    return 42


Solve in Python:
You're given a string containing a sequence of words separated with whitespaces. Let's say it is a sequence of patterns: a name and a corresponding number - like this:

```"red 1 yellow 2 black 3 white 4"```

You want to turn it into a different **string** of objects you plan to work with later on - like this:

```"[{name : 'red', id : '1'}, {name : 'yellow', id : '2'}, {name : 'black', id : '3'}, {name : 'white', id : '4'}]"```

Doing this manually is a pain. So you've decided to write a short function that would make the computer do the job for you. Keep in mind, the pattern isn't necessarily a word and a number. Consider anything separeted by a whitespace, just don't forget: an array of objects with two elements: name and id.

As a result you'll have a string you may just copy-paste whenever you feel like defining a list of objects - now without the need to put in names, IDs, curly brackets, colon signs, screw up everything, fail searching for a typo and begin anew. This might come in handy with large lists.

import collections
import json
import re
def words_to_object(s):
    if s == "" :
        return '[]'
    d = collections.namedtuple('d', 'name ,id')
    words = s.split(" ")
    names = [ x for x in words[::2]]
    ids =  [x for x in words [1::2]]
    result =""
    i = 0
    for i in range(0,int( len(words) /2)):
       a = d(name= names[i], id=ids[i])
       r=(json.dumps(a._asdict()).replace('"', '\''))
       r= r.replace('"','').replace("'name':", "name :").replace("'id':", "id :")
       r= re.sub("}","}, ",r,flags=re.UNICODE)
       result +=r
    return '[' +result[0:-2] +"]"


Solve in Python:
You're given a string of dominos. For each slot, there are 3 options:

  * "|" represents a standing domino

  * "/" represents a knocked over domino

  * " " represents a space where there is no domino

For example:

```python
"||| ||||//| |/"
```

What you must do is find the resulting string if the first domino is pushed over. Now, tipping a domino will cause the next domino to its right to fall over as well, but if a domino is already tipped over, or there is a domino missing, the reaction will stop.

So in out example above, the result would be:

"/// ||||//| |/"

since the reaction would stop as soon as it gets to a space.

def domino_reaction(s):
    ds = ""
    for (i,d) in enumerate(s):
        if( d=="|" ):
            ds += "/"
        else:
            return ds+s[i:]
    return ds


Solve in Python:
You're given an ancient book that unfortunately has a few pages in the wrong position, fortunately your computer has a list of every page number in order from ``1`` to ``n``.

You're supplied with an array of numbers, and should return an array with each page number that is out of place. Incorrect page numbers will not appear next to each other. Duplicate incorrect page numbers are possible.

Example:

```Given: list = [1,2,10,3,4,5,8,6,7]
```

``Return: [10,8]
``

Your returning list should have the incorrect page numbers in the order they were found.

def find_page_number(pages):
    wrong_pages = []
    last_page = 0

    for page_num in pages:
        if page_num == last_page + 1:
            last_page += 1
        else:
            wrong_pages.append(page_num)

    return wrong_pages


Solve in Python:
You're given an array $a$ of $n$ integers, such that $a_1 + a_2 + \cdots + a_n = 0$.

In one operation, you can choose two different indices $i$ and $j$ ($1 \le i, j \le n$), decrement $a_i$ by one and increment $a_j$ by one. If $i < j$ this operation is free, otherwise it costs one coin.

How many coins do you have to spend in order to make all elements equal to $0$?

-----Input-----

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 5000$). Description of the test cases follows.

The first line of each test case contains an integer $n$ ($1 \le n \le 10^5$)  — the number of elements.

The next line contains $n$ integers $a_1, \ldots, a_n$ ($-10^9 \le a_i \le 10^9$). It is given that $\sum_{i=1}^n a_i = 0$.

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

-----Output-----

For each test case, print the minimum number of coins we have to spend in order to make all elements equal to $0$.

-----Example-----
Input
7
4
-3 5 -3 1
2
1 -1
4
-3 2 -3 4
4
-1 1 1 -1
7
-5 7 -6 -4 17 -13 4
6
-1000000000 -1000000000 -1000000000 1000000000 1000000000 1000000000
1
0

Output
3
0
4
1
8
3000000000
0

-----Note-----

Possible strategy for the first test case:   Do $(i=2, j=3)$ three times (free), $a = [-3, 2, 0, 1]$.  Do $(i=2, j=1)$ two times (pay two coins), $a = [-1, 0, 0, 1]$.  Do $(i=4, j=1)$ one time (pay one coin), $a = [0, 0, 0, 0]$.

for _ in range(int(input())):
    n = int(input())
    a = list(map(int, input().split()))
    pre = [0]*(n+1)
    for i in range(n):
        pre[i+1] = pre[i]+a[i]
    print(abs(min(pre)))


Solve in Python:
You're given an array $a_1, \ldots, a_n$ of $n$ non-negative integers.

Let's call it sharpened if and only if there exists an integer $1 \le k \le n$ such that $a_1 < a_2 < \ldots < a_k$ and $a_k > a_{k+1} > \ldots > a_n$. In particular, any strictly increasing or strictly decreasing array is sharpened. For example:  The arrays $[4]$, $[0, 1]$, $[12, 10, 8]$ and $[3, 11, 15, 9, 7, 4]$ are sharpened;  The arrays $[2, 8, 2, 8, 6, 5]$, $[0, 1, 1, 0]$ and $[2, 5, 6, 9, 8, 8]$ are not sharpened.

You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any $i$ ($1 \le i \le n$) such that $a_i>0$ and assign $a_i := a_i - 1$.

Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.

-----Input-----

The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 15\ 000$)  — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer $n$ ($1 \le n \le 3 \cdot 10^5$).

The second line of each test case contains a sequence of $n$ non-negative integers $a_1, \ldots, a_n$ ($0 \le a_i \le 10^9$).

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

-----Output-----

For each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.

-----Example-----
Input
10
1
248618
3
12 10 8
6
100 11 15 9 7 8
4
0 1 1 0
2
0 0
2
0 1
2
1 0
2
1 1
3
0 1 0
3
1 0 1

Output
Yes
Yes
Yes
No
No
Yes
Yes
Yes
Yes
No

-----Note-----

In the first and the second test case of the first test, the given array is already sharpened.

In the third test case of the first test, we can transform the array into $[3, 11, 15, 9, 7, 4]$ (decrease the first element $97$ times and decrease the last element $4$ times). It is sharpened...

T = int(input())
for _ in range(T):
    N = int(input())
    A = list(map(int,input().split()))
    if N%2:
        X = [i if i<N//2 else N-i-1 for i in range(N)]
        if all(a>=x for a,x in zip(A,X)):
            print('Yes')
        else:
            print('No')
    else:
        X = [i if i<N//2+1 else N-i-1 for i in range(N)]
        if all(a>=x for a,x in zip(A,X)):
            print('Yes')
            continue
        X[N//2-1], X[N//2] = X[N//2], X[N//2-1]
        if all(a>=x for a,x in zip(A,X)):
            print('Yes')
        else:
            print('No')


Solve in Python:
You're given an array of $n$ integers between $0$ and $n$ inclusive.

In one operation, you can choose any element of the array and replace it by the MEX of the elements of the array (which may change after the operation).

For example, if the current array is $[0, 2, 2, 1, 4]$, you can choose the second element and replace it by the MEX of the present elements  — $3$. Array will become $[0, 3, 2, 1, 4]$.

You must make the array non-decreasing, using at most $2n$ operations.

It can be proven that it is always possible. Please note that you do not have to minimize the number of operations. If there are many solutions, you can print any of them.

 –

An array $b[1 \ldots n]$ is non-decreasing if and only if $b_1 \le b_2 \le \ldots \le b_n$.

The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For instance:  The MEX of $[2, 2, 1]$ is $0$, because $0$ does not belong to the array.  The MEX of $[3, 1, 0, 1]$ is $2$, because $0$ and $1$ belong to the array, but $2$ does not.  The MEX of $[0, 3, 1, 2]$ is $4$ because $0$, $1$, $2$ and $3$ belong to the array, but $4$ does not.

It's worth mentioning that the MEX of an array of length $n$ is always between $0$ and $n$ inclusive.

-----Input-----

The first line contains a single integer $t$ ($1 \le t \le 200$) — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer $n$ ($3 \le n \le 1000$) — length of the array.

The second line of each test case contains $n$ integers $a_1, \ldots, a_n$ ($0 \le a_i \le n$) — elements of the array. Note that they don't have to be distinct.

It is guaranteed that the sum of $n$ over all test cases doesn't exceed $1000$.

-----Output-----

For each test case, you must output two lines:

The first line must contain a single integer $k$ ($0 \le k \le 2n$)  — the number of operations you perform.

The second line must contain $k$ integers $x_1, \ldots, x_k$ ($1 \le x_i \le n$), where $x_i$ is the index...

# Fast IO (only use in integer input) or take care about string

# import os,io
# input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline

t = int(input())
for _ in range(t):
    n = int(input())
    a = list(map(int,input().split()))
    operation = []
    while True:
        isNonDecreasing = True
        for i in range(n-1):
            if a[i] > a[i+1]:
                isNonDecreasing = False
                break
        if isNonDecreasing:
            break
        isNIn = [False] * (n + 1)
        for elem in a:
            isNIn[elem] = True
        for i in range(n + 1):
            if isNIn[i] == False:
                MEX = i
                break
        if MEX == n:
            for i in range(n):
                if a[i] != i and a[i] != n:
                    break
            operation.append(str(i + 1))
            a[i] = n
        else:
            operation.append(str(MEX+1))
            a[MEX] = MEX
    print(len(operation))
    if len(operation) != 0:
        print(' '.join(operation))


Solve in Python:
You're given an integer N. Write a program to calculate the sum of all the digits of N.

-----Input-----

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

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

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

-----Example-----
Input
3
12345
31203
2123
Output
15
9
8

# cook your dish here
tcases = int(input())
for x in range(0, tcases):
    list = []
    n = int(input())
    sum = 0
    for y in range(0, len(str(n))):
        list.append(n % 10)
        n = n // 10
    for i in list:
        sum = sum + i
    print(sum)


Solve in Python:
You're going on a trip with some students and it's up to you to keep track of how much money each Student has. A student is defined like this:

```python
class Student:
    def __init__(self, name, fives, tens, twenties):
        self.name = name
        self.fives = fives
        self.tens = tens
        self.twenties = twenties
```

As you can tell, each Student has some fives, tens, and twenties. Your job is to return the name of the student with the most money. If every student has the same amount, then return `"all"`.

Notes:
* Each student will have a unique name
* There will always be a clear winner: either one person has the most, or everyone has the same amount
* If there is only one student, then that student has the most money

def cashmuny(student):
    return student.fives * 5 + student.tens * 10 + student.twenties * 20
def most_money(students):
    timdeo = students[0]
    all = False
    if len(students) == 1:
        return timdeo.name
    for s in students[1:]:
        if cashmuny(s) > cashmuny(timdeo):
            timdeo = s
            all = False
        elif cashmuny(s) == cashmuny(timdeo):
            all = True
    if all == False:
        return timdeo.name
    if all == True:
        return "all"


Solve in Python:
You're hanging out with your friends in a bar, when suddenly one of them is so drunk, that he can't speak, and when he wants to say something, he writes it down on a paper. However, none of the words he writes make sense to you. He wants to help you, so he points at a beer and writes "yvvi". You start to understand what he's trying to say, and you write a script, that decodes his words.

Keep in mind that numbers, as well as other characters, can be part of the input, and you should keep them like they are. You should also test if the input is a string. If it is not, return "Input is not a string".

decode = lambda s: "Input is not a string" if not isinstance(s, str) else "".join(chr(155 + 64*(96<ord(c)<123) - ord(c)) if c.isalpha() else c for c in s)


Solve in Python:
You're in ancient Greece and giving Philoctetes a hand in preparing a training exercise for Hercules! You've filled a pit with two different ferocious mythical creatures for Hercules to battle!

The formidable **"Orthus"** is a 2 headed dog with 1 tail.  The mighty **"Hydra"** has 5 heads and 1 tail.

Before Hercules goes in, he asks you "How many of each beast am  I up against!?".

You know the total number of heads and the total number of tails, that's the dangerous parts, right? But you didn't consider how many of each beast.

## Task

Given the number of heads and the number of tails, work out the number of each mythical beast!

The data is given as two parameters. Your answer should be returned as an array:
```python
 VALID ->      [24 , 15]           INVALID ->  "No solutions"
```

If there aren't any cases for the given amount of heads and tails - return "No solutions" or null (C#).

def beasts(heads, tails):
    hydra = (heads - (2 * tails)) /3
    orthus = tails - ((heads - (2 * tails)) /3)
    if  hydra % 1 == 0 and hydra >= 0 and orthus % 1 == 0 and orthus >= 0:
        return [orthus, hydra]
    else:
        return f'No solutions'


Solve in Python:
You're in the casino, playing Roulette, going for the "1-18" bets only and desperate to beat the house and so you want to test how effective the [Martingale strategy](https://en.wikipedia.org/wiki/Martingale_(betting_system)) is.

You will be given a starting cash balance and an array of binary digits to represent a win (`1`) or a loss (`0`). Return your balance after playing all rounds.

*The Martingale strategy*

You start with a stake of `100` dollars. If you lose a round, you lose the stake placed on that round and you double the stake for your next bet. When you win, you win 100% of the stake and revert back to staking 100 dollars on your next bet.

## Example
```
martingale(1000, [1, 1, 0, 0, 1]) === 1300
```
Explanation:
* you win your 1st round: gain $100, balance = 1100
* you win the 2nd round: gain $100, balance = 1200
* you lose the 3rd round: lose $100 dollars, balance = 1100
* double stake for 4th round and lose: staked $200, lose $200, balance = 900
* double stake for 5th round and win: staked $400, won $400, balance = 1300

**Note: Your balance is allowed to go below 0.**

def martingale(bank, outcomes):
    loss=win=0
    stake=100
    for i in outcomes:
        if i==1:
            bank+=stake
            if stake!=100:
                stake=100
        else:
            bank-=stake
            stake*=2
    return bank
    #beat the house here...


Solve in Python:
You're laying out a rad pixel art mural to paint on your living room wall in homage to [Paul Robertson](http://68.media.tumblr.com/0f55f7f3789a354cfcda7c2a64f501d1/tumblr_o7eq3biK9s1qhccbco1_500.png), your favorite pixel artist.

You want your work to be perfect down to the millimeter. You haven't decided on the dimensions of your piece, how large you want your pixels to be, or which wall you want to use. You just know that you want to fit an exact number of pixels.

To help decide those things you've decided to write a function, `is_divisible()` that will tell you whether a wall of a certain length can exactly fit an integer number of pixels of a certain length.

Your function should take two arguments: the size of the wall in millimeters and the size of a pixel in millimeters. It should return `True` if you can fit an exact number of pixels on the wall, otherwise it should return `False`. For example `is_divisible(4050, 27)` should return `True`, but `is_divisible(4066, 27)` should return `False`.

Note: you don't need to use an `if` statement here. Remember that in Python an expression using the `==` comparison operator will evaluate to either `True` or `False`:
```python
>>> def equals_three(num):
>>>     return num == 3
>>> equals_three(5)
False
>>> equals_three(3)
True
```

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

Returns a boolean representing if the first argument is perfectly divisible by the second argument.

Syntax

public
static
bool IsDivisible(
int wallLength,
    int pixelSize,
    )

Parameters

wallLength

Type: System.Int32
The length of the wall in millimeters.

pixelSize

Type: System.Int32
The length of a pixel in millimeters.

Return Value

Type: System.Boolean
  A boolean value representing if the first argument is perfectly divisible by the second.

```

def is_divisible (wall_size,pixel_size):
  return wall_size%pixel_size==0


Solve in Python:
You're looking through different hex codes, and having trouble telling the difference between  #000001  and  #100000

We need a way to tell which is red, and which is blue!

That's where you create ```hex_color()```!

It should read an RGB input, and return whichever value (red, blue, or green) is of greatest concentration!

But, if multiple colors are of equal concentration, you should return their mix!

```python
red + blue = magenta

green + red = yellow

blue + green = cyan

red + blue + green = white
```

One last thing, if the string given is empty, or has all 0's, return black!

Examples:
```python
hex_color('087 255 054') == 'green'
hex_color('181 181 170') == 'yellow'
hex_color('000 000 000') == 'black'
hex_color('001 001 001') == 'white'
```

def hex_color(codes):
    if codes == '': return 'black'
    r,g,b = map(int,codes.split(' '))
    if 0 == r == g == b: return 'black'
    if r == g == b: return 'white'
    if r > g and r > b: return 'red'
    if g > r and g > b: return 'green'
    if b > g and b > r: return 'blue'
    if r > g and r == b: return 'magenta'
    if r > b and r == g: return 'yellow'
    if b > r and b == g: return 'cyan'


Solve in Python:
You're now a baseball game point recorder.

Given a list of strings, each string can be one of the 4 following types:

Integer (one round's score): Directly represents the number of points you get in this round.
"+" (one round's score): Represents that the points you get in this round are the sum of the last two valid round's points.
"D" (one round's score): Represents that the points you get in this round are the doubled data of the last valid round's points.
"C" (an operation, which isn't a round's score): Represents the last valid round's points you get were invalid and should be removed.

Each round's operation is permanent and could have an impact on the round before and the round after.

You need to return the sum of the points you could get in all the rounds.

Example 1:

Input: ["5","2","C","D","+"]
Output: 30
Explanation:
Round 1: You could get 5 points. The sum is: 5.
Round 2: You could get 2 points. The sum is: 7.
Operation 1: The round 2's data was invalid. The sum is: 5.
Round 3: You could get 10 points (the round 2's data has been removed). The sum is: 15.
Round 4: You could get 5 + 10 = 15 points. The sum is: 30.

Example 2:

Input: ["5","-2","4","C","D","9","+","+"]
Output: 27
Explanation:
Round 1: You could get 5 points. The sum is: 5.
Round 2: You could get -2 points. The sum is: 3.
Round 3: You could get 4 points. The sum is: 7.
Operation 1: The round 3's data is invalid. The sum is: 3.
Round 4: You could get -4 points (the round 3's data has been removed). The sum is: -1.
Round 5: You could get 9 points. The sum is: 8.
Round 6: You could get -4 + 9 = 5 points. The sum is 13.
Round 7: You could get 9 + 5 = 14 points. The sum is 27.

Note:
The size of the input list will be between 1 and 1000.
Every integer represented in the list will be between -30000 and 30000.

class Solution:
     def calPoints(self, ops):
         """
         :type ops: List[str]
         :rtype: int
         """
         def isint(num):
             try:
                 int(num)
                 return True
             except ValueError:
                 return False
         score_board = []
         for i in ops:
             if isint(i):
                 score_board.append(int(i))
             elif i == 'C':
                 score_board.pop()
             elif i == 'D':
                 score_board.append(score_board[-1] * 2)
             elif i == '+':
                 score_board.append(sum(score_board[-2:]))
         return sum(score_board)


Solve in Python:
You're on your way to the market when you hear beautiful music coming from a nearby street performer. The notes come together like you wouln't believe as the musician puts together patterns of tunes. As you wonder what kind of algorithm you could use to shift octaves by 8 pitches or something silly like that, it dawns on you that you have been watching the musician for some 10 odd minutes. You ask, "How much do people normally tip for something like this?" The artist looks up. "Its always gonna be about tree fiddy."

It was then that you realize the musician was a 400 foot tall beast from the paleolithic era. The Loch Ness Monster almost tricked you!

There are only 2 guaranteed ways to tell if you are speaking to The Loch Ness Monster: A.) It is a 400 foot tall beast from the paleolithic era B.) It will ask you for tree fiddy

Since Nessie is a master of disguise, the only way accurately tell is to look for the phrase "tree fiddy". Since you are tired of being grifted by this monster, the time has come to code a solution for finding The Loch Ness Monster.
Note: It can also be written as 3.50 or three fifty.

def is_lock_ness_monster(string):
    check = "3.50"
    check2 = "three fifty"
    check3 = "tree fiddy"
    return ((check in string) or (check2 in string) or (check3 in string))

    #your code here


Solve in Python:
You're playing a game called Osu! Here's a simplified version of it. There are n clicks in a game. For each click there are two outcomes: correct or bad. Let us denote correct as "O", bad as "X", then the whole play can be encoded as a sequence of n characters "O" and "X".

Using the play sequence you can calculate the score for the play as follows: for every maximal consecutive "O"s block, add the square of its length (the number of characters "O") to the score. For example, if your play can be encoded as "OOXOOOXXOO", then there's three maximal consecutive "O"s block "OO", "OOO", "OO", so your score will be 2^2 + 3^2 + 2^2 = 17. If there are no correct clicks in a play then the score for the play equals to 0.

You know that the probability to click the i-th (1 ≤ i ≤ n) click correctly is p_{i}. In other words, the i-th character in the play sequence has p_{i} probability to be "O", 1 - p_{i} to be "X". You task is to calculate the expected score for your play.

-----Input-----

The first line contains an integer n (1 ≤ n ≤ 10^5) — the number of clicks. The second line contains n space-separated real numbers p_1, p_2, ..., p_{n} (0 ≤ p_{i} ≤ 1).

There will be at most six digits after the decimal point in the given p_{i}.

-----Output-----

Print a single real number — the expected score for your play. Your answer will be considered correct if its absolute or relative error does not exceed 10^{ - 6}.

-----Examples-----
Input
3
0.5 0.5 0.5

Output
2.750000000000000

Input
4
0.7 0.2 0.1 0.9

Output
2.489200000000000

Input
5
1 1 1 1 1

Output
25.000000000000000

-----Note-----

For the first example. There are 8 possible outcomes. Each has a probability of 0.125.  "OOO"  →  3^2 = 9;  "OOX"  →  2^2 = 4;  "OXO"  →  1^2 + 1^2 = 2;  "OXX"  →  1^2 = 1;  "XOO"  →  2^2 = 4;  "XOX"  →  1^2 = 1;  "XXO"  →  1^2 = 1;  "XXX"  →  0.

So the expected score is $\frac{9 + 4 + 2 + 1 + 4 + 1 + 1}{8} = 2.75$


Solve in Python:
You're playing a game with a friend involving a bag of marbles. In the bag are ten marbles:

* 1 smooth red marble
* 4 bumpy red marbles
* 2 bumpy yellow marbles
* 1 smooth yellow marble
* 1 bumpy green marble
* 1 smooth green marble

You can see that the probability of picking a smooth red marble from the bag is `1 / 10` or `0.10` and the probability of picking a bumpy yellow marble is `2 / 10` or `0.20`.

The game works like this: your friend puts her hand in the bag, chooses a marble (without looking at it) and tells you whether it's bumpy or smooth. Then you have to guess which color it is before she pulls it out and reveals whether you're correct or not.

You know that the information about whether the marble is bumpy or smooth changes the probability of what color it is, and you want some help with your guesses.

Write a function `color_probability()` that takes two arguments: a color (`'red'`, `'yellow'`, or `'green'`) and a texture (`'bumpy'` or `'smooth'`) and returns the probability as a decimal fraction accurate to two places.

The probability should be a string and should discard any digits after the 100ths place. For example, `2 / 3` or `0.6666666666666666` would become the string `'0.66'`. Note this is different from rounding.

As a complete example, `color_probability('red', 'bumpy')` should return the string `'0.57'`.

def color_probability(color, texture):
    bag = [
        ("red", "smooth"),
        ("red", "bumpy"),
        ("red", "bumpy"),
        ("red", "bumpy"),
        ("red", "bumpy"),
        ("yellow", "bumpy"),
        ("yellow", "bumpy"),
        ("yellow", "smooth"),
        ("green", "bumpy"),
        ("green", "smooth"),
    ]
    candidates = [marble for marble in bag if marble[1] == texture]
    return "{:.03}".format(sum(marble[0] == color for marble in candidates) / len(candidates))[:-1]


Solve in Python:
You're putting together contact information for all the users of your website to ship them a small gift. You queried your database and got back a list of users, where each user is another list with up to two items: a string representing the user's name and their shipping zip code. Example data might look like:

```python
[["Grae Drake", 98110], ["Bethany Kok"], ["Alex Nussbacher", 94101], ["Darrell Silver", 11201]]
```
Notice that one of the users above has a name but _doesn't_ have a zip code.

Write a function `user_contacts()` that takes a two-dimensional list like the one above and returns a dictionary with an item for each user where the key is the user's name and the value is the user's zip code. If your data doesn't include a zip code then the value should be `None`.

For example, using the input above, `user_contacts()` would return this dictionary:
```python
{
    "Grae Drake": 98110,
    "Bethany Kok": None,
    "Alex Nussbacher": 94101,
    "Darrell Silver": 11201,
}
```

You don't have to worry about leading zeros in zip codes.

def user_contacts(data):
    return {name: (code[0] if code else None) for name, *code in data}


Solve in Python:
You're re-designing a blog and the blog's posts have the following format for showing the date and time a post was made:

*Weekday* *Month* *Day*, *time*
e.g.,
Friday May 2, 7pm

You're running out of screen real estate, and on some pages you want to display a shorter format, *Weekday* *Month* *Day* that omits the time.

Write a function, shortenToDate, that takes the Website date/time in its original string format, and returns the shortened format.

Assume shortenToDate's input will always be a string, e.g. "Friday May 2, 7pm". Assume shortenToDate's output will be the shortened string, e.g., "Friday May 2".

def shorten_to_date(long_date):
    f = long_date.find(', ')
    return long_date[: f]


Solve in Python:
You're writing an excruciatingly detailed alternate history novel set in a world where [Daniel Gabriel Fahrenheit](https://en.wikipedia.org/wiki/Daniel_Gabriel_Fahrenheit) was never born.

Since Fahrenheit never lived the world kept on using the [Rømer scale](https://en.wikipedia.org/wiki/R%C3%B8mer_scale), invented by fellow Dane [Ole Rømer](https://en.wikipedia.org/wiki/Ole_R%C3%B8mer) to this very day, skipping over the Fahrenheit and Celsius scales entirely.

Your magnum opus contains several thousand references to temperature, but those temperatures are all currently in degrees Celsius. You don't want to convert everything by hand, so you've decided to write a function, `celsius_to_romer()` that takes a temperature in degrees Celsius and returns the equivalent temperature in degrees Rømer.

For example: `celsius_to_romer(24)` should return `20.1`.

celsius_to_romer=lambda t: t * 21 / 40.0 + 7.5


Solve in Python:
You've arrived at a carnival and head straight for the duck shooting tent. Why wouldn't you?

You will be given a set amount of ammo, and an aim rating of between 1 and 0. No your aim is not always perfect - hey maybe someone fiddled with the sights on the gun...

Anyway your task is to calculate how many successful shots you will be able to make given the available ammo and your aim score, then return a string representing the pool of ducks, with those ducks shot marked with 'X' and those that survived left unchanged. You will always shoot left to right.

Example of start and end duck string with two successful shots:

Start ---> |~~~~~22~2~~~~~|

**Bang!! Bang!!**

End  --->  |~~~~~XX~2~~~~~|

All inputs will be correct type and never empty.

def duck_shoot(ammo, aim, ducks):
    hit = min(int(ammo * aim), ducks.count('2'))
    return ducks.replace('2', 'X', hit)


Solve in Python:
You've been collecting change all day, and it's starting to pile up in your pocket, but you're too lazy to see how much you've found.

Good thing you can code!

Create ```change_count()``` to return a dollar amount of how much change you have!

Valid types of change include:
```
penny: 0.01
nickel: 0.05
dime: 0.10
quarter: 0.25
dollar: 1.00
```

```if:python
These amounts are already preloaded as floats into the `CHANGE` dictionary for you to use!
```
```if:ruby
These amounts are already preloaded as floats into the `CHANGE` hash for you to use!
```
```if:javascript
These amounts are already preloaded as floats into the `CHANGE` object for you to use!
```
```if:php
These amounts are already preloaded as floats into the `CHANGE` (a constant) associative array for you to use!
```

You should return the total in the format ```$x.xx```.

Examples:

```python
change_count('nickel penny dime dollar') == '$1.16'
change_count('dollar dollar quarter dime dime') == '$2.45'
change_count('penny') == '$0.01'
change_count('dime') == '$0.10'
```

Warning, some change may amount to over ```$10.00```!

def change_count(change):
    total = 0
    for i in change.split(' '):
        if i == 'penny':
            total += 0.01
        elif i == 'nickel':
            total += 0.05
        elif i == 'dime':
            total += 0.10
        elif i == 'quarter':
            total += 0.25
        elif i == 'dollar':
            total += 1.00
    return "${:.2f}".format(total)

print(change_count('dime penny dollar'))
print(change_count('dime penny nickel'))
print(change_count('quarter quarter'))
print(change_count('dollar penny dollar'))


Solve in Python:
You've came to visit your grandma and she straight away found you a job - her Christmas tree needs decorating!

She first shows you a tree with an identified number of branches, and then hands you a some baubles (or loads of them!).

You know your grandma is a very particular person and she would like the baubles to be distributed in the orderly manner. You decide the best course of action would be to put the same number of baubles on each of the branches (if possible) or add one more bauble to some of the branches - starting from the beginning of the tree.

In this kata you will return an array of baubles on each of the branches.

For example:

10 baubles, 2 branches: [5,5]
5 baubles, 7 branches: [1,1,1,1,1,0,0]
12 baubles, 5 branches: [3,3,2,2,2]

The numbers of branches and baubles will be always greater or equal to 0.
If there are 0 branches return: "Grandma, we will have to buy a Christmas tree first!".

Good luck - I think your granny may have some minced pies for you if you do a good job!

def baubles_on_tree(baubles, branches):
    return [baubles//branches + (i < baubles % branches) for i in range(branches)] if branches else 'Grandma, we will have to buy a Christmas tree first!'


Solve in Python:
You've got a bunch of textual data with embedded phone numbers. Write a function `area_code()` that finds and returns just the area code portion of the phone number.
```python
>>> message = "The supplier's phone number is (555) 867-5309"
>>> area_code(message)
'555'
```
The returned area code should be a string, not a number.
Every phone number is formatted like in the example, and the only non-alphanumeric characters in the string are apostrophes `'` or the punctuation used in the phone number.

import re

def area_code(message):
    return re.search(r'\((\d{3})\)', message).group(1)


Solve in Python:
You've got a list of program warning logs. Each record of a log stream is a string in this format:  "2012-MM-DD HH:MM:SS:MESSAGE" (without the quotes).

String "MESSAGE" consists of spaces, uppercase and lowercase English letters and characters "!", ".", ",", "?". String "2012-MM-DD" determines a correct date in the year of 2012. String "HH:MM:SS" determines a correct time in the 24 hour format.

The described record of a log stream means that at a certain time the record has got some program warning (string "MESSAGE" contains the warning's description).

Your task is to print the first moment of time, when the number of warnings for the last n seconds was not less than m.

-----Input-----

The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 10000).

The second and the remaining lines of the input represent the log stream. The second line of the input contains the first record of the log stream, the third line contains the second record and so on. Each record of the log stream has the above described format. All records are given in the chronological order, that is, the warning records are given in the order, in which the warnings appeared in the program.

It is guaranteed that the log has at least one record. It is guaranteed that the total length of all lines of the log stream doesn't exceed 5·10^6 (in particular, this means that the length of some line does not exceed 5·10^6 characters). It is guaranteed that all given dates and times are correct, and the string 'MESSAGE" in all records is non-empty.

-----Output-----

If there is no sought moment of time, print -1. Otherwise print a string in the format "2012-MM-DD HH:MM:SS" (without the quotes) — the first moment of time when the number of warnings for the last n seconds got no less than m.

-----Examples-----
Input
60 3
2012-03-16 16:15:25: Disk size is
2012-03-16 16:15:25: Network failute
2012-03-16 16:16:29: Cant write varlog
2012-03-16 16:16:42: Unable to start process
2012-03-16 16:16:43: Disk size is too...

n, m = list(map(int, input().split(" ")))

messages = []

months = [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

while True:
    try:
        s = input()
        messages.append(s)

    except:
        break

# print(messages)

length = len(messages)

pref = [0]

for i in range(1, 13):
    pref.append(pref[i - 1] + months[i])

# print(pref)

got = False
now = 0
prev = 0
store = []

for message in messages:
    date = int(message[8:10]) + pref[int(message[5:7]) - 1]
    time = date * 24 * 60 * 60 + int(message[11:13]) * 60 * 60 + int(message[14:16]) * 60 + int(message[17:19])
    store.append(time)

    if now < m - 1:
        now += 1
        continue

    else:
        prev = now - (m - 1)

    if (store[now] - store[prev]) < n:
        print(message[:19])
        got = True
        break

    now += 1

if not got:
    print(-1)


Solve in Python:
You've got array A, consisting of n integers and a positive integer k. Array A is indexed by integers from 1 to n.

You need to permute the array elements so that value $\sum_{i = 1}^{n - k}|A [ i ] - A [ i + k ]|$ became minimal possible. In particular, it is allowed not to change order of elements at all.

-----Input-----

The first line contains two integers n, k (2 ≤ n ≤ 3·10^5, 1 ≤ k ≤ min(5000, n - 1)).

The second line contains n integers A[1], A[2], ..., A[n] ( - 10^9 ≤ A[i] ≤ 10^9), separate by spaces — elements of the array A.

-----Output-----

Print the minimum possible value of the sum described in the statement.

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

Output
1

Input
5 2
3 -5 3 -5 3

Output
0

Input
6 3
4 3 4 3 2 5

Output
3

-----Note-----

In the first test one of the optimal permutations is 1 4 2.

In the second test the initial order is optimal.

In the third test one of the optimal permutations is 2 3 4 4 3 5.

f = lambda: list(map(int, input().split()))
n, k = f()
p = sorted(f())

m, d = n // k, n % k
u, v = d + 1, k - d + 1
g = [0] * u * v

i = 0
for a in range(u):
    j = a * m + a - 1
    for b in range(v):
        x = g[i - 1] + p[j] - p[j - m + 1] if b else 9e9
        y = g[i - v] + p[j] - p[j - m] if a else 9e9
        if i: g[i] = min(x, y)
        i += 1
        j += m
print(g[-1])


Solve in Python:
You've had a baby.

Well done. Nice isn't it? Life destroying... but in a good way.

Part of your new routine is lying awake at night worrying that you've either lost the baby... or that you have more than 1!

Given a string of words (x), you need to calculate how many babies are in it. To count as a baby you must have all of the letters in baby ('b', 'a', 'b', 'y'). That counts as 1. They do not need to be in order in the string. Upper and lower case letters count.

Examples:

If there are no babies in the string - you lost the baby!! Return a different value, as shown below:

```if-not:kotlin
'none here' = "Where's the baby?!"
'' = "Where's the baby?!"
```

```if:kotlin
"none here" = null
"" = null
```

from collections import Counter

def baby_count(s):
    c = Counter(s.lower())
    return min(c['a'],c['b']//2,c['y']) or "Where's the baby?!"


Solve in Python:
You've just entered a programming contest and have a chance to win a million dollars. This is the last question you have to solve, so your victory (and your vacation) depend on it. Can you guess the function just by looking at the test cases? There are two numerical inputs and one numerical output. Goodluck!

hint: go
 here

def code(x,y):
    return 10**len(str(x))+10**len(str(y))+3-x-y-5


Solve in Python:
You've just recently been hired to calculate scores for a  Dart Board game!

Scoring specifications:

* 0 points - radius above 10
* 5 points - radius between 5 and 10 inclusive
* 10 points - radius less than 5

**If all radii are less than 5, award 100 BONUS POINTS!**

Write a function that accepts an array of radii (can be integers and/or floats), and returns a total score using the above specification.

An empty array should return 0.

## Examples:

def score_throws(radiuses):
    scores = [5 * ((v<5) + (v<=10)) for v in radiuses]
    return sum(scores) + 100 * (len(set(scores)) == 1 and scores[0] == 10)


Solve in Python:
You've made it through the moat and up the steps of knowledge. You've won the temples games and now you're hunting for treasure in the final temple run. There's good news and bad news. You've found the treasure but you've triggered a nasty trap. You'll surely perish in the temple chamber.

With your last movements, you've decided to draw an "X" marks the spot for the next archeologist.

Given an odd number, n, draw an X for the next crew. Follow the example below.

`
`
If n = 1 return 'X\n' and if you're given an even number or invalid input, return '?'.

The output should be a string with no spaces after the final X on each line, but a \n to indicate a new line.

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: Down in Fraggle Rock
80's Kids #10: Captain Planet

from itertools import chain

def mark_spot(n):
    if not (isinstance(n, int) and n % 2 and n > 0):
        return '?'
    result = []
    row_length = n * 2 - 1
    for a in chain(range(0, n, 2), range(n - 3, -1, -2)):
        row = [' '] * row_length
        row[a] = 'X'
        row[-(a + 1)] = 'X\n'
        result.append(''.join(row).rstrip(' '))
    return ''.join(result)


Solve in Python:
You've purchased a ready-meal from the supermarket.

The packaging says that you should microwave it for 4 minutes and 20 seconds, based on a 600W microwave.

Oh no, your microwave is 800W! How long should you cook this for?!

___

# Input

You'll be given 4 arguments:

## 1. needed power
The power of the needed microwave.
Example: `"600W"`

## 2. minutes
The number of minutes shown on the package.
Example: `4`

## 3. seconds
The number of seconds shown on the package.
Example: `20`

## 4. power
The power of your microwave.
Example: `"800W"`

___

# Output
The amount of time you should cook the meal for formatted as a string.
Example: `"3 minutes 15 seconds"`

Note: the result should be rounded up.
```
59.2 sec  -->  60 sec  -->  return "1 minute 0 seconds"
```

___

## All comments/feedback/translations appreciated.

cooking_time=lambda n,m,s,p:'{} minutes {} seconds'.format(*divmod(-(-(m*60+s)*int(n[:-1])//int(p[:-1])),60))


Solve in Python:
Young Sheldon is given the task to teach Chemistry to his brother Georgie. After teaching him how to find total atomic weight, Sheldon gives him some formulas which consist of $x$, $y$ and $z$ atoms as an assignment.
You already know that Georgie doesn't like Chemistry, so he want you to help him solve this assignment.
Let the chemical formula be given by the string $S$. It consists of any combination of x, y and z with some value associated with it as well as parenthesis to encapsulate any combination. Moreover, the atomic weight of x, y and z are 2, 4 and 10 respectively.
You are supposed to find the total atomic weight of the element represented by the given formula.
For example, for the formula $(x_2y_2)_3z$, given string $S$ will be: $(x2y2)3z$. Hence, substituting values of x, y and z, total atomic weight will be
$(2*2+4*2)*3 + 10 = 46$.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input $S$.

-----Output:-----
For each testcase, output in a single line, the total atomic weight.

-----Constraints-----
- $1 \leq T \leq 100$
- Length of string $S \leq 100$
- String contains $x, y, z, 1, 2,..., 9$ and parenthesis

-----Sample Input:-----
2
(xy)2
x(x2y)3(z)2

-----Sample Output:-----
12
46


Solve in Python:
Young wilderness explorers set off to their first expedition led by senior explorer Russell. Explorers went into a forest, set up a camp and decided to split into groups to explore as much interesting locations as possible. Russell was trying to form groups, but ran into some difficulties...

Most of the young explorers are inexperienced, and sending them alone would be a mistake. Even Russell himself became senior explorer not long ago. Each of young explorers has a positive integer parameter $e_i$ — his inexperience. Russell decided that an explorer with inexperience $e$ can only join the group of $e$ or more people.

Now Russell needs to figure out how many groups he can organize. It's not necessary to include every explorer in one of the groups: some can stay in the camp. Russell is worried about this expedition, so he asked you to help him.

-----Input-----

The first line contains the number of independent test cases $T$($1 \leq T \leq 2 \cdot 10^5$). Next $2T$ lines contain description of test cases.

The first line of description of each test case contains the number of young explorers $N$ ($1 \leq N \leq 2 \cdot 10^5$).

The second line contains $N$ integers $e_1, e_2, \ldots, e_N$ ($1 \leq e_i \leq N$), where $e_i$ is the inexperience of the $i$-th explorer.

It's guaranteed that sum of all $N$ doesn't exceed $3 \cdot 10^5$.

-----Output-----

Print $T$ numbers, each number on a separate line.

In $i$-th line print the maximum number of groups Russell can form in $i$-th test case.

-----Example-----
Input
2
3
1 1 1
5
2 3 1 2 2

Output
3
2

-----Note-----

In the first example we can organize three groups. There will be only one explorer in each group. It's correct because inexperience of each explorer equals to $1$, so it's not less than the size of his group.

In the second example we can organize two groups. Explorers with inexperience $1$, $2$ and $3$ will form the first group, and the other two explorers with inexperience equal to $2$ will form the second group.

This solution is not...

import sys
input = sys.stdin.readline

t = int(input())
for _ in range(t):
    n = int(input())
    e = list(map(int, input().split()))

    e = sorted(e)
    ans = 0

    cnt = 0
    max_ = 0
    for i in range(n):
        cnt += 1
        max_ = max(e[i], max_)
        if max_ <= cnt:
            ans += 1
            max_ = 0
            cnt = 0
    print(ans)


Solve in Python:
Your Goal is to create a function that takes  two strings, a guess and a phone number.

Based on the guess, the function should display a portion of the phone number:

    guess_my_number('052', '123-451-2345')
    would return the string: '#2#-#5#-2##5'

    or

    guess_my_number('142', '123-451-2345')
    would return the string: '12#-4#1-2#4#'

Order of the guess string should not matter, and should not have duplicates of the ten digitis 0-9. Guess will never be an empty string or contains any other charachters. The phone number will always bea ten digit number in the format ###-###-####.

The default number of 123-451-2345 should be included, but can be overwriten by a different number if supplied at the time of execution.

from re import sub
def guess_my_number(guess, number = '123-451-2345'):
    return sub('[^{}-]'.format(guess), '#', number)


Solve in Python:
Your aged grandfather is tragically optimistic about Team GB's chances in the upcoming World Cup, and has enlisted you to help him make [Union Jack](https://en.wikipedia.org/wiki/Union_Jack) flags to decorate his house with.

## Instructions
* Write a function which takes as a parameter a number which represents the dimensions of the flag. The flags will always be square, so the number 9 means you should make a flag measuring 9x9.
* It should return a *string* of the flag, with _'X' for the red/white lines and '-' for the blue background_. It should include newline characters so that it's not all on one line.
* For the sake of symmetry, treat odd and even numbers differently: odd number flags should have a central cross that is *only one 'X' thick*. Even number flags should have a central cross that is *two 'X's thick* (see examples below).

## Other points
* The smallest flag you can make without it looking silly is 7x7. If you get a number smaller than 7, simply _make the flag 7x7_.
* If you get a decimal, round it _UP to the next whole number_, e.g. 12.45 would mean making a flag that is 13x13.
* If you get something that's not a number at all, *return false*.

Translations and comments (and upvotes) welcome!

![alt](http://i.imgur.com/1612YR3.jpg?1)

## Examples:
```python
union_jack(9) # (9 is odd, so the central cross is 1'X' thick)
"X---X---X
-X--X--X-
--X-X-X--
---XXX---
XXXXXXXXX
---XXX---
--X-X-X--
-X--X--X-
X---X---X"

union_jack(10) # (10 is even, so the central cross is 2 'X's thick)
'X---XX---X
-X--XX--X-
--X-XX-X--
---XXXX---
XXXXXXXXXX
XXXXXXXXXX
---XXXX---
--X-XX-X--
-X--XX--X-
X---XX---X

union_jack(1) # (the smallest possible flag is 7x7)
"X--X--X
-X-X-X-
--XXX--
XXXXXXX
--XXX--
-X-X-X-
X--X--X"

union_jack('string') #return false.
```

def union_jack(n):
    try:
        n=-min(-7,int(-n//1))
    except:return False
    f=[['-X'[i==j or i==n-j-1 or (n-1)//2<=i<=n//2 or (n-1)//2<=j<=n//2]for i in range(n)]for j in range(n)]
    return'\n'.join(''.join(l)for l in f)


Solve in Python:
Your are given a string $S$ containing only lowercase letter and a array of character $arr$. Find whether the given string only contains characters from the given character array.
Print $1$ if the string contains characters from the given array only else print $0$.
Note: string contains characters in lower case only.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains-
a string $S$ of lowercase letter
a integer $n$ denoting length of character array $arr$
next line contains $n$ space separated characters.

-----Output:-----
For each testcase, Print $1$ if the string contains characters from the given array only else print $0$.

-----Constraints-----
- $1 \leq T \leq 1000$
- $0 \leq n \leq 10^5$

-----Sample Input:-----
3
abcd
4
a b c d
aabbbcccdddd
4
a b c d
acd
3
a b d

-----Sample Output:-----
1
1
0

from collections import Counter
for _ in range(int(input())):
   strs = set(input().strip())
   lens = int(input())
   inps = [x for x in input().split()]
   isOK = True
   for i in strs:
       if i not in inps:
           isOK = False
           break
   print(1 if isOK else 0)


Solve in Python:
Your back at your newly acquired decrypting job for the secret organization when a new assignment comes in.   Apparently the enemy has been communicating using a device they call "The Mirror".
It is a rudimentary device with encrypts the message by switching its letter with its mirror opposite (A => Z), (B => Y), (C => X) etc.

Your job is to build a method called "mirror" which will decrypt the messages. Resulting messages will be in lowercase.

To add more secrecy, you are to accept a second optional parameter, telling you which letters or characters are to be reversed; if it is not given, consider the whole alphabet as a default.

To make it a bit more clear: e.g. in case of "abcdefgh" as the second optional parameter, you replace "a" with "h", "b" with "g" etc. .

For example:
```python
mirror("Welcome home"), "dvoxlnv slnv" #whole alphabet mirrored here
mirror("hello", "abcdefgh"), "adllo" #notice only "h" and "e" get reversed
```

def mirror(code, chars="abcdefghijklmnopqrstuvwxyz"):
    return code.lower().translate(str.maketrans(chars, chars[::-1]))


Solve in Python:
Your boss decided to save money by purchasing some cut-rate optical character recognition software for scanning in the text of old novels to your database. At first it seems to capture words okay, but you quickly notice that it throws in a lot of numbers at random places in the text. For example:

```python
string_clean('! !') == '! !'
string_clean('123456789') == ''
string_clean('This looks5 grea8t!') == 'This looks great!'

```

Your harried co-workers are looking to you for a solution to take this garbled text and remove all of the numbers. Your program will take in a string and clean out all numeric characters, and return a string with spacing and special characters `~#$%^&!@*():;"'.,?` all intact.

def string_clean(s):
    new=""
    for char in s:
        if char in "1234567890":
            new+=""
        else: new+=char
    return new


Solve in Python:
Your car is old, it breaks easily. The shock absorbers are gone and you think it can handle about 15 more bumps before it dies totally.

Unfortunately for you, your drive is very bumpy! Given a string showing either flat road ("\_") or bumps ("n"), work out if you make it home safely. 15 bumps or under, return "Woohoo!", over 15 bumps return "Car Dead".

def bumps(road):
    counter = -1
    bumps = 0
    for x in road:
        counter += 1
        if road[counter] == 'n':
            bumps += 1
            print(bumps)
    if bumps <= 15:
        return 'Woohoo!'
    else:
        return 'Car Dead'


Solve in Python:
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.)
Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse).
When you get an instruction "A", your car does the following: position += speed, speed *= 2.
When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.)
For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1.
Now for some target position, say the length of the shortest sequence of instructions to get there.
Example 1:
Input:
target = 3
Output: 2
Explanation:
The shortest instruction sequence is "AA".
Your position goes from 0->1->3.

Example 2:
Input:
target = 6
Output: 5
Explanation:
The shortest instruction sequence is "AAARA".
Your position goes from 0->1->3->7->7->6.

Note:

1 <= target <= 10000.

class Solution:
    def racecar(self, target: int) -> int:
        # from answers:
        # Dojkstra's
        '''
        K = target.bit_length() + 1
        barrier = 1 << K
        pq = [(0, target)]
        dist = [float('inf')] * (2 * barrier + 1)
        dist[target] = 0

        while pq:
            steps, targ = heapq.heappop(pq)
            if dist[targ] > steps: continue

            for k in range(K+1):
                walk = (1 << k) - 1
                steps2, targ2 = steps + k + 1, walk - targ
                if walk == targ: steps2 -= 1 #No \"R\" command if already exact

                if abs(targ2) <= barrier and steps2 < dist[targ2]:
                    heapq.heappush(pq, (steps2, targ2))
                    dist[targ2] = steps2

        return dist[0]
        '''
        # Dynamic programming
        dp = [0, 1, 4] + [float('inf')] * target
        for t in range(3, target + 1):
            k = t.bit_length()
            if t == 2**k - 1:
                dp[t] = k
                continue
            for j in range(k - 1):
                dp[t] = min(dp[t], dp[t - 2**(k - 1) + 2**j] + k - 1 + j + 2)
            if 2**k - 1 - t < t:
                dp[t] = min(dp[t], dp[2**k - 1 - t] + k + 1)
        return dp[target]


Solve in Python:
Your classmates asked you to copy some paperwork for them. You know that there are 'n' classmates and the paperwork has 'm' pages.

Your task is to calculate how many blank pages do you need.

### Example:
```python
paperwork(5, 5) == 25
```

**Note:** if `n < 0` or `m < 0` return `0`!

Waiting for translations and Feedback! Thanks!

def paperwork(n, m):
    return n*m*(m>0 and n>0)


Solve in Python:
Your colleagues have been good enough(?) to buy you a birthday gift. Even though it is your birthday and not theirs, they have decided to play pass the parcel with it so that everyone has an even chance of winning. There are multiple presents, and you will receive one, but not all are nice... One even explodes and covers you in soil... strange office. To make up for this one present is a dog! Happy days! (do not buy dogs as presents, and if you do, never wrap them).

Depending on the number of passes in the game (y), and the present you unwrap (x), return as follows:

x == goodpresent --> return x with num of passes added to each charCode (turn to charCode, add y to each, turn back)
x == crap || x == empty --> return string sorted alphabetically
x == bang --> return string turned to char codes, each code reduced by number of passes and summed to a single figure
x == badpresent --> return 'Take this back!'
x == dog, return 'pass out from excitement y times' (where y is the value given for y).

def present(present, passes):
    if present == "goodpresent":
        return "".join(chr(ord(c) + passes) for c in present)
    elif present == "crap" or present == "":
        return "".join(sorted(present))
    elif present == "bang":
        return str(sum(map(ord, present)) - passes * len(present))
    elif present == "badpresent":
        return "Take this back!"
    elif present == "dog":
        return f"pass out from excitement {passes} times"
    else:
        return "empty"


Solve in Python:
Your colleagues have been looking over you shoulder. When you should have been doing your boring real job, you've been using the work computers to smash in endless hours of codewars.

In a team meeting, a terrible, awful person declares to the group that you aren't working. You're in trouble. You quickly have to gauge the feeling in the room to decide whether or not you should gather your things and leave.

```if-not:java
Given an object (meet) containing team member names as keys, and their happiness rating out of 10 as the value, you need to assess the overall happiness rating of the group. If <= 5, return 'Get Out Now!'. Else return 'Nice Work Champ!'.
```
```if:java
Given a `Person` array (meet) containing team members, you need to assess the overall happiness rating of the group. If <= 5, return "Get Out Now!". Else return "Nice Work Champ!".

The `Person` class looks like:
~~~java
class Person {
  final String name;    // team memnber's name
  final int happiness;  // happiness rating out of 10
}
~~~
```

Happiness rating will be total score / number of people in the room.

Note that your boss is in the room (boss), their score is worth double it's face value (but they are still just one person!).

The Office II - Boredom Score
The Office III - Broken Photocopier
The Office IV - Find a Meeting Room
The Office V - Find a Chair

def outed(meet, boss):
    return 'Get Out Now!' if sum(meet[person] if not person == boss else meet[person] * 2 for person in meet) / len(meet) <= 5 else 'Nice Work Champ!'


Solve in Python:
Your company was appointed to lay new asphalt on the highway of length $n$. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.

Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are $g$ days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next $b$ days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again $g$ good days, $b$ bad days and so on.

You can be sure that you start repairing at the start of a good season, in other words, days $1, 2, \dots, g$ are good.

You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the $n = 5$ then at least $3$ units of the highway should have high quality; if $n = 4$ then at least $2$ units should have high quality.

What is the minimum number of days is needed to finish the repair of the whole highway?

-----Input-----

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

Next $T$ lines contain test cases — one per line. Each line contains three integers $n$, $g$ and $b$ ($1 \le n, g, b \le 10^9$) — the length of the highway and the number of good and bad days respectively.

-----Output-----

Print $T$ integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.

-----Example-----
Input
3
5 1 1
8 10 10
1000000 1 1000000

Output
5
8
499999500000

-----Note-----

In the first test case, you can just lay new asphalt each day, since days $1, 3, 5$ are good.

In the second test case, you can also lay new asphalt each day, since days $1$-$8$ are good.

def iinput():
    return [int(x) for x in input().split()]

def main():
    n, g, b = iinput()
    z = (n + 1) // 2
    d = (z - 1) // g
    return max(d * b + z, n)

for i in range(int(input())):
    print(main())


Solve in Python:
Your company, [Congo Pizza](http://interesting-africa-facts.com/Africa-Landforms/Congo-Rainforest-Facts.html), is the second-largest online frozen pizza retailer. You own a number of international warehouses that you use to store your frozen pizzas, and you need to figure out how many crates of pizzas you can store at each location.

Congo recently standardized its storage containers: all pizzas fit inside a *cubic crate, 16-inchs on a side*. The crates are super tough so you can stack them as high as you want.

Write a function `box_capacity()` that figures out how many crates you can store in a given warehouse. The function should take three arguments: the length, width, and height of your warehouse (in feet) and should return an integer representing the number of boxes you can store in that space.

For example: a warehouse 32 feet long, 64 feet wide, and 16 feet high can hold 13,824 boxes because you can fit 24 boxes across, 48 boxes deep, and 12 boxes high, so `box_capacity(32, 64, 16)` should return `13824`.

def box_capacity(x, y, z):
  return int(x*0.75)*int(y*0.75)*int(z*0.75)


Solve in Python:
Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake which is full of water, there will be a flood. Your goal is to avoid the flood in any lake.
Given an integer array rains where:

rains[i] > 0 means there will be rains over the rains[i] lake.
rains[i] == 0 means there are no rains this day and you can choose one lake this day and dry it.

Return an array ans where:

ans.length == rains.length
ans[i] == -1 if rains[i] > 0.
ans[i] is the lake you choose to dry in the ith day if rains[i] == 0.

If there are multiple valid answers return any of them. If it is impossible to avoid flood return an empty array.
Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes. (see example 4)

Example 1:
Input: rains = [1,2,3,4]
Output: [-1,-1,-1,-1]
Explanation: After the first day full lakes are [1]
After the second day full lakes are [1,2]
After the third day full lakes are [1,2,3]
After the fourth day full lakes are [1,2,3,4]
There's no day to dry any lake and there is no flood in any lake.

Example 2:
Input: rains = [1,2,0,0,2,1]
Output: [-1,-1,2,1,-1,-1]
Explanation: After the first day full lakes are [1]
After the second day full lakes are [1,2]
After the third day, we dry lake 2. Full lakes are [1]
After the fourth day, we dry lake 1. There is no full lakes.
After the fifth day, full lakes are [2].
After the sixth day, full lakes are [1,2].
It is easy that this scenario is flood-free. [-1,-1,1,2,-1,-1] is another acceptable scenario.

Example 3:
Input: rains = [1,2,0,1,2]
Output: []
Explanation: After the second day, full lakes are  [1,2]. We have to dry one lake in the third day.
After that, it will rain over lakes [1,2]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.

Example 4:
Input: rains = [69,0,0,0,69]
Output: [-1,69,1,1,-1]
Explanation: Any solution on one of the...

from collections import defaultdict
from sortedcontainers import SortedSet
class Solution:
    def avoidFlood(self, rains: List[int]) -> List[int]:
        def getCeil(a, v):
            if not a:
                return None
            b = a.bisect_right(v)

            if b == 0:
                if a[b]>=v:
                    return a[b]
                return None
            if b==len(a):
                return None
            return a[b]

        res = [0]*len(rains)
        zeros = SortedSet()
        m = {}
        for  i, val in enumerate(rains):
            # print(i, val, m, zeros, res)
            if val == 0:
                zeros.add(i)
            else:
                if val in m:
                    n = getCeil(zeros, m[val])
                    print(n)
                    if not n: return []
                    res[n] = val
                    zeros.remove(n)
                res[i] = -1
                m[val] = i
        for i in zeros:
            res[i] = 1
        return res


Solve in Python:
Your coworker was supposed to write a simple helper function to capitalize a string (that contains a single word) before they went on vacation.

Unfortunately, they have now left and the code they gave you doesn't work. Fix the helper function they wrote so that it works as intended (i.e. make the first character in the string "word" upper case).

Don't worry about numbers, special characters, or non-string types being passed to the function. The string lengths will be from 1 character up to 10 characters, but will never be empty.

def capitalize_word(word):
    return word.capitalize()
print(capitalize_word('word'))


Solve in Python:
Your dad doesn't really *get* punctuation, and he's always putting extra commas in when he posts. You can tolerate the run-on sentences, as he does actually talk like that, but those extra commas have to go!

Write a function called ```dadFilter``` that takes a string as argument and returns a string with the extraneous commas removed. The returned string should not end with a comma or any trailing whitespace.

def dad_filter(string):
    #your code here
    new_list = string.split()
    for i in range(len(new_list)):
        while new_list[i].count(',') > 1:
            new_list[i] = new_list[i].replace(',', '', 1)

    str = ' '.join(new_list)
    while str[-1] in ' ,':
        str = str[:-1]
    return str


Solve in Python:
Your friend Cody has to sell a lot of jam, so he applied a good 25% discount to all his merchandise.

Trouble is that he mixed all the prices (initial and discounted), so now he needs your cool coding skills to filter out only the discounted prices.

For example, consider this inputs:
```
"15 20 60 75 80 100"
"9 9 12 12 12 15 16 20"
```
They should output:
```
"15 60 75"
"9 9 12 15"
```
Every input will always have all the prices in pairs (initial and discounted) sorted from smaller to bigger.

You might have noticed that the second sample input can be tricky already; also, try to have an eye for performances, as huge inputs could be tested too.

***Final Note:*** kata blatantly taken from [this problem](https://code.google.com/codejam/contest/8274486/dashboard) (and still not getting why they created a separated Code Jam for ladies, as I find it rather discriminating...), this kata was created inspired by two of the talented girls I am coaching thanks to [codebar](https://codebar.io/) :)

def find_discounted(prices):
    prices = [int(n) for n in prices.split()]
    return " ".join(prices.remove(round(p*4/3)) or str(p) for p in prices)


Solve in Python:
Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call Azamon. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to have better names than his competitors, then he'll be at the top of the search results and will be a millionaire.

After doing some research, you find out that search engines only sort their results lexicographically. If your friend could rename his products to lexicographically smaller strings than his competitor's, then he'll be at the top of the rankings!

To make your strategy less obvious to his competitors, you decide to swap no more than two letters of the product names.

Please help Jeff to find improved names for his products that are lexicographically smaller than his competitor's!

Given the string $s$ representing Jeff's product name and the string $c$ representing his competitor's product name, find a way to swap at most one pair of characters in $s$ (that is, find two distinct indices $i$ and $j$ and swap $s_i$ and $s_j$) such that the resulting new name becomes strictly lexicographically smaller than $c$, or determine that it is impossible.

Note: String $a$ is strictly lexicographically smaller than string $b$ if and only if one of the following holds:  $a$ is a proper prefix of $b$, that is, $a$ is a prefix of $b$ such that $a \neq b$;  There exists an integer $1 \le i \le \min{(|a|, |b|)}$ such that $a_i < b_i$ and $a_j = b_j$ for $1 \le j < i$.

-----Input-----

The first line of input contains a single integer $t$ ($1 \le t \le 1500$) denoting the number of test cases. The next lines contain descriptions of the test cases.

Each test case consists of a single line containing two space-separated strings $s$ and $c$ ($2 \le |s| \le 5000, 1 \le |c| \le 5000$). The strings $s$ and $c$ consists of uppercase English letters.

It is guaranteed that the sum of $|s|$ in the input is at most...

def main():
    TT = int(input())
    for _ in range(TT):
        w, t = input().strip().split(' ')
        w = list(w)

        sf = [len(w) - 1 for _ in range(len(w))]
        for i in range(len(w) - 2, -1, -1):
            if w[i] < w[sf[i+1]]:
                sf[i] = i
            else:
                sf[i] = sf[i + 1]

        for i in range(len(w)):
            if sf[i] != i and w[sf[i]] != w[i]:
                w[i], w[sf[i]] = w[sf[i]], w[i]
                break
        w = ''.join(w)
        if w < t:
            print(w)
        else:
            print('---')

def __starting_point():
    main()
__starting_point()


Solve in Python:
Your friend Rick is trying to send you a message, but he is concerned that it would get intercepted by his partner. He came up with a solution:

1) Add digits in random places within the message.

2) Split the resulting message in two. He wrote down every second character on one page, and the remaining ones on another. He then dispatched the two messages separately.

Write a function interweave(s1, s2) that reverses this operation to decode his message!

Example 1: interweave("hlo", "el") -> "hello"
Example 2: interweave("h3lo", "el4") -> "hello"

Rick's a bit peculiar about his formats. He would feel ashamed if he found out his message led to extra white spaces hanging around the edges of his message...

import re

def interweave(s1, s2):
    return re.sub(r'\d', '', ''.join(a+b for a,b in zip(s1, s2.ljust(len(s1), ' ')))).strip()


Solve in Python:
Your friend has been out shopping for puppies (what a time to be alive!)... He arrives back with multiple dogs, and you simply do not know how to respond!

By repairing the function provided, you will find out exactly how you should respond, depending on the number of dogs he has.

The number of dogs will always be a number and there will always be at least 1 dog.

```r
The expected behaviour is as follows:
- Your friend has fewer than 10 dogs:                    "Hardly any"
- Your friend has at least 10 but fewer than 51 dogs:    "More than a handful!"
- Your friend has at least 51 but not exactly 101 dogs:  "Woah that's a lot of dogs!"
- Your friend has 101 dogs:                              "101 DALMATIANS!!!"

Your friend will always have between 1 and 101 dogs, inclusive.
```

def how_many_dalmatians(n):
    dogs = ["Hardly any", "More than a handful!", "Woah that's a lot of dogs!", "101 DALMATIONS!!!"];
    return dogs [(n==101)+(50<n<=101)+(n>10)]


Solve in Python:
Your friend has invited you to a party, and tells you to meet them in the line to get in. The one problem is it's a masked party. Everyone in line is wearing a colored mask, including your friend. Find which people in line could be your friend.

Your friend has told you that he will be wearing a `RED` mask, and has **TWO** other friends with him, both wearing `BLUE` masks.

Input to the function will be an array of strings, each representing a colored mask. For example:
```python
line = ['blue','blue','red','red','blue','green']
```

The output of the function should be the number of people who could possibly be your friend.
```python
friend_find(['blue','blue','red','red','blue','green','chipmunk'])  # return 1
```

friend_find  = lambda arr:sum([1 for i in range(len(arr)) if arr[i] == "red" if (i > 1 and arr[i - 1] == "blue" and arr[i - 2] == "blue" ) or (i > 0 and i < len(arr) - 1 and arr[i - 1] == "blue" and arr[i + 1] == "blue") or (i < len(arr) - 2 and arr[i + 1] == "blue" and arr[i + 2] == "blue" )])


Solve in Python:
Your friend is typing his name into a keyboard.  Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times.
You examine the typed characters of the keyboard.  Return True if it is possible that it was your friends name, with some characters (possibly none) being long pressed.

Example 1:
Input: name = "alex", typed = "aaleex"
Output: true
Explanation: 'a' and 'e' in 'alex' were long pressed.

Example 2:
Input: name = "saeed", typed = "ssaaedd"
Output: false
Explanation: 'e' must have been pressed twice, but it wasn't in the typed output.

Example 3:
Input: name = "leelee", typed = "lleeelee"
Output: true

Example 4:
Input: name = "laiden", typed = "laiden"
Output: true
Explanation: It's not necessary to long press any character.

Constraints:

1 <= name.length <= 1000
1 <= typed.length <= 1000
The characters of name and typed are lowercase letters.

class Solution:
    def isLongPressedName(self, name: str, typed: str) -> bool:
        n = 0
        t = 0

        while n < len(name) and t < len(typed):
            if name[n] == typed[t]:
                n += 1
                t += 1
            else:
                if t and typed[t] == typed[t - 1]:
                    t += 1
                else:
                    return False

        if n != len(name):
            return False

        while t < len(typed):
            if typed[t] == typed[t - 1]:
                t += 1
            else:
                return False

        return True


Solve in Python:
Your friend won't stop texting his girlfriend.  It's all he does. All day. Seriously.  The texts are so mushy too! The whole situation just makes you feel ill.
Being the wonderful friend that you are, you hatch an evil plot.  While he's sleeping, you take his phone and change the autocorrect options so that every time he types "you" or "u" it gets changed to "your sister."

Write a function called autocorrect that takes a string and replaces all instances of "you" or "u" (not case sensitive) with "your sister" (always lower case).

Return the resulting string.

Here's the slightly tricky part: These are text messages, so there are different forms of "you" and "u".

For the purposes of this kata, here's what you need to support:

"youuuuu" with any number of u characters tacked onto the end
"u" at the beginning, middle, or end of a string, but NOT part of a word
"you" but NOT as part of another word like youtube or bayou

from re import sub, I

def autocorrect(input):
    return sub(r'\b(you+|u)\b', 'your sister', input, flags=I)


Solve in Python:
Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result.

It should remove all values from list `a`, which are present in list `b`.

```python
array_diff([1,2],[1]) == [2]
```

If a value is present in `b`, all of its occurrences must be removed from the other:

```python
array_diff([1,2,2,2,3],[2]) == [1,3]
```
~~~ if:c
NOTE: In C, assign return array length to pointer *z
~~~

def array_diff(a, b):
    #your code here
    for i in range(len(b)):
        while b[i] in a:
            a.remove(b[i])
    return a


Solve in Python:
Your goal is to create a function to format a number given a template; if the number is not present, use the digits `1234567890` to fill in the spaces.

A few rules:

* the template might consist of other numbers, special characters or the like: you need to replace only alphabetical characters (both lower- and uppercase);
* if the given or default string representing the number is shorter than the template, just repeat it to fill all the spaces.

A few examples:

```python
numeric_formatter("xxx xxxxx xx","5465253289") == "546 52532 89"
numeric_formatter("xxx xxxxx xx") == "123 45678 90"
numeric_formatter("+555 aaaa bbbb", "18031978") == "+555 1803 1978"
numeric_formatter("+555 aaaa bbbb") == "+555 1234 5678"
numeric_formatter("xxxx yyyy zzzz") == "1234 5678 9012"
```

def numeric_formatter(template, digits = "1234567890"):
    counter = 0
    formatted = ""
    for char in template:
        if counter >= len(digits):
            counter = 0
        if char.isalpha():
            formatted += digits[counter]
            counter += 1
        else:
            formatted += char
    return formatted


Solve in Python:
Your goal is to implement the method **meanVsMedian** which accepts an *odd-length* array of integers and returns one of the following:

* 'mean' - in case **mean** value is **larger than** median value
* 'median' - in case **median** value is **larger than** mean value
* 'same' - in case both mean and median share the **same value**

Reminder: [Median](https://en.wikipedia.org/wiki/Median)

Array will always be valid (odd-length >= 3)

from statistics import mean
from statistics import median

def mean_vs_median(n):
    return "mean" if mean(n)>median(n) else "median" if mean(n)<median(n) else "same"


Solve in Python:
Your goal is to return multiplication table for ```number``` that is always an integer from 1 to 10.

For example, a multiplication table (string) for ```number == 5``` looks like below:

```
1 * 5 = 5
2 * 5 = 10
3 * 5 = 15
4 * 5 = 20
5 * 5 = 25
6 * 5 = 30
7 * 5 = 35
8 * 5 = 40
9 * 5 = 45
10 * 5 = 50
```

P. S. You can use ```\n``` in string to jump to the next line.


Solve in Python:
Your job at E-Corp is both boring and difficult. It isn't made any easier by the fact that everyone constantly wants to have a meeting with you, and that the meeting rooms are always taken!

In this kata, you will be given an array. Each value represents a meeting room. Your job? Find the **first** empty one and return its index (N.B. There may be more than one empty room in some test cases).

'X' --> busy
'O' --> empty

If all rooms are busy, return 'None available!'.

More in this series:

The Office I - Outed
The Office II - Boredeom Score
The Office III - Broken Photocopier
The Office V - Find a Chair

def meeting(rooms):
    return next((i for i, r in enumerate(rooms) if r == 'O'), 'None available!')


Solve in Python:
Your job is to build a function which determines whether or not there are double characters in a string (including whitespace characters). For example ```aa```, ``!!`` or ```  ```.

You want the function to return true if the string contains double characters and false if not.  The test should not be case sensitive; for example both ```aa``` & ```aA``` return true.

Examples:
```python
  double_check("abca")
  #returns False

  double_check("aabc")
  #returns True

  double_check("a 11 c d")
  #returns True

  double_check("AabBcC")
  #returns True

  double_check("a b  c")
  #returns True

  double_check("a b c d e f g h i h k")
  #returns False

  double_check("2020")
  #returns False

  double_check("a!@€£#$%^&*()_-+=}]{[|\"':;?/>.<,~")
  #returns False
```

def double_check(strng):
    prev_char = strng[0]
    for char in strng[1:].lower():
        if char == prev_char:
            return True
        prev_char = char
    return False


Solve in Python:
Your job is to change the given string `s` using a non-negative integer `n`.

Each bit in `n` will specify whether or not to swap the case for each alphabetic character in `s`: if the bit is `1`, swap the case; if its `0`, leave it as is. When you finished with the last bit of `n`, start again with the first bit.

You should skip the checking of bits when a non-alphabetic character is encountered, but they should be preserved in their original positions.

## Examples

```
swap('Hello world!', 11)  -->  'heLLO wORLd!'
```
...because `11` is `1011` in binary, so the 1st, 3rd, 4th, 5th, 7th, 8th and 9th alphabetical characters have to be swapped:
```
H e l l o  w o r l d !
1 0 1 1 1  0 1 1 1 0
^   ^ ^ ^    ^ ^ ^
```

More examples:
```
swap("gOOd MOrniNg", 7864)  -->  "GooD MorNIng"
swap('', 11345)  -->  ''
swap('the lord of the rings', 0)  -->  'the lord of the rings'
```

from itertools import cycle

def swap(s,n):
    doSwap = cycle(map(int,f"{n:b}"))
    return ''.join(c.swapcase() if c.isalpha() and next(doSwap) else c for c in s)


Solve in Python:
Your job is to create a calculator which evaluates expressions in [Reverse Polish notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation).

For example expression `5 1 2 + 4 * + 3 -` (which is equivalent to `5 + ((1 + 2) * 4) - 3` in normal notation) should evaluate to `14`.

For your convenience, the input is formatted such that a space is provided between every token.

Empty expression should evaluate to `0`.

Valid operations are `+`, `-`, `*`, `/`.

You may assume that there won't be exceptional situations (like stack underflow or division by zero).

def calc(expr):
  stack = []
  [stack.append(eval("{1}{2}{0}".format(stack.pop(), stack.pop(), e)) if e in ('+', '-', '/', '*') else e) for e in expr.split()]
  return float(stack.pop()) if stack else 0


Solve in Python:
Your job is to figure out the index of which vowel is missing from a given string:

* `A` has an index of 0,
* `E` has an index of 1,
* `I` has an index of 2,
* `O` has an index of 3,
* `U` has an index of 4.

**Notes:** There is no need for string validation and every sentence given will contain all vowles but one. Also, you won't need to worry about capitals.

## Examples

```
"John Doe hs seven red pples under his bsket"          =>  0  ; missing: "a"
"Bb Smith sent us six neatly arranged range bicycles"  =>  3  ; missing: "o"
```

def absent_vowel(x):
    dictionary = {
    "a": 0,
    "e": 1,
    "i": 2,
    "o": 3,
    "u": 4}
    for vow in "aeiou":
        if vow not in x:
            return dictionary.get(vow)


Solve in Python:
Your job is to return the volume of a cup when given the diameter of the top, the diameter of the bottom and the height.

You know that there is a steady gradient from the top to the bottom.

You want to return the volume rounded to 2 decimal places.

Exmples:
```python
cup_volume(1, 1, 1)==0.79

cup_volume(10, 8, 10)==638.79

cup_volume(1000, 1000, 1000)==785398163.4

cup_volume(13.123, 123.12, 1)==4436.57

cup_volume(5, 12, 31)==1858.51
```

You will only be passed positive numbers.

import math
def cup_volume(d1, d2, height):
    return round(math.pi * height * (d1**2 + d2**2 + d1*d2)/12, 2)


Solve in Python:
Your job is to write a function that takes a string and a maximum number of characters per line and then inserts line breaks as necessary so that no line in the resulting string is longer than the specified limit.

If possible, line breaks should not split words. However, if a single word is longer than the limit, it obviously has to be split. In this case, the line break should be placed after the first part of the word (see examples below).

Really long words may need to be split multiple times.

#Input

A word consists of one or more letters.

Input text will be the empty string or a string consisting of one or more words separated by single spaces. It will not contain any punctiation or other special characters.

The limit will always be an integer greater or equal to one.

#Examples

**Note:** Line breaks in the results have been replaced with two dashes to improve readability.

1. ("test", 7) -> "test"
2. ("hello world", 7) -> "hello--world"
3. ("a lot of words for a single line", 10) -> "a lot of--words for--a single--line"
4. ("this is a test", 4) -> "this--is a--test"
5. ("a longword", 6) -> "a long--word"
6. ("areallylongword", 6) -> "areall--ylongw--ord"

**Note:** Sometimes spaces are hard to see in the test results window.

import re

def word_wrap(text, limit):

    string = text.split()
    res = []
    line = []

    while string:
        word = string.pop(0)
        if len(''.join(line)) + len(line) + len(word) <= limit:
            line.append(word)
        else:
            if len(word) > limit:
                so_far = len(''.join(line)) + len(line) - 1
                available_space = limit - so_far if line else limit
                rest_word = word[available_space - 1:] if line else word[available_space:]

                if available_space:
                    line.append(word[:available_space - 1] if line else word[:available_space])
                    res.append(' '.join(line))
                    string = [rest_word] + string
                else:
                    res.append(' '.join(line))
                    res.append(word[:limit])
                    string = [word[limit:]] + string

                line = []

            else:
                res.append(' '.join(line))
                line = [word]

    return '\n'.join(res + [' '.join(line)])


Solve in Python:
Your job is to write a function which increments a string, to create a new string.

- If the string already ends with a number, the number should be incremented by 1.
- If the string does not end with a number. the number 1 should be appended to the new string.

Examples:

`foo -> foo1`

`foobar23 -> foobar24`

`foo0042 -> foo0043`

`foo9 -> foo10`

`foo099 -> foo100`

*Attention: If the number has leading zeros the amount of digits should be considered.*

def increment_string(strng):
    if strng=='':
        return '1'
    if not '0'<=strng[-1]<='9':
        return strng+'1'
    if '0'<=strng[-1]<'9':
        return strng[:-1]+str(int(strng[-1])+1)
    i=-1
    while strng[i]=='9':
        i=i-1
    if not '0'<=strng[i]<'9':
        return strng[:i+1]+'1'+'0'*(-i-1)
    return strng[:i]+str(int(strng[i])+1)+'0'*(-i-1)


Solve in Python:
Your job is to write function last_digits(n,d) which return the last `d` digits of an integer `n` as a list.
`n` will be from 0 to 10^10

Examples:

`last_digits(1,1)     --> [1]`

`last_digits(1234,2)   --> [3,4]`

`last_digits(637547,6) --> [6,3,7,5,4,7]`

Special cases:

If `d` > the number of digits, just return the number's digits as a list.

If `d` <= 0, then return an empty list.

This is the first kata I have made, so please report any issues.

def solution(n, d):
    if d >= len(str(n)):
        list_return = list(str(n))
        for i in range(len(list_return)):
            list_return[i] = int(list_return[i])
        return list_return
    if d <= 0:
        return []
    list_return = list((str(n)[-d:]))
    for i in range(len(list_return)):
        list_return[i] = int(list_return[i])
    return list_return


Solve in Python:
Your music player contains N different songs and she wants to listen to L (not necessarily different) songs during your trip.  You create a playlist so that:

Every song is played at least once
A song can only be played again only if K other songs have been played

Return the number of possible playlists.  As the answer can be very large, return it modulo 10^9 + 7.

Example 1:
Input: N = 3, L = 3, K = 1
Output: 6
Explanation: There are 6 possible playlists. [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1].

Example 2:
Input: N = 2, L = 3, K = 0
Output: 6
Explanation: There are 6 possible playlists. [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], [1, 2, 2]

Example 3:
Input: N = 2, L = 3, K = 1
Output: 2
Explanation: There are 2 possible playlists. [1, 2, 1], [2, 1, 2]

Note:

0 <= K < N <= L <= 100

class Solution:
    import math
    from functools import lru_cache
    def numMusicPlaylists(self, N: int, L: int, K: int) -> int:
        MOD = 1000000007

        @lru_cache(maxsize=None)
        def rec(n, l):
            if l < n or n <= K:
                return 0
            elif l == n:
                return math.factorial(n) % MOD
            return (n * rec(n - 1, l - 1) + (n - K) * rec(n, l - 1)) % MOD

        return rec(N, L)


Solve in Python:
Your program will receive an array of complex numbers represented as strings. Your task is to write the  `complexSum` function which have to return the sum as a string.

Complex numbers can be written in the form of `a+bi`, such as `2-3i` where `2` is the real part, `3` is the imaginary part, and `i` is the "imaginary unit".

When you add two complex numbers, the real and the imaginary part needs to be added separately,so for example `2+3i + 5-i = (2+5)+(3i-i) = 7+2i`

Both the complex and the imaginary part can be 0, so `123`, `-2i` or `i` are also complex numbers.

Complex numbers must be returned in their shortest form, so e.g. `0+1*i` should be just `i`, and `10+0i` should be `10`. This is also how you will get them!

For simplicity, the coefficients will always be integers. If the array is empty, return `0`.

Have fun! :)

def complexSum(arr, sub={'1i': 'i', '-1i': '-i', '0i': '0'}):
    s = str(sum(complex(x.replace('i', 'j')) for x in arr)).replace('j', 'i')
    s = s.strip('()')
    s = s.replace('+0i', '')
    return sub.get(s, s)


Solve in Python:
Your retro heavy metal band, VÄxën, originally started as kind of a joke, just because why would anyone want to use the crappy foosball table in your startup's game room when they could be rocking out at top volume in there instead? Yes, a joke, but now all the top tech companies are paying you top dollar to play at their conferences and big product-release events. And just as how in the early days of the Internet companies were naming everything "i"-this and "e"-that, now that VÄxënmänïä has conquered the tech world, any company that doesn't use Hëävÿ Mëtäl Ümläüts in ëvëry pössïblë pläcë is looking hopelessly behind the times.

Well, with great power chords there must also come great responsibility! You need to help these companies out by writing a function that will guarantee that their web sites and ads and everything else will RÖCK ÄS MÜCH ÄS PÖSSÏBLË! Just think about it -- with the licensing fees you'll be getting from Gööglë, Fäcëböök, Äpplë, and Ämäzön alone, you'll probably be able to end world hunger, make college and Marshall stacks free to all, and invent self-driving bumper cars. Sö lët's gët röckïng and röllïng! Pëdal tö thë MËTÄL!

Here's a little cheatsheet that will help you write your function to replace the so-last-year letters a-e-i-o-u-and-sometimes-y with the following totally rocking letters:

```
A = Ä = \u00c4     E = Ë = \u00cb     I = Ï = \u00cf
O = Ö = \u00d6     U = Ü = \u00dc     Y = Ÿ = \u0178
a = ä = \u00e4     e = ë = \u00eb     i = ï = \u00ef
o = ö = \u00f6     u = ü = \u00fc     y = ÿ = \u00ff
```
### Python issues
First, Python in the Codewars environment has some codec/encoding issues with extended ASCII codes like the umlaut-letters required above. With Python 2.7.6, when writing your solution you can just copy the above umlaut-letters (instead of the unicode sequences) and paste them into your code, but I haven't found something yet that will work for *both* 2.7.6 and 3.4.3 -- hopefully I will find something soon (answers/suggestions are welcome!), and hopefully that...

# -*- coding: utf-8 -*-
def heavy_metal_umlauts(boring_text):
    return boring_text.translate(str.maketrans('AEIOUYaeiouy','ÄËÏÖÜŸäëïöüÿ'))


Solve in Python:
Your start-up's BA has told marketing that your website has a large audience in Scandinavia and surrounding countries. Marketing thinks it would be great to welcome visitors to the site in their own language. Luckily you already use an API that detects the user's location, so this is an easy win.

### The Task
- Think of a way to store the languages as a database (eg an object). The languages are listed below so you can copy and paste!
- Write a 'welcome' function that takes a parameter 'language' (always a string), and returns a greeting - if you have it in your database. It should default to English if the language is not in the database, or in the event of an invalid input.

### The Database

```python
'english': 'Welcome',
'czech': 'Vitejte',
'danish': 'Velkomst',
'dutch': 'Welkom',
'estonian': 'Tere tulemast',
'finnish': 'Tervetuloa',
'flemish': 'Welgekomen',
'french': 'Bienvenue',
'german': 'Willkommen',
'irish': 'Failte',
'italian': 'Benvenuto',
'latvian': 'Gaidits',
'lithuanian': 'Laukiamas',
'polish': 'Witamy',
'spanish': 'Bienvenido',
'swedish': 'Valkommen',
'welsh': 'Croeso'
```
``` java
english: "Welcome",
czech: "Vitejte",
danish: "Velkomst",
dutch: "Welkom",
estonian: "Tere tulemast",
finnish: "Tervetuloa",
flemish: "Welgekomen",
french: "Bienvenue",
german: "Willkommen",
irish: "Failte",
italian: "Benvenuto",
latvian: "Gaidits",
lithuanian: "Laukiamas",
polish: "Witamy",
spanish: "Bienvenido",
swedish: "Valkommen",
welsh: "Croeso"
```

Possible invalid inputs include:
~~~~
IP_ADDRESS_INVALID - not a valid ipv4 or ipv6 ip address
IP_ADDRESS_NOT_FOUND - ip address not in the database
IP_ADDRESS_REQUIRED - no ip address was supplied
~~~~

def greet(language):
    dict = {'english': 'Welcome',
'czech': 'Vitejte',
'danish': 'Velkomst',
'dutch': 'Welkom',
'estonian': 'Tere tulemast',
'finnish': 'Tervetuloa',
'flemish': 'Welgekomen',
'french': 'Bienvenue',
'german': 'Willkommen',
'irish': 'Failte',
'italian': 'Benvenuto',
'latvian': 'Gaidits',
'lithuanian': 'Laukiamas',
'polish': 'Witamy',
'spanish': 'Bienvenido',
'swedish': 'Valkommen',
'welsh': 'Croeso'}
    if language not in dict:
        return dict["english"]
    else:
        return dict[language]
    #your code here


Solve in Python:
Your task in order to complete this Kata is to write a function which formats a duration, given as a number of seconds, in a human-friendly way.

The function must accept a non-negative integer. If it is zero, it just returns `"now"`. Otherwise,  the duration is expressed as a combination of `years`, `days`, `hours`, `minutes` and `seconds`.

It is much easier to understand with an example:

```Fortran
formatDuration (62)    // returns "1 minute and 2 seconds"
formatDuration (3662)  // returns "1 hour, 1 minute and 2 seconds"
```
```python
format_duration(62)    # returns "1 minute and 2 seconds"
format_duration(3662)  # returns "1 hour, 1 minute and 2 seconds"
```

**For the purpose of this Kata, a year is 365 days and a day is 24 hours.**

Note that spaces are important.

### Detailed rules

The resulting expression is made of components like `4 seconds`, `1 year`, etc.  In general, a positive integer and one of the valid units of time, separated by a space. The unit of time is used in plural if the integer is greater than 1.

The components are separated by a comma and a space (`", "`). Except the last component, which is separated by `" and "`, just like it would be written in English.

A more significant units of time will occur before than a least significant one. Therefore, `1 second and 1 year` is not correct, but `1 year and 1 second` is.

Different components have different unit of times. So there is not repeated units like in `5 seconds and 1 second`.

A component will not appear at all if its value happens to be zero.  Hence, `1 minute and 0 seconds` is not valid, but it should be just `1 minute`.

 A unit of time must be used "as much as possible". It means that the function should not return `61 seconds`, but `1 minute and 1 second` instead.  Formally, the duration specified by  of a component must not be greater than any valid more significant unit of time.

def format_duration(seconds):
      if seconds==0:
       return "now"
      #if seconds==132375840:
          #return '4 years, 68 days, 3 hours and 4 minutes'
      minu, sec = divmod(seconds, 60)
      hour, minu = divmod(minu, 60)
      day,hour=divmod(hour,24)
      year,day=divmod(day,365)
      if year==0:
        if day==0:
            if hour==0:
               if minu==0:
                    if sec==1:
                        return str(sec)+' second'
                    return str(sec)+' seconds'
               if minu==1:
                    if sec==0:
                        return str(minu)+' minute'
                    if sec==1:
                        return str(minu)+' minute and '+str(sec)+' second'
                    return str(minu)+' minute and '+str(sec)+' seconds'
               if minu>1:
                    if sec==0:
                        return str(minu)+' minutes'
                    if sec==1:
                        return str(minu)+' minutes and '+str(sec)+' second'
                    return str(minu)+' minutes and '+str(sec)+' seconds'

            if hour==1:
               if minu==0:
                   if sec==0:
                        return str(hour)+' hour'

                   if sec==1:
                        return str(hour)+' hour and '+str(sec)+' second'
                   return str(hour)+' hour and '+str(sec)+' seconds'
               if minu==1:
                   if sec==0:
                       return str(hour)+' hour, '+str(minu)+' minute'

                   if sec==1:
                        return str(hour)+' hour, '+str(minu)+' minute and '+str(sec)+' second'
                   return str(hour)+' hour, '+str(minu)+' minute and '+str(sec)+' seconds'
               if sec==0:
                   return str(hour)+' hour, '+str(minu)+' minutes'

               if sec==1:
                    return str(hour)+' hour, '+str(minu)+' minutes and '+str(sec)+' second'
       ...