Solve in Python:
You managed to send your friend to queue for tickets in your stead, but there is a catch: he will get there only if you tell him how much that is going to take. And everybody can only take one ticket at a time, then they go back in the last position of the queue if they need more (or go home if they are fine).

Each ticket takes one minutes to emit, the queue is well disciplined, [Brit-style](https://www.codewars.com/kata/english-beggars), and so it moves smoothly, with no waste of time.

You will be given an array/list/vector with all the people queuing and the *initial* position of your buddy, so for example, knowing that your friend is in the third position (that we will consider equal to the index, `2`: he is the guy that wants 3 tickets!) and the initial queue is `[2, 5, 3, 4, 6]`.

The first dude gets his ticket and the queue goes now like this `[5, 3, 4, 6, 1]`, then `[3, 4, 6, 1, 4]` and so on. In the end, our buddy will be queuing for 12 minutes, true story!

Build a function to compute it, resting assured that only positive integers are going to be there and you will be always given a valid index; but we also want to go to pretty popular events, so be ready for big queues with people getting plenty of tickets.

[[hard core version](https://www.codewars.com/kata/queue-time-counter-hard-core-version/solutions/javascript) now available if you don't want the "easy" kata!]

def queue(queuers, pos, time = 0):
    while True:
        for i in range(len(queuers)):
            if queuers[pos] == 0:
                return time
            elif queuers[i]:
                queuers[i] -= 1
                time += 1


Solve in Python:
You may be familiar with the concept of combinations: for example, if you take 5 cards from a 52 cards deck as you would playing poker, you can have a certain number (2,598,960, would you say?) of different combinations.

In mathematics the number of *k* combinations you can have taking from a set of *n* elements is called the [binomial coefficient](https://en.wikipedia.org/wiki/Binomial_coefficient) of n and k, more popularly called **n choose k**.

The formula to compute it is relatively simple: `n choose k`==`n!/(k!*(n-k)!)`, where `!` of course denotes the factorial operator.

You are now to create a choose function that computes the binomial coefficient, like this:

```
choose(1,1)==1
choose(5,4)==5
choose(10,5)==252
choose(10,20)==0
choose(52,5)==2598960
```

Be warned: a certain degree of optimization is expected, both to deal with larger numbers precision (and their rounding errors in languages like JS) and computing time.

import sys
import functools
sys.setrecursionlimit(1_000_000)

# lru_cache is a python shortcut for memoization
# memoization is a technique to avoid repeatedly calculating
# something that has already been calculated

@functools.lru_cache(maxsize=1_000_000)
def choose(n,k):
    # pascals triangle uses only addition
    # so no rounding
    #               1
    #              1 1
    #             1 2 1
    #            1 3 3 1
    #           1 4 6 4 1
    # with exception of edge cases
    # this has recursive formula
    # choose(n, k) = choose(n-1, k-1) + choose(n-1, k)
    if k > n:
        return 0
    if k == 0 or k == n:
        return 1
    return choose(n-1, k-1) + choose(n-1, k)


Solve in Python:
You may have already known that a standard ICPC team consists of exactly three members. The perfect team however has more restrictions. A student can have some specialization: coder or mathematician. She/he can have no specialization, but can't have both at the same time.

So the team is considered perfect if it includes at least one coder, at least one mathematician and it consists of exactly three members.

You are a coach at a very large university and you know that $c$ of your students are coders, $m$ are mathematicians and $x$ have no specialization.

What is the maximum number of full perfect teams you can distribute them into?

Note that some students can be left without a team and each student can be a part of no more than one team.

You are also asked to answer $q$ independent queries.

-----Input-----

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

Each of the next $q$ lines contains three integers $c$, $m$ and $x$ ($0 \le c, m, x \le 10^8$) — the number of coders, mathematicians and students without any specialization in the university, respectively.

Note that the no student is both coder and mathematician at the same time.

-----Output-----

Print $q$ integers — the $i$-th of them should be the answer to the $i$ query in the order they are given in the input. The answer is the maximum number of full perfect teams you can distribute your students into.

-----Example-----
Input
6
1 1 1
3 6 0
0 0 0
0 1 1
10 1 10
4 4 1

Output
1
3
0
0
1
3

-----Note-----

In the first example here are how teams are formed:  the only team of 1 coder, 1 mathematician and 1 without specialization;  all three teams consist of 1 coder and 2 mathematicians;  no teams can be formed;  no teams can be formed;  one team consists of 1 coder, 1 mathematician and 1 without specialization, the rest aren't able to form any team;  one team consists of 1 coder, 1 mathematician and 1 without specialization, one consists of 2 coders and 1 mathematician and one consists of 1 coder...

from sys import stdin
q=int(stdin.readline().strip())
for i in range(q):
    c,m,x=list(map(int,stdin.readline().strip().split()))
    n=c+m+x
    y=min(c,m)
    t=n//3
    ans=min(y,t)
    print(ans)


Solve in Python:
You may have helped Chef and prevented Doof from destroying the even numbers. But, it has only angered Dr Doof even further. However, for his next plan, he needs some time. Therefore, Doof has built $N$ walls to prevent Chef from interrupting him. You have to help Chef by telling him the number of walls he needs to destroy in order to reach Dr Doof.
Formally, the whole area can be represented as the first quadrant with the origin at the bottom-left corner. Dr. Doof is located at the origin $(0, 0)$. There are $N$ walls, the i-th wall is a straight line segment joining the points $(a_i, 0)$ and $(0, a_i)$. For every initial position of Chef $(x_j, y_j)$, find the number of walls he needs to break before reaching Doof. Obviously, chef can't start from a point on the wall. Therefore, if $(x_j, y_j)$ lies on any of the given walls, print $-1$ in a new line.

-----Input-----
- First line contains $T$, denoting the number of testcases.
- The first line of every test case contains a single integer $N$ denoting the number of walls Dr Doof has built.
- The next line contains $N$ space separated distinct integers each denoting $a_i$.
- The next line contains a single integer $Q$ denoting the number of times Chef asks for your help.
- The next $Q$ lines contains two space separated integers $x_j$ and $y_j$, each denoting the co-ordinates of the starting point of Chef.

-----Output-----
For each query, print the number of walls Chef needs to break in order to reach Dr Doof in a separate line. If Chef tries to start from a point on any of the walls, print $-1$.

-----Constraints-----
- $1 \leq T \leq 2 * 10^2$
- $1 \leq N, Q \leq 2 * 10^5$
- $1 \leq a_i \leq 10^9$
- $0 \leq x_j, y_j \leq 10^9$
- $a_1 < a_2 < a_3 < .... < a_N$
- Sum of $N$ and $Q$ over all testcases for a particular test file does not exceed $2 * 10^5$

-----Sample Input-----
1
2
1 3
5
0 0
2 0
0 4
1 1
1 2

-----Sample Output-----
0
1
2
1
-1

-----Explanation-----
The sample input can be represented by the graph given below:

If Chef starts from $(0, 0)$,...

import sys
from sys import stdin,stdout
from bisect import bisect_right
from os import path
#cin=sys.stdin.readline
cout=sys.stdout.write

if (path.exists('input.txt')):
 #------------------Sublime--------------------------------------#
 sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
 def cinN():return (int(input()))
 def cin():return(map(int,input().split()))
else:
 #------------------PYPY FAst I/o--------------------------------#
 def cinN():return (int(stdin.readline()))
 def cin():return(map(int,stdin.readline().split()))

def find_le(a, x):
 'Find rightmost value less than or equal to x'
 i = bisect_right(a, x)
 if i:
  return i-1
 return -1

def func():
 st=''
 n=cinN()
 l=list(cin())
 l.sort()
 qn=cinN()
 for _ in range(qn):
  x,y=cin()
  k=x+y
  t=find_le(l,k)
  if t==-1:
   ans=(0)
  else:
   if l[t]==k:
    ans=(-1)
   else:ans=(t+1)
  print(ans)

def __starting_point():
 test=cinN()
 for _ in range(test):func()
__starting_point()


Solve in Python:
You may have tried your level best to help Chef but Dr Doof has managed to come up with his masterplan in the meantime. Sadly, you have to help Chef once again. Dr Doof has designed a parenthesis-inator. It throws a stream of $N$ brackets at the target, $1$ bracket per second. The brackets can either be opening or closing. Chef appears in front of the stream at time $t$. If Chef faces an opening bracket, he gets hit. However, if he faces a closing bracket, he may choose to let it pass through him (Chef is immune to closing brackets). Chef gets a chance to counter attack Doof as soon as he finds a balanced non-empty bracket sequence. Help Chef by providing him the minimum time $x$ at which he will be able to launch his counter attack. If Chef is unable to counter attack, answer $-1$.
Formally, you are given a string $S$ of length $N$ consisting only of opening brackets $($ and closing brackets $)$. The substring of $S$ starting at index $L$ and ending at index $R$, i.e. $S_L S_{L+1} \ldots S_{R}$ is denoted by $S[L, R]$ . Consider $Q$ cases. In the $i^{\text{th}}$ case, Chef appears at time $t_i$ $(1 \leq t_i \leq N)$ and faces all characters from index $t_i$ to $N$. Find the minimum index $x$ $(t_i \leq x \leq N)$ such that the substring $S[t_i, x]$ contains a non-empty balanced bracket subsequence containing the same number of opening brackets as $S[t_i, x]$ (i.e., you cannot remove any opening bracket from the substring). If such an $x$ does not exist, print $-1$.
A string $X$ is called a subsequence of a string $Y$ if it is possible to obtain $X$ by erasing some (possibly zero) characters from $Y$ without changing the order of the remaining characters.
A balanced bracket sequence is defined as:
- an empty string is a balanced bracket sequence.
- if $s$ is a balanced bracket sequence, then so is $(s)$.
- if $s$ and $t$ are balanced bracket sequences, then so is $st$.
$Note :-$ The input files are large. The use of Fast I/O is recommended.

-----Input-----
- The first line contains a single integer $T$...

from sys import stdin, stdout
for t in range(int(stdin.readline())):
    s = str(stdin.readline())
    q = int(stdin.readline())
    a =  list(map(int, stdin.readline().split()))
    d = {}
    stc = []
    p = -1
    for i in range((len(s) - 1), -1, -1):
        if(s[i] == ')'):
            stc.append(i)
            d[i+1] = p
        elif(s[i] == '('):
            if(len(stc) >= 1):
                d[i+1] = stc[-1] + 1
                p = d[i + 1]
                stc.pop()
            else:
                d[i+1] = -1
                p = d[i + 1]

    for i in a:
        print(d[i])


Solve in Python:
You might have heard about our new goodie distribution program aka the "Laddu Accrual System". This problem is designed to give you a glimpse of its rules. You can read the page once before attempting the problem if you wish, nonetheless we will be providing all the information needed here itself.

Laddu Accrual System is our new goodie distribution program. In this program, we will be distributing Laddus in place of goodies for your winnings and various other activities (described below), that you perform on our system. Once you collect enough number of Laddus, you can then redeem them to get yourself anything from a wide range of CodeChef goodies.

Let us know about various activities and amount of laddus you get corresponding to them.

- Contest Win (CodeChef’s Long, Cook-Off, LTIME, or any contest hosted with us) : 300 + Bonus (Bonus = 20 - contest rank). Note that if your rank is > 20, then you won't get any bonus.
- Top Contributor on Discuss : 300
- Bug Finder	: 50 - 1000 (depending on the bug severity). It may also fetch you a CodeChef internship!
- Contest Hosting	 : 50

You can do a checkout for redeeming laddus once a month. The minimum laddus redeemable at Check Out are 200 for Indians and 400 for the rest of the world.

You are given history of various activities of a user. The user has not redeemed any of the its laddus accrued.. Now the user just wants to redeem as less amount of laddus he/she can, so that the laddus can last for as long as possible. Find out for how many maximum number of months he can redeem the laddus.

-----Input-----
- The first line of input contains a single integer T denoting number of test cases
- For each test case:

- First line contains an integer followed by a string denoting activities, origin respectively, where activities denotes number of activities of the user, origin denotes whether the user is Indian or the rest of the world. origin can be "INDIAN" or "NON_INDIAN".
- For each of the next activities lines, each line contains an activity.

			An...

# cook your dish here
for T in range(int(input())):
 n,ind = input().split()
 n = int(n)
 laddu = 0
 for i in range(n):
  ls = list(input().split())
  if len(ls)==2:
   if ls[0] == "CONTEST_WON":
    k = int(ls[1])
    if 20>=k:
     laddu = laddu+(300+(20-k))
     # print(laddu)
    else:
     laddu = 300 + laddu
   elif ls[0] == "BUG_FOUND":
    d = int(ls[1])
    laddu = laddu+d
    # print(laddu)
  else:
   if ls[0]=="TOP_CONTRIBUTOR":
    laddu = laddu+300
   else:
    laddu = laddu+50

 if ind == "INDIAN":
  print(laddu//200)
 else:
  print(laddu//400)

# t=int(input())
# for z in range(t):
#   a=list(map(str,input().split()))
#   m=int(a[0])
#   s=a[1]
#   flag=0
#   if(s=="INDIAN"):
#     flag=1
#   ans=0
#   for i in range(m):
#     b=list(map(str,input().split()))
#     if(len(b)==2):
#       if(b[0]=="CONTEST_WON"):
#         val=int(b[1])
#         if(val>20):
#           ans+=300
#         else:
#           ans+=300+(20-val)
#       elif(b[0]=="BUG_FOUND"):
#         d=int(b[1])
#         ans+=d
#     else:
#       if(b[0]=="TOP_CONTRIBUTOR"):
#         ans+=300
#       else:
#         ans+=50
#   # print(ans)
#   sol=0
#   if(flag==1):
#     sol=ans//200
#   else:
#     sol=ans//400
#   print(sol)


Solve in Python:
You might know some pretty large perfect squares.  But what about the NEXT one?

Complete the `findNextSquare` method that finds the next integral perfect square after the one passed as a parameter.  Recall that an integral perfect square is an integer n such that sqrt(n) is also an integer.

If the parameter is itself not a perfect square then `-1` should be returned.  You may assume the parameter is positive.

**Examples:**

```
findNextSquare(121) --> returns 144
findNextSquare(625) --> returns 676
findNextSquare(114) --> returns -1 since 114 is not a perfect
```

def find_next_square(sq):
    x = sq**0.5
    return -1 if x % 1 else (x+1)**2


Solve in Python:
You must create a function, `spread`, that takes a function and a list of arguments to be applied to that function. You must make this function return the result of calling the given function/lambda with the given arguments.

eg:
```python
spread(someFunction, [1, true, "Foo", "bar"] )
# is the same as...
someFunction(1, true, "Foo", "bar")
```


Solve in Python:
You must create a method that can convert a string from any format into CamelCase. This must support symbols too.

*Don't presume the separators too much or you could be surprised.*

### Tests
```python
camelize("example name")   # => ExampleName
camelize("your-NaMe-here") # => YourNameHere
camelize("testing ABC")    # => TestingAbc
```

import re
def camelize(str_):
    return ''.join(x.capitalize() for x in re.split(r'[\W_]', str_))


Solve in Python:
You must have tried to solve the Rubik’s cube. You might even have succeeded at it. Rubik’s cube is a 3x3x3 cube which has 6 different color for each face.The Rubik’s cube is made from 26 smaller pieces which are called cubies. There are 6 cubies at the centre of each face and these comprise of a single color. There are 8 cubies at the 8 corners which comprise of exactly 3 colors. The 12 reamaining cubies comprise of exactly 2 colors.

Apple has come up with a variation of the Rubik’s Cube, it’s the Rubik’s cuboid which has different colors on its 6 faces. The Rubik’s Cuboid comes in various sizes represented by M x N x O (M,N,O are natural numbers). Apple is giving away 100 Rubik’s cuboid for free to people who can answer a simple questions. Apple wants to know, in a Rubik’s cuboid with arbitrary dimensions, how many cubies would be there, which comprise of exactly 2 color.

-----Input-----
The input contains several test cases.The first line of the input contains an integer T denoting the number of test cases.

Each test case comprises of 3 natural numbers, M,N & O, which denote the dimensions of the Rubiks Cuboid.

-----Output-----
For each test case you are required to output the number of  cubies which comprise of 2 squares, each of which is of a different color.

-----Constraints-----
- 1 ≤ T ≤ <1000
- 1 ≤ M ≤ <100000
- 1 ≤ N ≤ <100000
- 1 ≤ O ≤ <100000

-----Example-----
Input:
1
3
3
3

Output:

12

for _ in range(int(input())):
 a=int(input())
 b=int(input())
 c=int(input())
 if a==1 or b==1 or c==1:
  print(0)
 else:
  print(4*(a+b+c-6))


Solve in Python:
You need count how many valleys you will pass.

Start is always from zero level.

Every time you go down below 0 level counts as an entry of a valley, and as you go up to 0 level from valley counts as an exit of a valley.

One passed valley is equal one entry and one exit of a valley.
```
s='FUFFDDFDUDFUFUF'
U=UP
F=FORWARD
D=DOWN
```

To represent string above
```
(level 1)  __
(level 0)_/  \         _(exit we are again on level 0)
(entry-1)     \_     _/
(level-2)       \/\_/
```
So here we passed one valley

def counting_valleys(s):
    r = l = 0
    for x in s:
        if x == "U" and l == -1: r += 1
        if x != "F": l += 1 if x == "U" else -1
    return r


Solve in Python:
You need to create a function that will validate if given parameters are valid geographical coordinates.

Valid coordinates look like the following: __"23.32353342, -32.543534534"__.
The return value should be either __true__ or __false__.

Latitude (which is first float) can be between 0 and 90, positive or negative.
Longitude (which is second float) can be between 0 and 180, positive or negative.

Coordinates can only contain digits, or one of the following symbols (including space after comma) __ -, . __

There should be no space between the minus "-" sign and the digit after it.

Here are some valid coordinates:

* -23, 25
* 24.53525235, 23.45235
* 04, -23.234235
* 43.91343345, 143
* 4, -3

And some invalid ones:

* 23.234, - 23.4234
* 2342.43536, 34.324236
* N23.43345, E32.6457
* 99.234, 12.324
* 6.325624, 43.34345.345
* 0, 1,2
* 0.342q0832, 1.2324

def is_valid_coordinates(coordinates):
    x = coordinates.split(', ')
    try:
        if len(x) == 2 and 90 >= float(x[0]) >= -90 and 180 >= float(x[1]) >= -180 and not any(c.isalpha() for c in x[0]) and not any(c.isalpha() for c in x[1]):
            return True
    except:
        return False
    return False


Solve in Python:
You need to find the largest value in each row of a binary tree.

Example:

Input:

          1
         / \
        3   2
       / \   \
      5   3   9

Output: [1, 3, 9]

# Definition for a binary tree node.
 # class TreeNode:
 #     def __init__(self, x):
 #         self.val = x
 #         self.left = None
 #         self.right = None

 class Solution:
     def largestValues(self, root):
         """
         :type root: TreeNode
         :rtype: List[int]
         """
         if root is None:
             return []
         r = []
         s = [root]
         t = []
         while True:
             mx = float('-inf')
             for x in s:
                 if x.left != None:
                     t.append(x.left)
                 if x.right != None:
                     t.append(x.right)
                 if x.val > mx:
                     mx = x.val
             r.append(mx)
             if len(t)>0:
                 s=t
                 t=[]
             else:
                 return r


Solve in Python:
You need to play around with the provided string (s).

Move consonants forward 9 places through the alphabet.
If they pass 'z', start again at 'a'.

Move vowels back 5 places through the alphabet.
If they pass 'a', start again at 'z'.
For our Polish friends this kata does not count 'y' as a vowel.

Exceptions:

If the character is 'c' or 'o', move it back 1 place.
For 'd' move it back 3, and for 'e', move it back 4.

If a moved letter becomes 'c', 'o', 'd' or 'e', revert it back to it's original value.

Provided string will always be lower case, won't be empty and will have no special characters.

from string import ascii_lowercase as abc

def vowel_back(st): return st.translate(str.maketrans(abc,"vkbaafpqistuvwnyzabtpvfghi"))


Solve in Python:
You need to swap the head and the tail of the specified array:

the head (the first half) of array moves to the end, the tail (the second half) moves to the start.
The middle element (if it exists) leaves on the same position.

Return new array.

 For example:
 ```
    [ 1, 2, 3, 4, 5 ]   =>  [ 4, 5, 3, 1, 2 ]
     \----/   \----/
      head     tail

    [ -1, 2 ]  => [ 2, -1 ]
    [ 1, 2, -3, 4, 5, 6, -7, 8 ]   =>  [ 5, 6, -7, 8, 1, 2, -3, 4 ]
```

def swap_head_tail(lst):
    n, d = divmod(len(lst), 2)
    return lst[n+d:] + [lst[n]] * d + lst[:n]


Solve in Python:
You need to write a function that reverses the words in a given string. A word can also fit an empty string. If this is not clear enough, here are some examples:

As the input may have trailing spaces, you will also need to ignore unneccesary whitespace.

```python
reverse('Hello World') == 'World Hello'
reverse('Hi There.') == 'There. Hi'
```

Happy coding!

def reverse(st):
    k=st.split()
    m=k[::-1]
    return " ".join(m)


Solve in Python:
You need to write a function, that returns the first non-repeated character in the given string.

For example for string `"test"` function should return `'e'`.
For string `"teeter"` function should return `'r'`.

If a string contains all unique characters, then return just the first character of the string.
Example: for input `"trend"` function should return `'t'`

You can assume, that the input string has always non-zero length.

If there is no repeating character, return `null` in JS or Java, and `None` in Python.

def first_non_repeated(s):
    for character in s:
        if s.count(character) == 1:
            return character
            break


Solve in Python:
You play a computer game. In this game, you lead a party of $m$ heroes, and you have to clear a dungeon with $n$ monsters. Each monster is characterized by its power $a_i$. Each hero is characterized by his power $p_i$ and endurance $s_i$.

The heroes clear the dungeon day by day. In the beginning of each day, you choose a hero (exactly one) who is going to enter the dungeon this day.

When the hero enters the dungeon, he is challenged by the first monster which was not defeated during the previous days (so, if the heroes have already defeated $k$ monsters, the hero fights with the monster $k + 1$). When the hero fights the monster, there are two possible outcomes:

  if the monster's power is strictly greater than the hero's power, the hero retreats from the dungeon. The current day ends;  otherwise, the monster is defeated.

After defeating a monster, the hero either continues fighting with the next monster or leaves the dungeon. He leaves the dungeon either if he has already defeated the number of monsters equal to his endurance during this day (so, the $i$-th hero cannot defeat more than $s_i$ monsters during each day), or if all monsters are defeated — otherwise, he fights with the next monster. When the hero leaves the dungeon, the current day ends.

Your goal is to defeat the last monster. What is the minimum number of days that you need to achieve your goal? Each day you have to use exactly one hero; it is possible that some heroes don't fight the monsters at all. Each hero can be used arbitrary number of times.

-----Input-----

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

The first line of each test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of monsters in the dungeon.

The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($1 \le a_i \le 10^9$), where $a_i$ is the power of the $i$-th monster.

The third line contains one integer $m$ ($1 \le m \le 2 \cdot 10^5$) — the number of heroes in...

t = int(input())

for _ in range(t):
    n = int(input())
    a = list(map(int, input().split()))
    m = int(input())
    h = [tuple(map(int, input().split())) for i in range(m)]
    h.sort(reverse=True)
    new_h = []
    prev = 0
    for p, s in h:
        if s > prev:
            new_h.append((p, s))
            prev = s

    h = new_h
    hum = 0
    res = 1
    cur = 0
    maxp = 0
    for mon in a:
        maxp = max(mon, maxp)
        cur += 1
        if mon > h[0][0]:
            res = -1
            break
        if hum < len(h) and cur > h[hum][1]:
            hum += 1
        if hum == len(h) or maxp > h[hum][0]:
            res += 1
            hum = 0
            cur = 1
            maxp = mon

    print(res)


Solve in Python:
You probably know that the "mode" of a set of data is the data point that appears most frequently. Looking at the characters that make up the string `"sarsaparilla"` we can see that the letter `"a"` appears four times, more than any other letter, so the mode of `"sarsaparilla"` is `"a"`.

But do you know what happens when two or more data points occur the most? For example, what is the mode of the letters in `"tomato"`? Both `"t"` and `"o"` seem to be tied for appearing most frequently.

Turns out that a set of data can, in fact, have multiple modes, so `"tomato"` has two modes: `"t"` and `"o"`. It's important to note, though, that if *all* data appears the same number of times there is no mode. So `"cat"`, `"redder"`, and `[1, 2, 3, 4, 5]` do not have a mode.

Your job is to write a function `modes()` that will accept one argument `data` that is a sequence like a string or a list of numbers and return a sorted list containing the mode(s) of the input sequence. If data does not contain a mode you should return an empty list.

For example:

```python
>>> modes("tomato")
["o", "t"]
>>> modes([1, 3, 3, 7])
[3]
>>> modes(["redder"])
[]
```

You can trust that your input data will always be a sequence and will always contain orderable types (no inputs like `[1, 2, 2, "a", "b", "b"]`).

def modes(data):
    most, l, length = 0, [], len(data)
    for x in set(data):
        res = data.count(x)
        if most < res:
            most = res
            l = []
            l.append(x)
            length = len(data)-most
        elif most == res:
            l.append(x)
            length -= most
    return sorted(l) if length else []


Solve in Python:
You probably know the "like" system from Facebook and other pages. People can "like" blog posts, pictures or other items. We want to create the text that should be displayed next to such an item.

Implement a function `likes :: [String] -> String`, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples:

```python
likes([]) # must be "no one likes this"
likes(["Peter"]) # must be "Peter likes this"
likes(["Jacob", "Alex"]) # must be "Jacob and Alex like this"
likes(["Max", "John", "Mark"]) # must be "Max, John and Mark like this"
likes(["Alex", "Jacob", "Mark", "Max"]) # must be "Alex, Jacob and 2 others like this"
```

For 4 or more names, the number in `and 2 others` simply increases.

def likes(names):
    n = len(names)
    return {
        0: 'no one likes this',
        1: '{} likes this',
        2: '{} and {} like this',
        3: '{}, {} and {} like this',
        4: '{}, {} and {others} others like this'
    }[min(4, n)].format(*names[:3], others=n-2)


Solve in Python:
You probably know the 42 number as "The answer to life, the universe and everything" according to Douglas Adams' "The Hitchhiker's Guide to the Galaxy". For Freud, the answer was quite different.

In the society he lived in, people-women in particular- had to repress their sexual needs and desires. This was simply how the society was at the time.
Freud then wanted to study the illnesses created by this, and so he digged to the root of their desires. This led to some of the most important psychoanalytic theories to this day, Freud being the father of psychoanalysis.

Now, basically, when a person hears about Freud, s/he hears "sex" because for Freud, everything was basically related to, and explained by sex.

In this kata, the toFreud() function will take a string as its argument, and return a string with every word replaced by the explanation to everything, according to Freud. Note that an empty string, or no arguments, should result in the ouput being ""(empty string).

def to_freud(sentence):
    return ' '.join('sex' for el in sentence.split(' ') )


Solve in Python:
You receive some random elements as a space-delimited string. Check if the elements are part of an ascending sequence of integers starting with 1, with an increment of 1 (e.g. 1, 2, 3, 4).

Return:

* `0` if the elements can form such a sequence, and no number is missing ("not broken", e.g. `"1 2 4 3"`)
* `1` if there are any non-numeric elements in the input ("invalid", e.g. `"1 2 a"`)
* `n` if the elements are part of such a sequence, but some numbers are missing, and `n` is the lowest of them ("broken", e.g. `"1 2 4"` or `"1 5"`)

## Examples
```
"1 2 3 4"  ==>  return 0, because the sequence is complete

"1 2 4 3"  ==>  return 0, because the sequence is complete (order doesn't matter)

"2 1 3 a"  ==>  return 1, because it contains a non numerical character

"1 3 2 5"  ==>  return 4, because 4 is missing from the sequence

"1 5"      ==>  return 2, because the sequence is missing 2, 3, 4 and 2 is the lowest

```

def find_missing_number(sequence):
    if not sequence:
        return 0
    if not sequence.replace(" ", "").isnumeric():
        return 1
    seq = list(map(int, sequence.split(" ")))
    result = [number for number in [x for x in range(1, max(seq))] if number not in seq]
    return 0 if not result else result[0]


Solve in Python:
You receive the name of a city as a string, and you need to return a string that shows how many times each letter shows up in the string by using an asterisk (`*`).

For example:

```
"Chicago"  -->  "c:**,h:*,i:*,a:*,g:*,o:*"
```

As you can see, the letter `c` is shown only once, but with 2 asterisks.

The return string should include **only the letters** (not the dashes, spaces, apostrophes, etc). There should be no spaces in the output, and the different letters are separated by a comma (`,`) as seen in the example above.

Note that the return string must list the letters in order of their first appearence in the original string.

More examples:
```
"Bangkok"    -->  "b:*,a:*,n:*,g:*,k:**,o:*"
"Las Vegas"  -->  "l:*,a:**,s:**,v:*,e:*,g:*"
```

Have fun! ;)

def get_strings(city):
    city = city.lower()
    return ','.join(f"{c}:{'*' * city.count(c)}" for c in dict.fromkeys(city) if c.isalpha())


Solve in Python:
You received a whatsup message from an unknown number. Could it be from that girl/boy with a foreign accent you met yesterday evening?

Write a simple regex to check if the string contains the word hallo in different languages.

These are the languages of the possible people you met the night before:

* hello - english
* ciao - italian
* salut - french
* hallo - german
* hola - spanish
* ahoj - czech republic
* czesc - polish

By the way, how cool is the czech republic hallo!!

PS. you can assume the input is a string.
PPS. to keep this a beginner exercise you don't need to check if the greeting is a subset of word ('Hallowen' can pass the test)

PS. regex should be case insensitive to pass the tests

def validate_hello(greetings):
    return any(i for i in ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc'] if i in greetings.lower())


Solve in Python:
You should have done Product Partitions I to do this second part.
If you solved it, you should have notice that we try to obtain the multiplicative partitions with ```n ≤ 100 ```.

In this kata we will have more challenging values, our ```n ≤  10000```. So, we need a more optimized a faster code.

We need the function ```prod_int_partII()``` that will give all the amount of different products, excepting the number itself multiplied by one.

The function ```prod_int_partII()``` will receive two arguments, the number ```n``` for the one we have to obtain all the multiplicative partitions, and an integer s that determines the products that have an amount of factors equals to ```s```.

The function will output a list with this structure:
```python
[(1), (2), [(3)]]

(1) Total amount of different products we can obtain, using the factors of n. (We do not consider the product n . 1)

(2) Total amount of products that have an amount of factors equals to s.

[(3)] A list of lists with each product represented with by a sorted list of the factors. All the product- lists should be sorted also.
If we have only one product-list as a result, the function will give only the list
and will not use the list of lists
```
Let's see some cases:
```python
prod_int_partII(36, 3) == [8, 3, [[2, 2, 9], [2, 3, 6], [3, 3, 4]]]

/// (1) ----> 8 # Amount of different products, they are: [2, 2, 3, 3], [2, 2, 9],
[2, 3, 6], [2, 18], [3, 3, 4], [3, 12], [4, 9], [6, 6] (8 products)

    (2) ----> 3 # Amount of products with three factors (see them bellow)

    (3) ----> [[2, 2, 9], [2, 3, 6], [3, 3, 4]] # These are the products with 3 factors
```
```python
prod_int_partII(48, 5) == [11, 1, [2, 2, 2, 2, 3]] # Only one list.
```
Again consider that some numbers will not have multiplicative partitions.
```python
prod_int_partII(37, 2) == [0, 0, []]
```
Happy coding!!

(Recursion is advisable)

from functools import reduce

def updateParts(d,s,n,p):
    d.append(p)
    for t in list(s):
        s.add(tuple(sorted(t+(p,))))
        for i in range(len(t)):
            s.add( tuple(sorted(t[:i]+(p*t[i],)+(t[i+1:]))) )
    s.add((p,))
    return n//p

def prod_int_partII(n,m):
    x,d,s,p = n,[],set(),2
    while p*p<=n:
        while not n%p: n = updateParts(d,s,n,p)
        p += 1+(p!=2)
    if n-1 and n!=x: updateParts(d,s,-1,n)

    s = [t for t in s if reduce(int.__mul__,t)==x and len(t)>1]
    d = sorted(list(t) for t in s if len(t)==m)

    return [len(s),len(d),d[0] if len(d)==1 else d]


Solve in Python:
You should write a function that takes a string and a positive integer `n`, splits the string into parts of length `n` and returns them in an array. It is ok for the last element to have less than `n` characters.

If `n` is not a valid size (`> 0`) (or is absent), you should return an empty array.

If `n` is greater than the length of the string, you should return an array with the only element being the same string.

Examples:

```python
string_chunk('codewars', 2) # ['co', 'de', 'wa', 'rs']
string_chunk('thiskataeasy', 4) # ['this', 'kata', 'easy']
string_chunk('hello world', 3) # ['hel', 'lo ', 'wor', 'ld']
string_chunk('sunny day', 0) # []
```

def string_chunk(string, n=0):
    if isinstance(n, int) and n > 0:
        starts = range(0, len(string), n)
    else:
        starts = []
    return [string[i:i+n] for i in starts]


Solve in Python:
You should write a simple function that takes string as input and checks if it is a valid Russian postal code, returning `true` or `false`.

A valid postcode should be 6 digits with no white spaces, letters or other symbols. Empty string should also return false.

Please also keep in mind that a valid post code **cannot start with** `0, 5, 7, 8 or 9`

## Examples

Valid postcodes:
* 198328
* 310003
* 424000

Invalid postcodes:
* 056879
* 12A483
* 1@63
* 111

def zipvalidate(p):
    return p.isdigit() and 100000 < int(p) < 699999 and p[0] != "5"

# Python translation of kata by MMMAAANNN


Solve in Python:
You start with a value in dollar form, e.g. $5.00. You must convert this value to a string in which the value is said, like '5 dollars' for example. This should account for ones, cents, zeroes, and negative values. Here are some examples:
```python
dollar_to_speech('$0.00') == '0 dollars.'
dollar_to_speech('$1.00') == '1 dollar.'
dollar_to_speech('$0.01') == '1 cent.'
dollar_to_speech('$5.00') == '5 dollars.'
dollar_to_speech('$20.18') == '20 dollars and 18 cents.'
dollar_to_speech('$-1.00') == 'No negative numbers are allowed!'
```
These examples account for pretty much everything. This kata has many specific outputs, so good luck!

import re
def dollar_to_speech(val):
    if '-' in val: return 'No negative numbers are allowed!'
    c =  int(re.findall(r'\.(\d+)',val)[0])
    d = int(re.findall(r'\$(\d+)\.',val)[0])
    if d == 0 == c : return '0 dollars.'

    seg1 = '{} dollar{}'.format(d,('s' if d > 1 else '')) if d else ''
    seg2 = '{} cent{}'.format(c,  ('s' if c > 1 else '')) if c else ''
    seg3 = ' and ' if seg1 and seg2 else ''
    return ''.join([seg1,seg3,seg2,'.'])


Solve in Python:
You take your son to the forest to see the monkeys. You know that there are a certain number there (n), but your son is too young to just appreciate the full number, he has to start counting them from 1.

As a good parent, you will sit and count with him. Given the number (n), populate an array with all numbers up to and including that number, but excluding zero.

For example:
```python
monkeyCount(10) # --> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
monkeyCount(1) # --> [1]
```

def monkey_count(n):
    count = []

    for i in range(1,n+1):
        count += [i]
    return(count)


Solve in Python:
You task is to implement an simple interpreter for the notorious esoteric language [HQ9+](https://esolangs.org/wiki/HQ9+) that will work for a single character input:

- If the input is `'H'`, return `'Hello World!'`
- If the input is `'Q'`, return the input
- If the input is `'9'`, return the full lyrics of [99 Bottles of Beer](http://www.99-bottles-of-beer.net/lyrics.html). It should be formatted like this:

```if:rust
__Note__: In Rust, return `Some` containing the appropriate value.
```

```
99 bottles of beer on the wall, 99 bottles of beer.
Take one down and pass it around, 98 bottles of beer on the wall.
98 bottles of beer on the wall, 98 bottles of beer.
Take one down and pass it around, 97 bottles of beer on the wall.
97 bottles of beer on the wall, 97 bottles of beer.
Take one down and pass it around, 96 bottles of beer on the wall.
...
...
...
2 bottles of beer on the wall, 2 bottles of beer.
Take one down and pass it around, 1 bottle of beer on the wall.
1 bottle of beer on the wall, 1 bottle of beer.
Take one down and pass it around, no more bottles of beer on the wall.
No more bottles of beer on the wall, no more bottles of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.
```

- For everything else, don't return anything (return `null` in C#, `None` in Rust).

(`+` has no visible effects so we can safely ignore it.)

def HQ9(code):
    if code == 'Q': return code
    elif code == 'H': return "Hello World!"
    elif code == '9': return '99 bottles of beer on the wall, 99 bottles of beer.\nTake one down and pass it around, 98 bottles of beer on the wall.\n98 bottles of beer on the wall, 98 bottles of beer.\nTake one down and pass it around, 97 bottles of beer on the wall.\n97 bottles of beer on the wall, 97 bottles of beer.\nTake one down and pass it around, 96 bottles of beer on the wall.\n96 bottles of beer on the wall, 96 bottles of beer.\nTake one down and pass it around, 95 bottles of beer on the wall.\n95 bottles of beer on the wall, 95 bottles of beer.\nTake one down and pass it around, 94 bottles of beer on the wall.\n94 bottles of beer on the wall, 94 bottles of beer.\nTake one down and pass it around, 93 bottles of beer on the wall.\n93 bottles of beer on the wall, 93 bottles of beer.\nTake one down and pass it around, 92 bottles of beer on the wall.\n92 bottles of beer on the wall, 92 bottles of beer.\nTake one down and pass it around, 91 bottles of beer on the wall.\n91 bottles of beer on the wall, 91 bottles of beer.\nTake one down and pass it around, 90 bottles of beer on the wall.\n90 bottles of beer on the wall, 90 bottles of beer.\nTake one down and pass it around, 89 bottles of beer on the wall.\n89 bottles of beer on the wall, 89 bottles of beer.\nTake one down and pass it around, 88 bottles of beer on the wall.\n88 bottles of beer on the wall, 88 bottles of beer.\nTake one down and pass it around, 87 bottles of beer on the wall.\n87 bottles of beer on the wall, 87 bottles of beer.\nTake one down and pass it around, 86 bottles of beer on the wall.\n86 bottles of beer on the wall, 86 bottles of beer.\nTake one down and pass it around, 85 bottles of beer on the wall.\n85 bottles of beer on the wall, 85 bottles of beer.\nTake one down and pass it around, 84 bottles of beer on the wall.\n84 bottles of beer on the wall, 84 bottles of beer.\nTake one down and pass it around, 83 bottles of beer on the wall.\n83...


Solve in Python:
You throw a ball vertically upwards with an initial speed `v (in km per hour)`. The height `h` of the ball at each time `t`
is given by `h = v*t - 0.5*g*t*t` where `g` is Earth's gravity `(g ~ 9.81 m/s**2)`. A device is recording at every **tenth
of second** the height of the ball.
For example with `v = 15 km/h` the device gets something of the following form:
`(0, 0.0), (1, 0.367...), (2, 0.637...), (3, 0.808...), (4, 0.881..) ...`
where the first number is the time in tenth of second and the second number the height in meter.
# Task
Write a function `max_ball` with parameter `v (in km per hour)` that returns the `time in tenth of second`
of the maximum height recorded by the device.
# Examples:
`max_ball(15) should return 4`

`max_ball(25) should return 7`
# Notes
- Remember to convert the velocity from km/h to m/s or from m/s in km/h when necessary.
- The maximum height recorded by the device is not necessarily the maximum height reached by the ball.

def max_ball(v0):
    # acceleration
    g = 9.81
    # height from ground, u is time in s, v speed in m/s
    def h(u):
        return v*u - 0.5*g*u*u
    # from km/h to m/s
    v = v0 * 1000 / 3600.0
    # in t = v/g the derivative is 0, the height is max
    t = v / g
    # record done every 0.1 s; tm is in tenth of second
    tm = int(t*10)
    # device max is before (<=) or after tm (>)
    h1 = h( tm/10.0 )
    h2 = h( (tm+1)/10.0 )
    mx = max( h1, h2 )
    # is the recorded max before or after the theoric max
    if (mx == h( tm/10.0 )):
        return tm
    else:
        return tm+1


Solve in Python:
You visit a doctor on a date given in the format $yyyy:mm:dd$. Your doctor suggests you to take pills every alternate day starting from that day. You being a forgetful person are pretty sure won’t be able to remember the last day you took the medicine and would end up in taking  the medicines on wrong days.
So you come up with the idea of taking medicine on the dates whose day is odd or even depending on whether $dd$ is odd or even. Calculate the number of pills you took on right time before messing up for the first time.

-----Note:-----
Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, in the format $yyyy:mm:dd$

-----Output:-----
For each testcase, output in a single line the required answer.

-----Constraints-----
- $ 1 \leq T \leq 1000 $
- $ 1900 \leq yyyy \leq 2038 $
- $yyyy:mm:dd$ is a valid date

-----Sample Input:-----
1
2019:03:31

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

-----EXPLANATION:-----
You can take pill on the right day only on 31st March. Next you will take it on 1st April which is not on the alternate day.

from sys import stdin, stdout
ans = []

def leap_check(yy):
 if yy % 400 == 0:
  return True
 elif yy % 100 == 0:
  return False
 elif yy % 4 == 0:
  return True
 else:
  return 0

for _ in range(int(stdin.readline())):
 yy, mm, dd = list(map(int, stdin.readline().split(':')))
 if mm in [1, 3, 5, 7, 8, 10, 12]:
  ans.append(str(int(((31 - dd) / 2) + 1)))
 elif mm in [4, 6, 9, 11]:
  ans.append(str(int(((30 - dd) / 2) + 16 + (dd % 2))))
 else:
  ans.append(str(int((29 - dd) / 2 + 1)
      if leap_check(yy) else int((28 - dd)/2 + 16 + (dd % 2))))
stdout.write('\n'.join(ans))


Solve in Python:
You want to build a standard house of cards, but you don't know how many cards you will need. Write a program which will count the minimal number of cards according to the number of floors you want to have. For example, if you want a one floor house, you will need 7 of them (two pairs of two cards on the base floor, one horizontal card and one pair to get the first floor). Here you can see which kind of house of cards I mean:
http://www.wikihow.com/Build-a-Tower-of-Cards

## Note about floors:
This kata uses the British numbering system for building floors. If you want your house of cards to have a first floor, it needs a ground floor and then a first floor above that.

### Details (Ruby & JavaScript & Python & R)
The input must be an integer greater than 0, for other input raise an error.

### Details (Haskell)
The input must be an integer greater than 0, for other input return `Nothing`.

def house_of_cards(n):
    assert n > 0
    return (n + 1) * (3 * n + 4) // 2


Solve in Python:
You want to build a temple for snakes. The temple will be built on a mountain range, which can be thought of as n blocks, where height of i-th block is given by hi. The temple will be made on a consecutive section of the blocks and its height should start from 1 and increase by exactly 1 each time till some height and then decrease by exactly 1 each time to height 1,
i.e. a consecutive section of 1, 2, 3, .. x-1, x, x-1, x-2, .., 1 can correspond to a temple. Also, heights of all the blocks other than of the temple should have zero height, so that the temple is visible to people who view it from the left side or right side.
You want to construct a temple. For that, you can reduce the heights of some of the blocks. In a single operation, you can reduce the height of a block by 1 unit. Find out minimum number of operations required to build a temple.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains an integer n.
The next line contains n integers, where the i-th integer denotes hi

-----Output-----
For each test case, output a new line with an integer corresponding to the answer of that testcase.

-----Constraints-----
- 1 ≤ T ≤ 10
- 2 ≤ n ≤ 105
- 1 ≤ hi ≤ 109

-----Example-----
Input
3
3
1 2 1
4
1 1 2 1
5
1 2 6 2 1

Output
0
1
3

-----Explanation-----
Example 1. The entire mountain range is already a temple. So, there is no need to make any operation.
Example 2. If you reduce the height of the first block to 0. You get 0 1 2 1. The blocks 1, 2, 1 form a temple. So, the answer is 1.
Example 3. One possible temple can be 1 2 3 2 1. It requires 3 operations to build. This is the minimum amount you have to spend in order to build a temple.

t=int(input())
for _ in range(t):
 n=int(input())
 arr = list(map(int, input(). strip(). split()))
 a=[0]*n
 b=[0]*n
 if arr[0]>=1:
  a[0]+=1
  b[0]+=1
 if arr[-1]>=1:
  a[-1]+=1
  b[-1]+=1
 for i in range(1,n):
  if arr[i]>=a[i-1]+1:
   a[i]=a[i-1]+1
  else:
   a[i]=arr[i]
 for j in range(n-2,-1,-1):
  if arr[j]>=b[j+1]+1:
   b[j]=b[j+1]+1
  else:
   b[j]=arr[j]
 max=0
 for i in range(n):
  tmp=min(a[i],b[i])
  if tmp>max:
   max=tmp
 total = sum(arr)
 s=max+ (max*(max-1))
 print(total-s)


Solve in Python:
You want to form a target string of lowercase letters.
At the beginning, your sequence is target.length '?' marks.  You also have a stamp of lowercase letters.
On each turn, you may place the stamp over the sequence, and replace every letter in the sequence with the corresponding letter from the stamp.  You can make up to 10 * target.length turns.
For example, if the initial sequence is "?????", and your stamp is "abc",  then you may make "abc??", "?abc?", "??abc" in the first turn.  (Note that the stamp must be fully contained in the boundaries of the sequence in order to stamp.)
If the sequence is possible to stamp, then return an array of the index of the left-most letter being stamped at each turn.  If the sequence is not possible to stamp, return an empty array.
For example, if the sequence is "ababc", and the stamp is "abc", then we could return the answer [0, 2], corresponding to the moves "?????" -> "abc??" -> "ababc".
Also, if the sequence is possible to stamp, it is guaranteed it is possible to stamp within 10 * target.length moves.  Any answers specifying more than this number of moves will not be accepted.

Example 1:
Input: stamp = "abc", target = "ababc"
Output: [0,2]
([1,0,2] would also be accepted as an answer, as well as some other answers.)

Example 2:
Input: stamp = "abca", target = "aabcaca"
Output: [3,0,1]

Note:

1 <= stamp.length <= target.length <= 1000
stamp and target only contain lowercase letters.

class Solution:
    def movesToStamp(self, stamp: str, target: str) -> List[int]:
        # work backward
        n_s, n_t = len(stamp), len(target)
        stamp, target = list(stamp), list(target)

        def check(idx):
            match = False
            for j in range(n_s):
                if target[idx+j] == '?':
                    continue
                if target[idx+j] != stamp[j]:
                    return False
                match = True
            if match:
                target[idx:idx+n_s] = ['?'] * n_s
                res.append(idx)
            return match

        changed = True
        res = []
        while changed:
            changed = False
            for idx in range(n_t - n_s + 1):
                changed = changed or check(idx)

        return res[::-1] if target == ['?'] * n_t else []


Solve in Python:
You want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the i-th job, you have to finish all the jobs j where 0 <= j < i).
You have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the d days. The difficulty of a day is the maximum difficulty of a job done in that day.
Given an array of integers jobDifficulty and an integer d. The difficulty of the i-th job is jobDifficulty[i].
Return the minimum difficulty of a job schedule. If you cannot find a schedule for the jobs return -1.

Example 1:

Input: jobDifficulty = [6,5,4,3,2,1], d = 2
Output: 7
Explanation: First day you can finish the first 5 jobs, total difficulty = 6.
Second day you can finish the last job, total difficulty = 1.
The difficulty of the schedule = 6 + 1 = 7

Example 2:
Input: jobDifficulty = [9,9,9], d = 4
Output: -1
Explanation: If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs.

Example 3:
Input: jobDifficulty = [1,1,1], d = 3
Output: 3
Explanation: The schedule is one job per day. total difficulty will be 3.

Example 4:
Input: jobDifficulty = [7,1,7,1,7,1], d = 3
Output: 15

Example 5:
Input: jobDifficulty = [11,111,22,222,33,333,44,444], d = 6
Output: 843

Constraints:

1 <= jobDifficulty.length <= 300
0 <= jobDifficulty[i] <= 1000
1 <= d <= 10

class Solution:
    def minDifficulty(self, jobDifficulty: List[int], d: int) -> int:
        jD=jobDifficulty
        day=d
        self.memo = {}
        def dp(i,day):
            if (i,day) not in self.memo:
                if i < day: self.memo[(i,day)] = float('inf')
                elif day == 1: self.memo[(i,day)] = max(jD[:i])
                elif i == day: self.memo[(i,day)] = sum(jD[:i])
                else:
                    tmp = jD[i-1]
                    self.memo[(i,day)] = dp(i-1,day-1) + tmp
                    for j in range(i-1,day-3,-1):
                        tmp = max(jD[j-1],tmp)
                        self.memo[(i,day)] = min(self.memo[(i,day)],dp(j,day-1) + tmp)
            return self.memo[(i,day)]
        ans = dp(len(jD),d)
        return ans if ans!= float('inf') else -1


Solve in Python:
You were given a string of integer temperature values. Create a function `close_to_zero(t)` and return the closest value to 0 or `0` if the string is empty. If two numbers are equally close to zero, return the positive integer.

def close_to_zero(t):
    t = [int(x) for x in t.split()]
    return min(t or [0],key=lambda t:(abs(t),-t))


Solve in Python:
You were given a string of integer temperature values. Create a function `lowest_temp(t)` and return the lowest value or `None/null/Nothing` if the string is empty.

def lowest_temp(t):
    if t == '':
        return None
    t = t.split()
    low = int(t[0])
    for i in t:
        if  int(i) < low:
            low = int(i)
    return low


Solve in Python:
You were strolling outside the restaurant at the end of the universe. On a metaspiral path you stumble upon a weird device which takes a three-digit number as input and processes it. The Hitchhiker's guide to the galaxy explains that it processes the input in the following manner:
- Multiplies it with 13, followed by 11 and then 7
- Outputs all the distinct three-digit numbers possible from the digits of the new number (each digit can only be used once)
Your friend Zaphod is in a playful mood, and does the following with the device-
- Given a three-digit positive number $K$, he feeds it to the device for processing.
- He then takes the numbers it gives as output, and send each of them through the device and again collect all the numbers sent out.
- Repeats the above step $N$ times.
To test your wit, he challenges you to find the number of distinct 3-digit numbers which the device outputs over the $N$ steps. Can you?

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

-----Output:-----
For each testcase, output a single integer denoting the number of distinct 3-digit numbers which the device outputs over the $N$ steps.

-----Constraints-----
- $1 \leq T \leq 1000$
- $5 \leq N \leq 10^9$
- Each digit of $K$ is non-zero

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

123 5

-----Sample Output:-----
27

from math import *
for _ in range(int(input())):
 k,n = map(str, input().split())
 n = int(n)
 p = len(set(list(k)))
 if p == 1:
  print(1)
 else:
  p = p**3
  x = 1
  y = 1
  flag = 0
  for i in range(n):
   if x > p:
    flag = 1
    break
   x += (y*2)
   y *= 2
  if flag == 0:
   print(x-y)
  else:
   print(p)


Solve in Python:
You will be given a certain array of length ```n```, such that ```n > 4```, having positive and negative integers but there will be no zeroes and all the elements will occur once in it.

We may obtain an amount of ```n``` sub-arrays of length ```n - 1```, removing one element at a time (from left to right).

For each subarray, let's calculate the product and sum of its elements with the corresponding absolute value of the quotient, ```q = SubProduct/SubSum``` (if it is possible, SubSum cannot be 0).
Then we select the array with the lowest value of ```|q|```(absolute value)

e.g.: we have the array, ```arr = [1, 23, 2, -8, 5]```
```
Sub Arrays            SubSum    SubProduct         |q|
[23, 2, -8, 5]         22         -1840         83.636363
[1, 2, -8, 5]           0           -80          No value
[1, 23, -8, 5]         21          -920         43.809524
[1, 23, 2, 5]          31           230          7.419355  <--- selected array
[1, 23, 2, -8]         18           368         20.444444
```
Let's compare the given array with the selected subarray:
```
[1, 23, 2, -8, 5]
[1, 23, 2,     5]
```
The difference between them is at the index ```3``` for the given array, with element ```-8```, so we put both things for a result ```[3, -8]```.

That means that to obtain the selected subarray we have to take out the value -8 at index 3.
We need a function that receives an array as an argument and outputs the the pair ```[index, arr[index]]``` that generates the subarray with  the lowest value of ```|q|```.

```python
select_subarray([1, 23, 2, -8, 5]) == [3, -8]
```
Another case:
```python
select_subarray([1, 3, 23, 4, 2, -8, 5, 18]) == [2, 23]
```
In Javascript the function will be ```selectSubarray()```.

We may have some special arrays that may have more than one solution as the one that follows below.
```python
select_subarray([10, 20, -30, 100, 200]) == [[3, 100], [4, 200]]
```
If there is more than one result the function should output a 2Darray sorted by the index of the element removed from the...

from operator import mul
from functools import reduce
def select_subarray(array):
    l = []
    for i in array:
        arr = [j for j in array if j != i]
        if sum(arr):
            l.append(((abs(reduce(mul, arr)/float(sum(arr)))), array.index(i), i))
    c = [[j, k] for i, j, k in l if i == sorted(l)[0][0]]
    return c[0] if len(c) == 1 else c


Solve in Python:
You will be given a fruit which a farmer has harvested, your job is to see if you should buy or sell.

You will be given 3 pairs of fruit. Your task is to trade your harvested fruit back into your harvested fruit via the intermediate pair, you should return a string of 3 actions.

if you have harvested apples, you would buy this fruit pair: apple_orange, if you have harvested oranges, you would sell that fruit pair.

(In other words, to go from left to right (apples to oranges) you buy, and to go from right to left you sell (oranges to apple))

e.g.
apple_orange, orange_pear, apple_pear
1. if you have harvested apples, you would buy this fruit pair: apple_orange
2. Then you have oranges, so again you would buy this fruit pair: orange_pear
3. After you have pear, but now this time you would sell this fruit pair: apple_pear
4. Finally you are back with the apples

So your function would return a list: [“buy”,”buy”,”sell”]

If any invalid input is given, "ERROR" should be returned

def buy_or_sell(pairs, fruit):
    res = []
    for b, s in pairs:
        if fruit == b:
            fruit = s
            res.append("buy")
        elif fruit == s:
            fruit = b
            res.append("sell")
        else:
            return "ERROR"
    return res


Solve in Python:
You will be given a string (x) featuring a cat 'C' and a mouse 'm'. The rest of the string will be made up of '.'.

You need to find out if the cat can catch the mouse from it's current position. The cat can jump over three characters. So:

C.....m returns 'Escaped!'  <-- more than three characters between

C...m returns 'Caught!'   <-- as there are three characters between the two, the cat can jump.

def cat_mouse(x):
    if len(x) > 5:
        return "Escaped!"
    else:
        return "Caught!"


Solve in Python:
You will be given a string (x) featuring a cat 'C', a dog 'D' and a mouse 'm'. The rest of the string will be made up of '.'.

You need to find out if the cat can catch the mouse from it's current position. The cat can jump (j) characters.

Also, the cat cannot jump over the dog.

So:

if j = 5:

```..C.....m.``` returns 'Caught!'  <-- not more than j characters between

```.....C............m......``` returns 'Escaped!'  <-- as there are more than j characters between the two, the cat can't jump far enough

if j = 10:

```...m.........C...D``` returns 'Caught!' <--Cat can jump far enough and jump is not over dog

```...m....D....C.......``` returns 'Protected!' <-- Cat can jump far enough, but dog is in the way, protecting the mouse

Finally, if all three animals are not present, return 'boring without all three'

def cat_mouse(x,j):
    if not all(('C' in x, 'D' in x, 'm' in x)):
        return "boring without all three"
    cat, dog, mouse = x.index('C'), x.index('D'), x.index('m')
    zone = [x[cat:mouse],x[mouse+1:cat]][mouse<cat]
    return { (1,0):"Caught!",
             (1,1):"Protected!" }.get( (len(zone)<=j,'D' in zone),"Escaped!")


Solve in Python:
You will be given a string and you task is to check if it is possible to convert that string into a palindrome by removing a single character. If the string is already a palindrome, return `"OK"`. If it is not, and we can convert it to a palindrome by removing one character, then return `"remove one"`, otherwise return `"not possible"`. The order of the characters should not be changed.

For example:
```Haskell
solve("abba") = "OK". -- This is a palindrome
solve("abbaa") = "remove one". -- remove the 'a' at the extreme right.
solve("abbaab") = "not possible".
```

More examples in the test cases.

Good luck!

If you like this Kata, please try [Single Character Palindromes II](https://www.codewars.com/kata/5a66ea69e6be38219f000110)

def solve(s):
    isOK = lambda x: x == x[::-1]

    return ("OK" if isOK(s)  else
            "remove one" if any( isOK(s[:i]+s[i+1:]) for i in range(len(s)) ) else
            "not possible")


Solve in Python:
You will be given a string.

You need to return an array of three strings by gradually pulling apart the string.

You should repeat the following steps until the string length is 1:

a) remove the final character from the original string, add to solution string 1.
b) remove the first character from the original string, add to solution string 2.

The final solution string value is made up of the remaining character from the original string, once originalstring.length == 1.

Example:

"exampletesthere"
becomes:
["erehtse","example","t"]

The Kata title gives a hint of one technique to solve.

def pop_shift(stg):
    d, m = divmod(len(stg), 2)
    return [stg[:d+m-1:-1], stg[:d], stg[d] if m else ""]


Solve in Python:
You will be given a two-dimensional array with row consisting values 0 or 1.
A move consists of choosing any column or row, and toggling all the 0’s as 1’s and 1’s as 0’s.
After making the required moves, every row represents a binary number and the score of the matrix will be sum of all the numbers represented as binary numbers in each row.
Find the highest possible score.
$Example:$
Input:

0 0 1 1

1 0 1 0

1 1 0 0
Output:

39
Explanation:

Toggled to

1 1 1 1

1 0 0 1

1 1 1 1
0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39

-----Input:-----
- First line will contains $m$, $n$ for the size of the 2-D array.
- Contains $m$ lines of $n$ space-separated values each.

-----Output:-----
Single integer which is the maximum score obtained by the sum of binary numbers.

-----Constraints-----
- $1 \leq m, n \leq 20$
- $A[i][j] = 1$ or $0$

-----Sample Input:-----
3 4
0 0 1 1
1 0 1 0
1 1 0 0

-----Sample Output:-----
39

def matrixScore(A):
        """
        :type A: List[List[int]]
        :rtype: int
        """
        m,n = len(A),len(A[0])
        # 行变换
        for i in range(m):
            if A[i][0] == 1: continue
            for j in range(n):
                A[i][j] = 1 - A[i][j]

        # 列变换
        res = 0
        for rows in zip(*A):
         # 始终使1的个数是更大的
            cnt1 = max(rows.count(1), rows.count(0))
            res += cnt1 * 2**(n-1)
            n -= 1
        return res
m, n = [int(s) for s in input().split(" ")]
arr = [[int(s) for s in input().split(" ")] for i in range(m)]
ans = matrixScore(arr)
print(ans)


Solve in Python:
You will be given a vector of strings. You must sort it alphabetically (case-sensitive, and based on the ASCII values of the chars) and then return the first value.

The returned value must be a string, and have `"***"` between each of its letters.

You should not remove or add elements from/to the array.

def two_sort(array):
    array = sorted(array)
    return ('***').join(x[0] for x in array[0])


Solve in Python:
You will be given an array `a` and a value `x`. All you need to do is check whether the provided array contains the value.

~~~if:swift
The type of `a` and `x` can be `String` or `Int`.
~~~
~~~if-not:swift
Array can contain numbers or strings. X can be either.
~~~
~~~if:racket
In racket, you'll be given a list instead of an array. If the value is in the list,
return #t instead of another value that is also considered true.
```racket
(contains '(1 2 3) 3) ; returns #t
(contains '(1 2 3) 5) ; returns #f
```
~~~

Return `true` if the array contains the value, `false` if not.

def check(seq, elem):
    total = 0
    print(len(seq))
    for i in seq:
        if i == elem:
            return True
        else:
            total += 1
            if total == len(seq):
                return False


Solve in Python:
You will be given an array of non-negative integers and positive integer bin width.

Your task is to create the Histogram method that will return histogram data corresponding to the input array. The histogram data is an array that stores under index i the count of numbers that belong to bin i. The first bin always starts with zero.

On empty input you should return empty output.

Examples:

For input data [1, 1, 0, 1, 3, 2, 6] and binWidth=1 the result will be [1, 3, 1, 1, 0, 0, 1] as the data contains single element "0", 3 elements "1" etc.
For the same data and binWidth=2 the result will be [4, 2, 0, 1]
For input data [7] and binWidth=1 the result will be [0, 0, 0, 0, 0, 0, 0, 1]

from itertools import groupby
def histogram(values, bin_width):
    c={k:len(list(g)) for k,g in groupby(sorted(values),key=lambda x:x//bin_width)}
    return [c.get(i,0) for i in range(max(c)+1)] if c else []


Solve in Python:
You will be given an array of numbers.

For each number in the array you will need to create an object.

The object key will be the number, as a string. The value will be the corresponding character code, as a string.

Return an array of the resulting objects.

All inputs will be arrays of numbers. All character codes are valid lower case letters. The input array will not be empty.

def num_obj(s):
    objects = []
    for i in s:
        objects.append( {str(i):chr(i)} )
    return objects


Solve in Python:
You will be given an array of positive integers. The array should be sorted by the amount of distinct perfect squares and reversed, that can be generated from each number permuting its digits.

E.g.: ```arr = [715, 112, 136, 169, 144]```
```
Number   Perfect Squares w/ its Digits   Amount
 715                -                       0
 112               121                      1
 136               361                      1
 169           169, 196, 961                3
 144             144, 441                   2
```
So the output will have the following order:
```[169, 144, 112, 136, 715]```

When we have two or more numbers with the same amount of perfect squares in their permutations, we sorted by their values.

In the example given above, we can see that 112 and 136 both generate a perfect square. So 112 comes first.

Examples for this kata:
```python
sort_by_perfsq([715, 112, 136, 169, 144]) == [169, 144, 112, 136, 715]
# number of perfect squares:                   3    2    1    1    0
```
We may have in the array numbers that belongs to the same set of permutations.
```python
sort_by_perfsq([234, 61, 16, 441, 144, 728]) == [144, 441, 16, 61, 234, 728]
# number of perfect squares:                      2    2    1   0   0    0
```

Features of the random tests:
~~~if:ruby,python
- Number of tests: 80
- Arrays between 4 and 20 elements
- Integers having from 1 to 7 digits included
~~~
~~~if:js
- Number of tests: 30
- Arrays between 4 and 16 elements
- Integers having from 1 to 7 digits included
~~~

Enjoy it!!

def sort_by_perfsq(arr):

    def get_pos_nums(digs, currn=''):
        if len(digs) == 1:
            nums.append(currn + digs[0])

        for d in digs:
            locd = digs[:]
            locd.remove(d)
            get_pos_nums(locd, currn + d)

    count_sq = []

    for x in arr:
        count_sq.append([x, 0])

        digs = [d for d in str(x)]
        nums = []
        get_pos_nums(digs)
        nums = set(map(int, nums))

        for n in nums:
            if n ** 0.5 % 1 == 0:
                count_sq[-1][1] += 1

    count_sq.sort()
    count_sq.sort(key=lambda num: num[1], reverse=True)
    return [num[0] for num in count_sq]


Solve in Python:
You will be given an array of strings. The words in the array should mesh together where one or more letters at the end of one word will have the same letters (in the same order) as the next word in the array. But, there are times when all the words won't mesh.

Examples of meshed words:

  "apply" and "plywood"

  "apple" and "each"

  "behemoth" and "mother"

Examples of words that don't mesh:

  "apply" and "playground"

  "apple" and "peggy"

  "behemoth" and "mathematics"

If all the words in the given array mesh together, then your code should return the meshed letters in a string.
You won't know how many letters the meshed words have in common, but it will be at least one.

If all the words don't mesh together, then your code should return `"failed to mesh"`.

Input: An array of strings. There will always be at least two words in the input array.

Output: Either a string of letters that mesh the words together or the string `"failed to mesh"`.

## Examples

#1:

```
["allow", "lowering", "ringmaster", "terror"] --> "lowringter"
```
because:

* the letters `"low"` in the first two words mesh together
* the letters `"ring"` in the second and third word mesh together
* the letters `"ter"` in the third and fourth words mesh together.

#2:

```
["kingdom", "dominator", "notorious", "usual", "allegory"] --> "failed to mesh"
```

Although the words `"dominator"` and `"notorious"` share letters in the same order, the last letters of the first word don't mesh with the first letters of the second word.

def word_mesh(lst):
    meshes = []
    for w1, w2 in zip(lst, lst[1:]):
        for i in range(min(len(w1), len(w2)), 0, -1):
            if w1[-i:] == w2[:i]:
                meshes.append(w1[-i:])
                break
        else:
            return "failed to mesh"
    return "".join(meshes)


Solve in Python:
You will be given an array that contains two strings. Your job is to create a function that will take those two strings and transpose them, so that the strings go from top to bottom instead of left to right.
A few things to note:

1. There should be one space in between the two characters
2. You don't have to modify the case (i.e. no need to change to upper or lower)
3. If one string is longer than the other, there should be a space where the character would be

from itertools import zip_longest

def transpose_two_strings(arr):
    return '\n'.join(map(' '.join, zip_longest(*arr, fillvalue=' ')))


Solve in Python:
You will be given an array which lists the current inventory of stock in your store and another array which lists the new inventory being delivered to your store today.

Your task is to write a function that returns the updated list of your current inventory **in alphabetical order**.

## Example

```python
cur_stock = [(25, 'HTC'), (1000, 'Nokia'), (50, 'Samsung'), (33, 'Sony'), (10, 'Apple')]
new_stock = [(5, 'LG'), (10, 'Sony'), (4, 'Samsung'), (5, 'Apple')]

update_inventory(cur_stock, new_stock)  ==>
[(15, 'Apple'), (25, 'HTC'), (5, 'LG'), (1000, 'Nokia'), (54, 'Samsung'), (43, 'Sony')]
```

___

*Kata inspired by the FreeCodeCamp's 'Inventory Update' algorithm.*

from collections import Counter

revertToDct = lambda lst: Counter(dict(x[::-1] for x in lst))

def update_inventory(*stocks):
    old,new = map(revertToDct,stocks)
    return [it[::-1] for it in sorted((old+new).items())]


Solve in Python:
You will be given m strings. For each of those strings, you need to count the total number of appearances of that string as substrings in all possible strings of length n containing only lower case English letters.

A string may appear in a string multiple times. Also, these appearances may overlap. All these must be counted separately. For example, aa appears thrice in the string aaacaa: aaacaa, aaacaa and aaacaa.

-----Input-----
- The first line contains one integer, T, the number of test cases. The description of each test case follows:
- The first line of each test case will contain two integers n and m.
- The ith of the next m lines will have one string in each line. All the strings will consist only of lower case English letters.

-----Output-----
- For each test case, print "Case x:" (without quotes. x is the test case number, 1-indexed) in the first line.
- Then print m lines. The ith line should contain the number of appearances of the ith string in all possible strings of length n. As the numbers can be very large, print the answers modulo 109+7.

-----Constraints-----
- 1 ≤ T ≤ 100
- 1 ≤ n ≤ 100000
- 1 ≤ m ≤ 1000
- 1 ≤ Length of every string in input
- 1 ≤ Total length of all strings in one test case ≤ 5 * 105
- 1 ≤ Total length of all strings in one test file ≤ 5 * 106

-----Example-----
Input:
3
2 1
aa
2 1
d
12 3
cdmn
qweewef
qs

Output:
Case 1:
1
Case 2:
52
Case 3:
443568031
71288256
41317270

-----Explanation:-----
Testcase 1: aa is the only string of length 2 which contains aa as a substring. And it occurs only once. Hence the answer is 1.

t = int(input())
for i in range(t):
  print('Case ', (i+1), ": ", sep='')
  inp = input().split()
  inp[0] = int(inp[0])
  inp[1] = int(inp[1])
  for j in range(inp[1]):
    length = len(input())
    if inp[0] == length:
      print("1")
    elif inp[0] < length:
      print("0")
    else:

      ans = ((inp[0]-length+1)*(pow(26,inp[0]-length,1000000007)))%1000000007
      print(ans)


Solve in Python:
You will be given the prime factors of a number as an array.
E.g: ```[2,2,2,3,3,5,5,13]```

You need to find the number, n, to which that prime factorization belongs.
It will be:
```
n = 2³.3².5².13 = 23400
```
Then, generate the divisors of this number.

Your function ```get_num() or getNum()``` will receive an array with potentially unordered prime factors and should output: an array with the found integer n at index 0, the amount of total divisors (both prime and compound numbers) at index 1, followed the smallest factor (index 2, and the biggest one (last element)

We will see the example given above with the only difference that the array of the prime factors is unordered.

The list of divisors for that number (23400) is:
```
2, 3, 4, 5, 6, 8, 9, 10, 12, 13, 15, 18, 20, 24, 25, 26, 30, 36, 39, 40, 45, 50, 52, 60, 65, 72, 75, 78, 90, 100, 104, 117, 120, 130, 150, 156, 180, 195, 200, 225, 234, 260, 300, 312, 325, 360, 390, 450, 468, 520, 585, 600, 650, 780, 900, 936, 975, 1170, 1300, 1560, 1800, 1950, 2340, 2600, 2925, 3900, 4680, 5850, 7800, 11700 (not considering the integer 23400 itself)
```
There is a total amount of ```71``` divisors. The smallest divisor is ```2``` and the highest ```11700```.
So the expected output will be:
```
get_num([2,13,2,5,2,5,3,3]) == [23400, 71, 2, 11700]
```
Enjoy!

from collections import Counter
from functools import reduce
from operator import mul

def get_num(arr):
    n, small = reduce(mul, arr), min(arr)
    count = reduce(mul, (v+1 for v in Counter(arr).values())) - 1
    return [n, count, small, n//small]


Solve in Python:
You will be given two ASCII strings, `a` and `b`. Your task is write a function to determine which one of these strings is "worth" more, and return it.

A string's worth is determined by the sum of its ASCII codepoint indexes. So, for example, the string `HELLO` has a value of 372: H is codepoint 72, E 69, L 76, and O is 79. The sum of these values is 372.

In the event of a tie, you should return the first string, i.e. `a`.

def highest_value(*args):
    return max(args, key=lambda s:sum(map(ord, s)))


Solve in Python:
You will be given two numbers `m,n`. The numbers could span from `0` to `10000`. We can get their product by using binary reduction as show in the table below.
Example (to understand the table please read the description below it)

real value of m(r)
m
n
(r*n)

0
100
15
0

0
50
30
0

1
25
60
60

0
12
120
0

0
6
240
0

1
3
480
480

1
1
960
960

Above, we are given two numbers `100` and `15`. we keep reducing the bigger number by dividing it by `2` and hold the integer part of the division till it is no more divisible by `2`. Then we assign the real values to these reduced parts of `m`. Any reduced number `[1,m]` has real value of `0` if it is even, and it will have real value of `1` if it is odd. On the other hand the smaller number in this case `n` keeps on doubling itself the same amount of times `m` reduces itself. The idea of this method is to change multiplication of two big number to a sequence of multiplication by `0` or `1` and perform addition to get the final product. You can see that from the last column `(r*n)` above.
if we sum the last column we get `0+60+0+0+480+960=1500=100*15`
Now your task for this kata will be to get those non-zero number in the last column in an array and return it sorted in descending order.so for the above example the return will be `[960,480,60]`.

_Beware: _`m,n`_ are not necessarily ordered._

def bin_mul(m,n):
    if m < n: return bin_mul(n,m)
    if n == 0: return[]
    r = []
    while m >= 1:
        print(m,n)
        if m % 2: r.append(1*n)
        m = m//2
        n = n*2

    return sorted(r,reverse=True)


Solve in Python:
You will be given two strings `a` and `b` consisting of lower case letters, but `a` will have at most one asterix character. The asterix (if any) can be replaced with an arbitrary sequence (possibly empty) of lowercase letters. No other character of string `a` can be replaced. If it is possible to replace the asterix in `a` to obtain string `b`, then string `b` matches the pattern.

If the string matches, return `true` else `false`.

```
For example:
solve("code*s","codewars") = true, because we can replace the asterix(*) with "war" to match the second string.
solve("codewar*s","codewars") = true, because we can replace the asterix(*) with "" to match the second string.
solve("codewars","codewars") = true, because the strings already match.
solve("a","b") = false
```
More examples in test cases.

Good luck!

import re
def solve(a,b):
    rx = '^' + '.*'.join(a.split('*')) + '$'
    return bool(re.search(rx,b))


Solve in Python:
You will get an array of numbers.

Every preceding number is smaller than the one following it.

Some numbers will be missing, for instance:
```
[-3,-2,1,5] //missing numbers are: -1,0,2,3,4
```
Your task is to return an array of those missing numbers:
```
[-1,0,2,3,4]
```

def find_missing_numbers(arr):
    return [n for n in range(arr[0], arr[-1]) if n not in arr] if arr else []


Solve in Python:
You will have a list of rationals in the form

```
lst = [ [numer_1, denom_1] , ... , [numer_n, denom_n] ]
```
or
```
lst = [ (numer_1, denom_1) , ... , (numer_n, denom_n) ]
```

where all numbers are positive integers. You have to produce their sum `N / D` in an irreducible form: this means that `N` and `D` have only `1` as a common divisor.

Return the result in the form:

- `[N, D]` in Ruby, Crystal, Python, Clojure, JS, CS, PHP, Julia
- `Just "N D"` in Haskell, PureScript
- `"[N, D]"` in Java, CSharp, TS, Scala, PowerShell, Kotlin
- `"N/D"` in Go, Nim
- `{N, D}` in C++, Elixir
- `{N, D}` in C
- `Some((N, D))` in Rust
- `Some "N D"` in F#, Ocaml
- `c(N, D)` in R
- `(N, D)` in Swift
- `'(N D)` in Racket

If the result is an integer (`D` evenly divides `N`) return:

- an integer in Ruby, Crystal, Elixir, Clojure, Python, JS, CS, PHP, R, Julia
- `Just "n"` (Haskell, PureScript)
- `"n"` Java, CSharp, TS, Scala, PowerShell, Go, Nim, Kotlin
- `{n, 1}` in C++
- `{n, 1}` in C
- `Some((n, 1))` in Rust
- `Some "n"` in F#, Ocaml,
- `(n, 1)` in Swift
- `n` in Racket

If the input list is empty, return

- `nil/None/null/Nothing`
- `{0, 1}` in C++
- `{0, 1}` in C
- `"0"` in Scala, PowerShell, Go, Nim
- `O` in Racket
- `""` in Kotlin

### Example:

```
[ [1, 2], [1, 3], [1, 4] ]  -->  [13, 12]

    1/2  +  1/3  +  1/4     =      13/12
```

### Note
See sample tests for more examples and the form of results.

from fractions import Fraction
def sum_fracts(lst):
    out = Fraction(0, 1)
    for x in lst: out = out + Fraction(x[0], x[1])
    return None if out.numerator == 0 else out.numerator if out.denominator == 1 else [out.numerator, out.denominator]


Solve in Python:
You will receive an uncertain amount of integers in a certain order ```k1, k2, ..., kn```.

You form a new number of n digits in the following way:
you take one of the possible digits of the first given number, ```k1```, then the same with the given number ```k2```, repeating the same process up to ```kn``` and you concatenate these obtained digits(in the order that were taken) obtaining the new number. As you can see, we have many possibilities.

Let's see the process above explained with three given numbers:
```
k1 = 23, k2 = 17, k3 = 89
Digits Combinations   Obtained Number
  ('2', '1', '8')           218    <---- Minimum
  ('2', '1', '9')           219
  ('2', '7', '8')           278
  ('2', '7', '9')           279
  ('3', '1', '8')           318
  ('3', '1', '9')           319
  ('3', '7', '8')           378
  ('3', '7', '9')           379    <---- Maximum
             Total Sum =   2388   (8 different values)
```
We need the function that may work in this way:

```python
proc_seq(23, 17, 89) == [8, 218, 379, 2388]
```

See this special case and deduce how the function should handle the cases which have many repetitions.

```python
proc_seq(22, 22, 22, 22) == [1, 2222] # we have only one obtained number, the minimum, maximum and total sum coincide
```

The sequence of numbers will have numbers of n digits only. Numbers formed by leading zeroes will be discarded.

```python
proc_seq(230, 15, 8) == [4, 218, 358, 1152]
```

Enjoy it!!

You will never receive the number 0 and all the numbers will be in valid format.

from functools import reduce
def prod(arr):
    return reduce(lambda x,y:x*y, arr)

def proc_seq(*args):
    args = [set(str(n)) for n in args]
    args[0] -= {'0'}
    minimum = int("".join(min(n) for n in args))
    maximum = int("".join(max(n) for n in args))
    total = get_total(args)
    number = prod(len(arg) for arg in args)

    return [number, minimum, maximum, total] if number > 1 else [1, minimum]

def get_total(args):
    total = 0
    args = args[::-1]
    for i, arg in enumerate(args):
        total += 10 ** i * sum(map(int, arg)) * prod(len(x) for x in args[:i] + args[i+1:])
    return total


Solve in Python:
You work in a big office. It is a 9 floor building with an elevator that can accommodate up to 4 people. It is your responsibility to manage this elevator.

Today you are late, so there are queues on some floors already. For each person you know the floor where he currently is and the floor he wants to reach. Also, you know the order in which people came to the elevator.

According to the company's rules, if an employee comes to the elevator earlier than another one, he has to enter the elevator earlier too (even if these employees stay on different floors). Note that the employees are allowed to leave the elevator in arbitrary order.

The elevator has two commands:   Go up or down one floor. The movement takes 1 second.  Open the doors on the current floor. During this operation all the employees who have reached their destination get out of the elevator. Then all the employees on the floor get in the elevator in the order they are queued up while it doesn't contradict the company's rules and there is enough space in the elevator. Each employee spends 1 second to get inside and outside the elevator.

Initially the elevator is empty and is located on the floor 1.

You are interested what is the minimum possible time you need to spend to deliver all the employees to their destination. It is not necessary to return the elevator to the floor 1.

-----Input-----

The first line contains an integer n (1 ≤ n ≤ 2000) — the number of employees.

The i-th of the next n lines contains two integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ 9, a_{i} ≠ b_{i}) — the floor on which an employee initially is, and the floor he wants to reach.

The employees are given in the order they came to the elevator.

-----Output-----

Print a single integer — the minimal possible time in seconds.

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

Output
10
Input
2
5 3
3 5

Output
12

-----Note-----

 Explaination for the first sample [Image] t = 0

[Image] t = 2

[Image] t = 3

[Image] t = 5

[Image] t = 6

[Image] t = 7

[Image] t = 9

[Image] t = 10

# python3
import sys
from collections import namedtuple

def readline(): return list(map(int, input().split()))

def readlines():
    for line in sys.stdin.readlines():
        yield list(map(int, line.split()))

class State(namedtuple('State', 'payload time floor')):
    def hook(self, pivot, a, b):
        lo, up = min(pivot, a, self.floor), max(pivot, a, self.floor)
        return tuple(x for x in self.payload if x < lo or up < x) + (b,), \
            self.time + abs(self.floor - pivot) + abs(pivot - a)

    def choices_to_take_next(self, a, b):
        floor = self.floor

        payload, time = self.hook(floor, a, b)
        if len(payload) < 5:
            yield payload, time
            if floor > a:
                pivots = (x for x in self.payload if x > floor)
            elif floor == a:
                pivots = ()
            else:
                pivots = (x for x in self.payload if x < floor)
        else:
            pivots = self.payload

        for pivot in pivots:
            yield self.hook(pivot, a, b)

def time_to_get_free(payload, floor):
    if payload:
        lo, up = min(payload), max(payload)
        return abs(lo-up) + min(abs(floor-lo), abs(floor-up))
    else:
        return 0

def main():
    n, = readline()

    floor = 1
    positions = {(): 0}  # empty elevator, time = 0
    for (a, b) in readlines():
        max_acceptable_time = min(positions.values()) + 16 - abs(floor - a)

        new_positions = dict()
        for payload, time in list(positions.items()):
            state = State(payload, time, floor)
            for npayload, ntime in state.choices_to_take_next(a, b):
                if ntime <= max_acceptable_time:
                    npayload = tuple(sorted(npayload))
                    if new_positions.setdefault(npayload, ntime) > ntime:
                        new_positions[npayload] = ntime

        positions = new_positions
        floor = a

    return min(t + time_to_get_free(p, floor) for p, t in list(positions.items())) \
        + 2 * n

print(main())


Solve in Python:
You work in the best consumer electronics corporation, and your boss wants to find out which three products generate the most revenue.
Given 3 lists of the same length like these:

* products: `["Computer", "Cell Phones", "Vacuum Cleaner"]`
* amounts: `[3, 24, 8]`
* prices: `[199, 299, 399]`

return the three product names with the highest revenue (`amount * price`).

**Note**: if multiple products have the same revenue, order them according to their original positions in the input list.

def top3(products, amounts, prices):
    catalog = {n:amounts[i] * prices[i] for i,n in enumerate(products)}
    return sorted(catalog, key=catalog.get, reverse=True)[:3]


Solve in Python:
You would like to get the 'weight' of a name by getting the sum of the ascii values. However you believe that capital letters should be worth more than mere lowercase letters. Spaces, numbers, or any other character are worth 0.

Normally in ascii

    a has a value of 97
    A has a value of 65
    ' ' has a value of 32
    0 has a value of 48

To find who has the 'weightier' name you will switch all the values so:

    A will be 97
    a will be 65
    ' ' will be 0
    0 will be 0
    etc...

For example Joe will have a weight of 254, instead of 286 using normal ascii values.


Solve in Python:
You wrote all your unit test names in camelCase.
But some of your colleagues have troubles reading these long test names.
So you make a compromise to switch to underscore separation.

To make these changes fast you wrote a class to translate a camelCase name
into an underscore separated name.

Implement the ToUnderscore() method.

Example:

`"ThisIsAUnitTest" => "This_Is_A_Unit_Test"`

**But of course there are always special cases...**

You also have some calculation tests. Make sure the results don't get split by underscores.
So only add an underscore in front of the first number.

Also Some people already used underscore names in their tests. You don't want to change them.
But if they are not split correct you should adjust them.

Some of your colleagues mark their tests with a leading and trailing underscore.
Don't remove this.

And of course you should handle empty strings to avoid unnecessary errors. Just return an empty string then.

Example:

`"Calculate15Plus5Equals20" => "Calculate_15_Plus_5_Equals_20"`

`"This_Is_Already_Split_Correct" => "This_Is_Already_Split_Correct"`

`"ThisIs_Not_SplitCorrect" => "This_Is_Not_Split_Correct"`

`"_UnderscoreMarked_Test_Name_" => _Underscore_Marked_Test_Name_"`


Solve in Python:
You'll be given a list of two strings, and each will contain exactly one colon (`":"`) in the middle (but not at beginning or end). The length of the strings, before and after the colon, are random.

Your job is to return a list of two strings (in the same order as the original list), but with the characters after each colon swapped.

## Examples
```
["abc:123", "cde:456"]  -->  ["abc:456", "cde:123"]
["a:12345", "777:xyz"]  -->  ["a:xyz", "777:12345"]
```

def tail_swap(arr):
    fmt = '{}:{}'.format
    (head, tail), (head_2, tail_2) = (a.split(':') for a in arr)
    return [fmt(head, tail_2), fmt(head_2, tail)]


Solve in Python:
You'll be given a string of random characters (numbers, letters, and symbols). To decode this string into the key we're searching for:

(1) count the number occurences of each ascii lowercase letter, and

(2) return an ordered string, 26 places long, corresponding to the number of occurences for each corresponding letter in the alphabet.

For example:
```python
'$aaaa#bbb*cc^fff!z' gives '43200300000000000000000001'
   ^    ^   ^  ^  ^         ^^^  ^                   ^
  [4]  [3] [2][3][1]        abc  f                   z

'z$aaa#ccc%eee1234567890' gives '30303000000000000000000001'
 ^  ^   ^   ^                    ^ ^ ^                    ^
[1][3] [3] [3]                   a c e                    z
```
Remember, the string returned should always be 26 characters long, and only count lowercase letters.

Note: You can assume that each lowercase letter will appears a maximum of 9 times in the input string.

decrypt=lambda s:''.join(str(s.count(chr(c)))for c in range(97,123))


Solve in Python:
You'll be given a string, and have to return the total of all the unicode characters as an int. Should be able to handle any characters sent at it.

examples:

uniTotal("a") == 97
uniTotal("aaa") == 291

def uni_total(string):
    res = 0

    for let in string:
        res += ord(let)

    return res


Solve in Python:
You're a buyer/seller and your buisness is at stake... You ___need___ to make profit... Or at least, you need to lose the least amount of money!
Knowing a list of prices for buy/sell operations, you need to pick two of them. Buy/sell market is evolving across time and the list represent this evolution. First, you need to buy one item, then sell it later. Find the best profit you can do.

### Example:

Given an array of prices `[3, 10, 8, 4]`, the best profit you could make would be `7` because you buy at `3` first, then sell at `10`.

# Input:

A list of prices (integers), of length 2 or more.

# Output:

The result of the best buy/sell operation, as an integer.

### Note:
Be aware you'll face lists with several thousands of elements, so think about performance.

import numpy as np

def max_profit(prices):
    p = np.array(prices)
    return np.array([p[i+1:].max() - prices[i] for i in range(len(prices)-1)]).max()


Solve in Python:
You're a programmer in a SEO company. The SEO specialist of your company gets the list of all project keywords everyday, then he looks for the longest keys to analyze them.

You will get the list with keywords and must write a simple function that returns the biggest search keywords and sorts them in lexicographical order.

For instance you might get:
```python
'key1', 'key2', 'key3', 'key n', 'bigkey2', 'bigkey1'
```

And your function should return:
```python
"'bigkey1', 'bigkey2'"
```

Don't forget to rate this kata! Thanks :)

def the_biggest_search_keys(*arg):
    mx = len(max(arg, key=len, default = ''))
    return ", ".join(sorted( f"'{e}'" for e in list(arg)+[''] if len(e) == mx))


Solve in Python:
You're a statistics professor and the deadline for submitting your students' grades is tonight at midnight. Each student's grade is determined by their mean score across all of the tests they took this semester.

You've decided to automate grade calculation by writing a function `calculate_grade()` that takes a list of test scores as an argument and returns a one character string representing the student's grade calculated as follows:

 * 90% <= mean score <= 100%: `"A"`,
 * 80% <= mean score < 90%: `"B"`,
 * 70% <= mean score < 80%: `"C"`,
 * 60% <= mean score < 70%: `"D"`,
 * mean score < 60%: `"F"`

For example, `calculate_grade([92, 94, 99])` would return `"A"` since the mean score is `95`, and `calculate_grade([50, 60, 70, 80, 90])` would return `"C"` since the mean score is `70`.

Your function should handle an input list of any length greater than zero.

from bisect import bisect
from statistics import mean

def calculate_grade(scores):
    return 'FDCBA'[bisect([60, 70, 80, 90], mean(scores))]


Solve in Python:
You're about to go on a trip around the world! On this trip you're bringing your trusted backpack, that anything fits into. The bad news is that the airline has informed you, that your luggage cannot exceed a certain amount of weight.

To make sure you're bringing your most valuable items on this journey you've decided to give all your items a score that represents how valuable this item is to you. It's your job to pack you bag so that you get the most value out of the items that you decide to bring.

Your input will consist of two arrays, one for the scores and one for the weights. You input will always be valid lists of equal length, so you don't have to worry about verifying your input.

You'll also be given a maximum weight. This is the weight that your backpack cannot exceed.

For instance, given these inputs:

    scores = [15, 10, 9, 5]
    weights = [1, 5, 3, 4]
    capacity = 8

The maximum score will be ``29``. This number comes from bringing items ``1, 3 and 4``.

Note: Your solution will have to be efficient as the running time of your algorithm will be put to a test.

def pack_bagpack(scores, weights, capacity):
    loads = [0] * (capacity + 1)
    for score, weight in zip(scores, weights):
        loads = [max(l, weight <= w and loads[w - weight] + score) for w, l in enumerate(loads)]
    return loads[-1]


Solve in Python:
You're continuing to enjoy your new piano, as described in Piano Kata, Part 1. You're also continuing the exercise where you start on the very first (leftmost, lowest in pitch) key on the 88-key keyboard, which (as shown below) is the note A, with the little finger on your left hand, then the second key, which is the black key A# ("A sharp"), with your left ring finger, then the third key, B, with your left middle finger, then the fourth key, C, with your left index finger, and then the fifth key, C#, with your left thumb. Then you play the sixth key, D, with your right thumb, and continue on playing the seventh, eighth, ninth, and tenth keys with the other four fingers of your right hand. Then for the eleventh key you go back to your left little finger, and so on. Once you get to the rightmost/highest, 88th, key, C, you start all over again with your left little finger on the first key.

(If the Codewars Instructions pane resizes the above piano keyboard image to be too small to read the note labels of the black/sharp keys on your screen, click here to open a copy of the image in a new tab or window.)

This time, in addition to counting each key press out loud (not starting again at 1 after 88, but continuing on to 89 and so forth) to try to keep a steady rhythm going and to see how far you can get before messing up, you're also saying the name of each note. You wonder whether this may help you develop perfect pitch in addition to learning to just *know* which note is which, and -- as in Piano Kata, Part 1 -- helping you to learn to move smoothly and with uniform pressure on the keys from each finger to the next and back and forth between hands.

The function you are going to write will explore one of the patterns you're experiencing in your practice: Given the number you stopped on, which note was it? For example, in the description of your piano exercise above, if you stopped at 5, your left thumb would be on the fifth key of the piano, which is C#. Or if you stopped at 92, you would have gone all the...


Solve in Python:
You're familiar with [list slicing](https://docs.python.org/3/library/functions.html#slice) in Python and know, for example, that:

```python
>>> ages = [12, 14, 63, 72, 55, 24]
>>> ages[2:4]
[63, 72]
>>> ages[2:]
[63, 72, 55, 24]
>>> ages[:3]
[12, 14, 63]
```

write a function `inverse_slice()` that takes three arguments: a list `items`, an integer `a` and an integer `b`. The function should return a new list with the slice specified by `items[a:b]` _excluded_. For example:

```python
>>>inverse_slice([12, 14, 63, 72, 55, 24], 2, 4)
[12, 14, 55, 24]
```

The input will always be a valid list, `a` and `b` will always be different integers equal to or greater than zero, but they _may_ be zero or be larger than the length of the list.

def inverse_slice(items, a, b):
  return [v for i,v in enumerate(items) if i < a or i >= b]