Solve in Python:
A factorial (of a large number) will usually contain some trailing zeros.
Your job is to make a function that calculates the number of trailing zeros, in any given base.

Factorial is defined like this:
```n! = 1 * 2 * 3 * 4 * ... * n-2 * n-1 * n```

Here's two examples to get you started:

```python
trailing_zeros(15, 10) == 3
#15! = 1307674368000, which has 3 zeros at the end

trailing_zeros(7, 2) == 4
#7! = 5030 = 0b1001110110000, which has 4 zeros at the end
```

Your code should be able to handle some very large numbers, so write some smart code.

Note: ```num``` will be a non-negative integer, ```base``` will be an integer larger or equal to two.

HINT: Should you not make any headway after trying a long time, you should try [this kata](https://www.codewars.com/kata/number-of-trailing-zeros-of-n) first.

f = lambda n, p: 0 if n < p else n//p + f(n//p, p)

def factors(n):
    p = 2
    while p*p <= n:
        cnt = 0
        while n % p == 0:
            cnt += 1
            n //= p
        yield p, cnt
        p += 1
    if n != 1:
        yield n, 1

def trailing_zeros(number, base):
    return min(f(number, num) // cnt for num, cnt in factors(base) if cnt != 0)


Solve in Python:
A family of kookaburras are in my backyard.

I can't see them all, but I can hear them!

# How many kookaburras are there?

## Hint

The trick to counting kookaburras is to listen carefully

* The males go ```HaHaHa```...

* The females go ```hahaha```...

* And they always alternate male/female

^ Kata Note : No validation is necessary; only valid input will be passed :-)

import re

def kooka_counter(laughing):
    return len(re.findall(r'(ha)+|(Ha)+',laughing))


Solve in Python:
A famous casino is suddenly faced with a sharp decline of their revenues. They decide to offer Texas hold'em also online. Can you help them by writing an algorithm that can rank poker hands?

## Task

Create a poker hand that has a method to compare itself to another poker hand:

```python
compare_with(self, other_hand)
```

A poker hand has a constructor that accepts a string containing 5 cards:
```python
PokerHand("KS 2H 5C JD TD")
```

The characteristics of the string of cards are:
* Each card consists of two characters, where
 * The first character is the value of the card: `2, 3, 4, 5, 6, 7, 8, 9, T(en), J(ack), Q(ueen), K(ing), A(ce)`
 * The second character represents the suit: `S(pades), H(earts), D(iamonds), C(lubs)`
* A space is used as card separator between cards

The result of your poker hand compare can be one of these 3 options:

```python
[ "Win", "Tie", "Loss" ]
```

## Notes
* Apply the [Texas Hold'em](https://en.wikipedia.org/wiki/Texas_hold_%27em) rules for ranking the cards.
* Low aces are **NOT** valid in this kata.
* There is no ranking for the suits.

If you finished this kata, you might want to continue with [Sortable Poker Hands](https://www.codewars.com/kata/sortable-poker-hands)

class PokerHand(object):

    def __init__(self, hand):
        self.st = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A']
        self.h = sorted(hand.split(), key=lambda x: self.st.index(x[0]))
        self.v=lambda i,j :"Win" if self.st.index(i) > self.st.index(j) else 'Loss'

    def compare_with(self, o):
        o = sorted(o.h, key=lambda x: self.st.index(x[0]))
        if o == self.h : return 'Tie'
        s,s1 = [i[0] for i in o],[i[0] for i in self.h]
        a = [self.straight_flush, self.four_of_kind, self.full_house, self.flush, self.straight, self.three_of_kind,self.two_pair, self.one_pair]
        b = [0, 1, 2, self.flush_, self.straight_,5,6, 7]
        for u, j in enumerate(zip(a, b)):
            k,l = j[0],j[1]
            i,j = k(self.h),k(o)
            if i != j : return 'Win' if i else 'Loss'
            elif i == j == 1 :
                if u in [3,4] : return l(s1,s)
                return self.common(s1, s)
        for i, j in zip(s1[::-1], s[::-1]):
            if i != j : return self.v(i,j)
        return 'Tie'

    def straight_flush(self, p):
        return len(set([i[1] for i in p])) == 1 and all(abs(self.st.index(p[i][0]) - self.st.index(p[i + 1][0])) == 1 for i in range(len(p) - 1))

    def four_of_kind(self, p):
        p = [i[0] for i in p]
        return any(p.count(i) == 4 for i in p)

    def full_house(self, p):
        p = [i[0] for i in p]
        return any(p.count(i) == 3 for i in p) and any(p.count(i) == 2 for i in p)

    def flush(self, p):
        return len(set([i[1] for i in p])) == 1

    def straight(self, p):
        return all(abs(self.st.index(p[i][0]) - self.st.index(p[i + 1][0])) == 1 for i in range(len(p) - 1))

    def three_of_kind(self, p):
        p = [i[0] for i in p]
        return any(p.count(i) == 3 for i in p)

    def two_pair(self, p):
        p = [i[0] for i in p]
        return [p.count(i) for i in set(p)].count(2) == 2

    def one_pair(self, p):
        p = [i[0] for i in p]
        return [p.count(i) for i in...


Solve in Python:
A famous casino is suddenly faced with a sharp decline of their revenues. They decide to offer Texas hold'em also online. Can you help them by writing an algorithm that can rank poker hands?

Task:

Create a poker hand that has a constructor that accepts a string containing 5 cards:

```python
hand = PokerHand("KS 2H 5C JD TD")
```

The characteristics of the string of cards are:

A space is used as card seperator
Each card consists of two characters
The first character is the value of the card, valid characters are:
`2, 3, 4, 5, 6, 7, 8, 9, T(en), J(ack), Q(ueen), K(ing), A(ce)`
The second character represents the suit, valid characters are:
`S(pades), H(earts), D(iamonds), C(lubs)`

The poker hands must be sortable by rank, the highest rank first:

```python
hands = []
hands.append(PokerHand("KS 2H 5C JD TD"))
hands.append(PokerHand("2C 3C AC 4C 5C"))
hands.sort() (or sorted(hands))
```

Apply the Texas Hold'em rules for ranking the cards.
There is no ranking for the suits.
An ace can either rank high or rank low in a straight or straight flush. Example of a straight with a low ace:
`"5C 4D 3C 2S AS"`

Note:  there are around 25000 random tests, so keep an eye on performances.

class PokerHand(object):
    VALUES = "A23456789TJQKA"

    def __repr__(self):  return self.hand

    def __init__(self, hand):
        self.hand = hand
        values = ''.join(sorted(hand[::3], key=self.VALUES[1:].index))
        suits = set(hand[1::3])
        hi_straight = values in self.VALUES
        lo_straight = values[-1] + values[:-1] in self.VALUES
        is_flush = len(suits) == 1
        self.score = (2 * sum(values.count(card) for card in values)
                      + 13 * (hi_straight or lo_straight) + 15 * is_flush,
                     [self.VALUES[:-1].index(card) if lo_straight else self.VALUES[1:].index(card) for card in values[::-1]])

    def __lt__(self, other):
        return other.score < self.score


Solve in Python:
A faro shuffle of a deck of playing cards is a shuffle in which the deck is split exactly in half and then the cards in the two halves are perfectly interwoven, such that the original bottom card is still on the bottom and the original top card is still on top.

For example, faro shuffling the list
```python
['ace', 'two', 'three', 'four', 'five', 'six']
```
gives
```python
['ace', 'four', 'two', 'five', 'three', 'six' ]
```

If 8 perfect faro shuffles are performed on a deck of 52 playing cards, the deck is restored to its original order.

Write a function that inputs an integer n and returns an integer representing the number of faro shuffles it takes to restore a deck of n cards to its original order.

Assume n is an even number between 2 and 2000.

def faro_cycles(deck_size):
    arr, count = list(range(deck_size)), 0
    original_arr = arr
    while True:
        arr = arr[0:deck_size:2] + arr[1:deck_size:2]
        count += 1
        if original_arr == arr:
            break
    return count


Solve in Python:
A festival will be held in a town's main street. There are n sections in the main street. The sections are numbered 1 through n from left to right. The distance between each adjacent sections is 1.

In the festival m fireworks will be launched. The i-th (1 ≤ i ≤ m) launching is on time t_{i} at section a_{i}. If you are at section x (1 ≤ x ≤ n) at the time of i-th launching, you'll gain happiness value b_{i} - |a_{i} - x| (note that the happiness value might be a negative value).

You can move up to d length units in a unit time interval, but it's prohibited to go out of the main street. Also you can be in an arbitrary section at initial time moment (time equals to 1), and want to maximize the sum of happiness that can be gained from watching fireworks. Find the maximum total happiness.

Note that two or more fireworks can be launched at the same time.

-----Input-----

The first line contains three integers n, m, d (1 ≤ n ≤ 150000; 1 ≤ m ≤ 300; 1 ≤ d ≤ n).

Each of the next m lines contains integers a_{i}, b_{i}, t_{i} (1 ≤ a_{i} ≤ n; 1 ≤ b_{i} ≤ 10^9; 1 ≤ t_{i} ≤ 10^9). The i-th line contains description of the i-th launching.

It is guaranteed that the condition t_{i} ≤ t_{i} + 1 (1 ≤ i < m) will be satisfied.

-----Output-----

Print a single integer — the maximum sum of happiness that you can gain from watching all the fireworks.

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

-----Examples-----
Input
50 3 1
49 1 1
26 1 4
6 1 10

Output
-31

Input
10 2 1
1 1000 4
9 1000 4

Output
1992


Solve in Python:
A few years ago, Aaron left his old school and registered at another due to security reasons. Now he wishes to find Jane, one of his schoolmates and good friends.

There are `n` schools numbered from 1 to `n`. One can travel between each pair of schools by buying a ticket. The ticket between schools `i` and `j` costs `(i + j) modulo (n + 1)` and can be used multiple times. Help Aaron find the minimum total cost to visit all schools. He can start and finish at any school.

Range : 1 ≤ n ≤ 10^(6)


Solve in Python:
A forest fire has been spotted at *fire*, a simple 2 element array with x, y coordinates.

The forest service has decided to send smoke jumpers in by plane and drop them in the forest.

The terrain is dangerous and surveyors have determined that there are three possible safe *dropzones*, an array of three simple arrays with x, y coordinates.

The plane is en route and time is of the essence. Your mission is to return a simple [x,y] array with the coordinates of the dropzone closest to the fire.

EDIT:
The airplane is leaving from the origin at 0,0. If your result returns two possible dropzones that are both an equal distance from the fire, choose the dropzone that is closest to 0,0.

If the two dropzones are both equal distance away from 0,0, then return the dropzone that is first in the given array.

For example, if you are given: fire = [1,1], possibleDZ = [0,1],[1,0],[2,2] . The answer is [0,1] because that is the first possible drop zone in the given array.

def dropzone(p, dropzones):
  return min(dropzones, key=lambda q: (q[0]-p[0])**2 + (q[1]-p[1])**2)


Solve in Python:
A format for expressing an ordered list of integers is to use a comma separated list of either

* individual integers
* or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. The range includes all integers in the interval including both endpoints.  It is not considered a range unless it spans at least 3 numbers. For example "12,13,15-17"

Complete the solution  so that it takes a list of integers in increasing order and returns a correctly formatted string in the range format.

**Example:**

```python
solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20])
# returns "-6,-3-1,3-5,7-11,14,15,17-20"
```

```C#
RangeExtraction.Extract(new[] {-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20});
# returns "-6,-3-1,3-5,7-11,14,15,17-20"
```

*Courtesy of rosettacode.org*

from itertools import groupby
def solution(args):
    d=''
    fun = lambda x: x[1] - x[0]
    for k, g in groupby(enumerate(args), fun):
        c=[b for a,b in g]
        if len(c)==1:
            d=d+'%d,'%c[0]
        elif len(c)==2:
            d=d+'%d,%d,'%(c[0],c[-1])
        else:
            d=d+'%d-%d,'%(c[0],c[-1])
    return (d[:-1])


Solve in Python:
A friend of mine told me privately: "I don't like palindromes". "why not?" - I replied. "Because when I want to do some programming challenges, I encounter 2 or 3 ones first related with palindromes. I'm fed up" - he confess me with anger. I said to myself:"Thankfully, that doesn't happen in Codewars".
Talking seriously, we have to count the palindrome integers. Doing that, perhaps, it will help us to make all the flood of palindrome programming challenges more understandable.

For example all the integers of 1 digit (not including 0) are palindromes, 9 cases.
We have nine of them with two digits, so the total amount of palidromes below ```100``` (10^(2)) is ```18```.
At least, will we be able to calculate the amount of them for a certain number of digits?
Let's say for ```2000``` digits?
Prepare a code that given the number of digits ```n```, may output the amount of palindromes of length equals to n and the total amount of palindromes below 10^(n).

You will see more examples in the box.
Happy coding!!

(You don't know what palindromes are? Investigate, :))

def count_pal(n):
    x = lambda y: 9 * int(10 ** ((y - 1)//2))
    return [x(n), sum(x(i) for i in range(n+1))]


Solve in Python:
A frog is crossing a river. The river is divided into x units and at each unit there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.

Given a list of stones' positions (in units) in sorted ascending order, determine if the frog is able to cross the river by landing on the last stone. Initially, the frog is on the first stone and assume the first jump must be 1 unit.

If the frog's last jump was k units, then its next jump must be either k - 1, k, or k + 1 units. Note that the frog can only jump in the forward direction.

Note:

The number of stones is ≥ 2 and is < 1,100.
Each stone's position will be a non-negative integer < 231.
The first stone's position is always 0.

Example 1:

[0,1,3,5,6,8,12,17]

There are a total of 8 stones.
The first stone at the 0th unit, second stone at the 1st unit,
third stone at the 3rd unit, and so on...
The last stone at the 17th unit.

Return true. The frog can jump to the last stone by jumping
1 unit to the 2nd stone, then 2 units to the 3rd stone, then
2 units to the 4th stone, then 3 units to the 6th stone,
4 units to the 7th stone, and 5 units to the 8th stone.

Example 2:

[0,1,2,3,4,8,9,11]

Return false. There is no way to jump to the last stone as
the gap between the 5th and 6th stone is too large.

class Solution:
     def canCross(self, stones):
         """
         :type stones: List[int]
         :rtype: bool
         """
         if stones == []: return False
         if len(stones) == 1: return True
         diff = [0]*len(stones)

         for i in range(1,len(stones)):
             if stones[i] - stones[i-1] > i: return False

         stk = [(0, 0)]
         dictt = {}
         for idx, stone in enumerate(stones):
             dictt[stone] = idx
         while stk:
             idx, prevjump = stk.pop()

             for k in range(max(1, prevjump-1), prevjump+2):
                 if stones[idx] + k in dictt:
                     x = dictt[stones[idx] + k]
                     if x == len(stones) - 1: return True
                     stk.append((dictt[stones[idx]+k], k))

         return False


Solve in Python:
A function $f : R \rightarrow R$ is called Lipschitz continuous if there is a real constant K such that the inequality |f(x) - f(y)| ≤ K·|x - y| holds for all $x, y \in R$. We'll deal with a more... discrete version of this term.

For an array $h [ 1 . . n ]$, we define it's Lipschitz constant $L(h)$ as follows:  if n < 2, $L(h) = 0$  if n ≥ 2, $L(h) = \operatorname{max} [ \frac{|h [ j ] - h [ i ]|}{j - i} ]$ over all 1 ≤ i < j ≤ n

In other words, $L = L(h)$ is the smallest non-negative integer such that |h[i] - h[j]| ≤ L·|i - j| holds for all 1 ≤ i, j ≤ n.

You are given an array [Image] of size n and q queries of the form [l, r]. For each query, consider the subarray $s = a [ l . . r ]$; determine the sum of Lipschitz constants of all subarrays of $S$.

-----Input-----

The first line of the input contains two space-separated integers n and q (2 ≤ n ≤ 100 000 and 1 ≤ q ≤ 100) — the number of elements in array [Image] and the number of queries respectively.

The second line contains n space-separated integers $a [ 1 . . n ]$ ($0 \leq a [ i ] \leq 10^{8}$).

The following q lines describe queries. The i-th of those lines contains two space-separated integers l_{i} and r_{i} (1 ≤ l_{i} < r_{i} ≤ n).

-----Output-----

Print the answers to all queries in the order in which they are given in the input. For the i-th query, print one line containing a single integer — the sum of Lipschitz constants of all subarrays of [Image].

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

Output
17
82
23
210

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

Output
2
0
22
59
16
8

-----Note-----

In the first query of the first sample, the Lipschitz constants of subarrays of $[ 5,2,9 ]$ with length at least 2 are:  $L([ 5,2 ]) = 3$  $L([ 2,9 ]) = 7$  $L([ 5,2,9 ]) = 7$

The answer to the query is their sum.

f = lambda: list(map(int, input().split()))
n, m = f()
t = list(f())
p = [1e9] + [abs(b - a) for a, b in zip(t, t[1:])] + [1e9]
L, R = [0] * n, [0] * n
for i in range(1, n):
    j = n - i
    x, y = i - 1, j + 1
    a, b = p[i], p[j]
    while a > p[x]: x = L[x]
    while b >= p[y]: y = R[y]
    L[i], R[j] = x, y
for k in range(m):
    l, r = f()
    print(sum((i - max(l - 1, L[i])) * (min(r, R[i]) - i) * p[i] for i in range(l, r)))


Solve in Python:
A function receives a certain numbers of integers ```n1, n2, n3 ..., np```(all positive and different from 0) and a factor ```k, k > 0```

The function rearranges the numbers ```n1, n2, ..., np``` in such order that generates the minimum number concatenating the digits and this number should be divisible by ```k```.

The order that the function receives their arguments is:
```python
rearranger(k, n1, n2, n3,....,np)
```

## Examples

```python
rearranger(4, 32, 3, 34, 7, 12)  == "Rearrangement: 12, 3, 34, 7, 32 generates: 12334732 divisible by 4"

rearranger(10, 32, 3, 34, 7, 12) == "There is no possible rearrangement"
```
If there are more than one possible arrengement for the same minimum number, your code should be able to handle those cases:
```python
rearranger(6, 19, 32, 2, 124, 20, 22) == "Rearrangements: 124, 19, 20, 2, 22, 32 and 124, 19, 20, 22, 2, 32 generates: 124192022232 divisible by 6"
```

The arrangements should be in sorted order, as you see: `124, 19, 20, 2, 22, 32` comes first than `124, 19, 20, 22, 2, 32`.

Have an enjoyable time!

(Thanks to `ChristianE.Cooper` for his contribution to this kata)

from itertools import permutations as p

def rearranger(k, *args):
    res, u, t = 1E200, len(args),(0,0)
    for i in p(args,u):
        a = int(''.join(map(str,i)))
        if a % k == 0:
            if a < res:
                res = a
                t = i
            if a == res:
                if i < t:
                    t = i
    if t == (0,0):
        return "There is no possible rearrangement"
    else:
        return "Rearrangement: " + str(t)[1:-1] + " generates: " + str(res) + " divisible by " + str(k)


Solve in Python:
A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns.
The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph.
Mouse starts at node 1 and goes first, Cat starts at node 2 and goes second, and there is a Hole at node 0.
During each player's turn, they must travel along one edge of the graph that meets where they are.  For example, if the Mouse is at node 1, it must travel to any node in graph[1].
Additionally, it is not allowed for the Cat to travel to the Hole (node 0.)
Then, the game can end in 3 ways:

If ever the Cat occupies the same node as the Mouse, the Cat wins.
If ever the Mouse reaches the Hole, the Mouse wins.
If ever a position is repeated (ie. the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw.

Given a graph, and assuming both players play optimally, return 1 if the game is won by Mouse, 2 if the game is won by Cat, and 0 if the game is a draw.

Example 1:
Input: [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]
Output: 0
Explanation:
4---3---1
|   |
2---5
 \ /
  0

Note:

3 <= graph.length <= 50
It is guaranteed that graph[1] is non-empty.
It is guaranteed that graph[2] contains a non-zero element.

class Solution:
    def catMouseGame(self, graph):
        mem = [[[-1 for i in range(1+2*len(graph))] for i in range(1+2*len(graph))] for i in range(2*len(graph))]
        def storeRet(m,c,t,v):
            mem[m][c][t] = v
            return mem[m][c][t]
        mouseWin = lambda m,c,t:storeRet(m,c,t,1)
        catWin = lambda m,c,t:storeRet(m,c,t,2)
        draw = lambda m,c,t:storeRet(m,c,t,0)

        def play(m, c, t):
            if mem[m][c][t]!=-1: return mem[m][c][t] # already visited this game state
            if t >= len(graph)*2: return 0 # repeated states
            if not t % 2: # mouse turn
                drawFound = False
                for n in graph[m]:
                    if n == 0: return mouseWin(m,c,t)
                    if n == c: continue
                    res = play(n, c, t+1)
                    if res == 1: return mouseWin(m,c,t)
                    if res == 0: drawFound = True
                return draw(m,c,t) if drawFound else catWin(m,c,t)
            else: # cat turn
                drawFound=False
                for n in graph[c]:
                    if n == m: return catWin(m,c,t)
                    if n == 0: continue
                    res = play(m, n, t+1)
                    if res == 2: return catWin(m,c,t)
                    if res == 0: drawFound = True
                return draw(m,c,t) if drawFound else mouseWin(m,c,t)
        return play(1,2,0)


Solve in Python:
A generalization of Bézier surfaces, called the S-patch, uses an interesting scheme for indexing its control points.

In the case of an n-sided surface of degree d, each index has n non-negative integers that sum to d, and all possible configurations are used.

For example, for a 3-sided quadratic (degree 2) surface the control points are:

> indices 3 2 => [[0,0,2],[0,1,1],[0,2,0],[1,0,1],[1,1,0],[2,0,0]]

Given the degree and the number of sides, generate all control point indices.
The order of the indices in the list can be arbitrary, so for the above example

> [[1,1,0],[2,0,0],[0,0,2],[0,2,0],[0,1,1],[1,0,1]]

is also a good solution.

def indices(n, d):
    result=[]
    temp=[]
    def tt (n, d,temp):
        if d==1:
            result.extend([temp+[n]])
            return 0
        for i in range(0,n+1):
            aa=temp+[i]
            tt(n-i, d-1,aa)
    tt(d, n,temp)
    return result


Solve in Python:
A grammar is a set of rules that let us define a language. These are called **production rules** and can be derived into many different tools. One of them is **String Rewriting Systems** (also called Semi-Thue Systems or Markov Algorithms). Ignoring technical details, they are a set of rules that substitute ocurrences in a given string by other strings.

The rules have the following format:

```
str1 -> str2
```

We define a rule application as the substitution of a substring following a rule. If this substring appears more than once, only one of this occurences is substituted and any of them is equally valid as an option:

```python
'a' -> 'c' # Substitution rule

'aba' # Base string
'cba' # One application on position 0
'abc' # One application on position 2
'cbc' # Two applications
```

Another valid example of rule application would be the following:

```python
# Rules
'l' -> 'de'
'm' -> 'col'
'rr' -> 'wakr'
'akr' -> 'ars'

# Application
'mrr' # Starting string
'colrr' # Second rule
'coderr' # First rule
'codewakr' # Third rule
'codewars' # Last rule
```
Note that this example is exhaustive, but Semi-Thue Systems can be potentially infinite:

```python
# Rules
'a' -> 'aa'

# Application
'a' # Starting string
'aa' # First application
'aaa' # Second application
...
```

The so called **Word Problem** is to decide whether or not a string can be derived from another using these rules. This is an **undecidable problem**, but if we restrict it to a certain number of applications, we can give it a solution.

Your task is to write a function that solves the word problem given a maximum number of rule applications.

**Python:** The rules are given as tuples where the left and the right handside of the rule correspond to the first and the second element respectively.

**Notes:**
* Two rules can have the same left handside and a different right handside.
* You do not have to worry too much about performance yet. A simple, funtional answer will be enough.

def word_problem(rules: List[Tuple[str, str]], from_str: str, to_str: str, applications: int) -> bool:
    rec = lambda s,n: s == to_str or n and any(s[i:].startswith(x) and rec(s[:i] + y + s[i+len(x):], n-1) for i in range(len(s)) for x,y in rules)
    return rec(from_str, applications)


Solve in Python:
A great flood has hit the land, and just as in Biblical times we need to get the animals to the ark in pairs. We are only interested in getting one pair of each animal, and not interested in any animals where there are less than 2....they need to mate to repopulate the planet after all!

You will be given a list of animals, which you need to check to see which animals there are at least two of, and then return a dictionary containing the name of the animal along with the fact that there are 2 of them to bring onto the ark.

---

```python
>>> two_by_two(['goat', 'goat', 'rabbit', 'rabbit', 'rabbit', 'duck', 'horse', 'horse', 'swan'])
{'goat': 2, 'horse': 2, 'rabbit': 2}

# If the list of animals is empty, return False as there are no animals to bring onto the ark and we are all doomed!!!
>>> two_by_two([])
False

# If there are no pairs of animals, return an empty dictionary
>>> two_by_two(['goat'])
{}
```

from collections import Counter

def two_by_two(animals):
    if not animals:
        return False
    return {k: 2 for k, v in Counter(animals).items() if v >= 2}


Solve in Python:
A grid is a perfect starting point for many games (Chess, battleships, Candy Crush!).

Making a digital chessboard I think is an interesting way of visualising how loops can work together.

Your task is to write a function that takes two integers `rows` and `columns` and returns a chessboard pattern as a two dimensional array.

So `chessBoard(6,4)` should return an array like this:

    [
            ["O","X","O","X"],
            ["X","O","X","O"],
            ["O","X","O","X"],
            ["X","O","X","O"],
            ["O","X","O","X"],
            ["X","O","X","O"]
    ]

And `chessBoard(3,7)` should return this:

    [
        ["O","X","O","X","O","X","O"],
        ["X","O","X","O","X","O","X"],
        ["O","X","O","X","O","X","O"]
    ]

The white spaces should be represented by an: `'O'`

and the black an: `'X'`

The first row should always start with a white space `'O'`

chess_board = lambda r, c: [["OX"[(i+j)%2] for j in range(c)] for i in range(r)]


Solve in Python:
A group of N golfers wants to play in groups of G players for D days in such a way that no golfer plays more than once with any other golfer. For example, for N=20, G=4, D=5, the solution at Wolfram MathWorld is

```
 Mon:   ABCD    EFGH    IJKL    MNOP    QRST
 Tue:   AEIM    BJOQ    CHNT    DGLS    FKPR
 Wed:   AGKO    BIPT    CFMS    DHJR    ELNQ
 Thu:   AHLP    BKNS    CEOR    DFIQ    GJMT
 Fri:   AFJN    BLMR    CGPQ    DEKT    HIOS
```

Write a function that validates a proposed solution, a list of list of strings, as being a solution to the social golfer problem. Each character represents a golfer, and each string is a group of players. Rows represent days. The solution above would be encoded as:

```
 [
  ['ABCD', 'EFGH', 'IJKL', 'MNOP', 'QRST'],
  ['AEIM', 'BJOQ', 'CHNT', 'DGLS', 'FKPR'],
  ['AGKO', 'BIPT', 'CFMS', 'DHJR', 'ELNQ'],
  ['AHLP', 'BKNS', 'CEOR', 'DFIQ', 'GJMT'],
  ['AFJN', 'BLMR', 'CGPQ', 'DEKT', 'HIOS']
 ]
```

You need to make sure (1) that each golfer plays exactly once every day, (2) that the number and size of the groups is the same every day, and (3) that each player plays with every other player *at most* once.

So although each player must play every day, there can be particular pairs of players that never play together.

It is not necessary to consider the case where the number of golfers is zero; no tests will check for that. If you do wish to consider that case, note that you should accept as valid all possible solutions for zero golfers, who (vacuously) can indeed play in an unlimited number of groups of zero.

import itertools

def valid(schedule):
    golfers = set(golfer for day in schedule for group in day for golfer in group)
    days = ["".join(day) for day in schedule]
    groups = [set(group) for group in sum(schedule, [])]
    return (
        all(day.count(golfer) == 1 for day in days for golfer in golfers) and
        len(set(len(day) for day in schedule)) == 1 and
        len(set(len(group) for group in groups)) == 1 and
        all(sum(pair <= group for group in groups) <= 1 for pair in map(set, itertools.combinations(golfers, 2))))


Solve in Python:
A group of friends (n >= 2) have reunited for a get-together after
a very long time.

They agree that they will make presentations on holiday destinations
or expeditions they have been to only if it satisfies **one simple rule**:
> the holiday/journey being presented must have been visited _only_ by the presenter and no one else from the audience.

Write a program to output the presentation agenda, including the
presenter and their respective presentation titles.

---
### EXAMPLES

```python
presentation_agenda([
    {'person': 'Abe', 'dest': ['London', 'Dubai']},
    {'person': 'Bond', 'dest': ['Melbourne', 'Dubai']}
]) == [{'person': 'Abe', 'dest': ['London']},
       {'person': 'Bond', 'dest': ['Melbourne']}]

presentation_agenda([
    {'person': 'Abe', 'dest': ['Dubai']},
    {'person': 'Brad', 'dest': ['Dubai']}
]) == []

presentation_agenda([
    {'person': 'Abe', 'dest': ['London', 'Dubai']},
    {'person': 'Bond', 'dest': ['Melbourne', 'Dubai']},
    {'person': 'Carrie', 'dest': ['Melbourne']},
    {'person': 'Damu', 'dest': ['Melbourne', 'Dubai', 'Paris']}
]) == [{'person': 'Abe',  'dest': ['London']},
       {'person': 'Damu', 'dest': ['Paris']}]

```

from functools import reduce
def presentation_agenda(friend_list):

    def add_exclusive_locations(agenda, friend):
        locations_visited_by_peers = reduce(
                lambda lst, p: lst + p['dest'] if p != friend else lst,
                friend_list,
                []
        )

        def is_unique(loc):
            return loc not in locations_visited_by_peers

        exclusive = list(filter(is_unique, friend['dest']))
        if exclusive: # at least one location?
            agenda.append({'person': friend['person'], 'dest': exclusive})
        return agenda

    return reduce(add_exclusive_locations, friend_list, []);


Solve in Python:
A group of n cities is connected by a network of roads. There is an undirected road between every pair of cities, so there are $\frac{n \cdot(n - 1)}{2}$ roads in total. It takes exactly y seconds to traverse any single road.

A spanning tree is a set of roads containing exactly n - 1 roads such that it's possible to travel between any two cities using only these roads.

Some spanning tree of the initial network was chosen. For every road in this tree the time one needs to traverse this road was changed from y to x seconds. Note that it's not guaranteed that x is smaller than y.

You would like to travel through all the cities using the shortest path possible. Given n, x, y and a description of the spanning tree that was chosen, find the cost of the shortest path that starts in any city, ends in any city and visits all cities exactly once.

-----Input-----

The first line of the input contains three integers n, x and y (2 ≤ n ≤ 200 000, 1 ≤ x, y ≤ 10^9).

Each of the next n - 1 lines contains a description of a road in the spanning tree. The i-th of these lines contains two integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n) — indices of the cities connected by the i-th road. It is guaranteed that these roads form a spanning tree.

-----Output-----

Print a single integer — the minimum number of seconds one needs to spend in order to visit all the cities exactly once.

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

Output
9

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

Output
8

-----Note-----

In the first sample, roads of the spanning tree have cost 2, while other roads have cost 3. One example of an optimal path is $5 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 2$.

In the second sample, we have the same spanning tree, but roads in the spanning tree cost 3, while other roads cost 2. One example of an optimal path is $1 \rightarrow 4 \rightarrow 5 \rightarrow 2 \rightarrow 3$.

from collections import defaultdict
from collections import deque
from functools import reduce
n, x, y = [int(x) for x in input().split()]
E = defaultdict(set)
for i in range(n-1):
    u, v = [int(x) for x in input().split()]
    E[u].add(v)
    E[v].add(u)

if x > y:
    for v in E:
        if len(E[v]) == n-1:
            print((n-2)*y + x)
            break
        elif len(E[v]) > 1:
            print((n-1)*y)
            break
else:
    visited = {v : False for v in E}
    stack = [1]
    topsorted = deque()
    while stack:
        v = stack.pop()
        if visited[v]: continue
        visited[v] = True
        topsorted.appendleft(v)
        stack.extend(E[v])
    chopped = set()
    ans = 0
    for v in topsorted:
        ans += max(0, len(E[v])-2)
        if len(E[v]) > 2:
            S = E[v].intersection(chopped)
            S1 = {S.pop(), S.pop()}
            for u in E[v]:
                if not u in S1:
                    E[u].remove(v)
            E[v].clear()
            E[v].update(S1)
        chopped.add(v)
    print(ans*y + (n-1-ans)*x)


Solve in Python:
A group of rebels travelling on a square hoverboard is ambushed by Imperial Stormtroopers.Their big hoverboard is an easy target, so they decide to split the board into smaller square hoverboards so that they can bolt away easily.But they should also make sure they don't get too spread out.Help the rebels split the craft into minimum number of smaller crafts possible.

-----Input-----
A single integer N denoting the side length of the big hoverboard.

-----Output-----
In the first line, output the integer 'k' which is the minimum number of square boards into which the bigger board can be split up.

In the second line, output k space separated integers which denote the sizes of the smaller square hoverboards.This must be in increasing order of sizes.

-----Constraints-----
N ranges from 2 to 50.

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

Output:
6
1 1 1 1 1 2

-----Explanation-----
A square of side length 3 can be split into smaller squares in two ways: Either into 9 squares of side1 or 5 squares of side 1 and 1 square of size 2.The second case is the favourable one.


Solve in Python:
A happy number is a number defined by the following process: starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.

Those numbers for which this process ends in 1 are **happy numbers**, while those that do not end in 1 are unhappy numbers (or sad numbers) (Wikipedia).

Write a function that takes `n` as parameter and return `true` if and only if `n` is an happy number, `false` otherwise.

## Examples

For example number `7` is happy because after a number of steps the computed sequence ends up with a 1: `7, 49, 97, 130, 10, 1 `

While `3` is not, and would give us an infinite sequence: `3, 9, 81, 65, 61, 37, 58, 89, 145, 42, 20, 4, 16, 37, 58, 89, 145, 42, 20, 4, 16, 37, ...`

Happy coding!

def is_happy(n):
    seen = set()
    while n!=1:
        n = sum(int(d)**2 for d in str(n))
        if n not in seen: seen.add(n)
        else:             return False
    return True


Solve in Python:
A happy string is a string that:

consists only of letters of the set ['a', 'b', 'c'].
s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed).

For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy strings and strings "aa", "baa" and "ababbc" are not happy strings.
Given two integers n and k, consider a list of all happy strings of length n sorted in lexicographical order.
Return the kth string of this list or return an empty string if there are less than k happy strings of length n.

Example 1:
Input: n = 1, k = 3
Output: "c"
Explanation: The list ["a", "b", "c"] contains all happy strings of length 1. The third string is "c".

Example 2:
Input: n = 1, k = 4
Output: ""
Explanation: There are only 3 happy strings of length 1.

Example 3:
Input: n = 3, k = 9
Output: "cab"
Explanation: There are 12 different happy string of length 3 ["aba", "abc", "aca", "acb", "bab", "bac", "bca", "bcb", "cab", "cac", "cba", "cbc"]. You will find the 9th string = "cab"

Example 4:
Input: n = 2, k = 7
Output: ""

Example 5:
Input: n = 10, k = 100
Output: "abacbabacb"

Constraints:

1 <= n <= 10
1 <= k <= 100

class Solution:
    def getHappyString(self, n: int, k: int) -> str:

        def dfs(ind,nlen,path,res):
            if ind == nlen:
                res.append(path)
                return
            for i in range(3):
                if len(path)==0 or (path[-1]!=ls[i]):
                    dfs(ind+1,nlen,path+ls[i],res)

        ls = ['a','b','c']
        vis = [0]*3
        res = []
        dfs(0,n,'',res)
        res.sort()
        if len(res)<k:
            return ''
        return res[k-1]


Solve in Python:
A hero is on his way to the castle to complete his mission. However, he's been told that the castle is surrounded with a couple of powerful dragons! each dragon takes 2 bullets to be defeated, our hero has no idea how many bullets he should carry.. Assuming he's gonna grab a specific given number of bullets and move forward to fight another specific given number of dragons, will he survive?

Return True if yes, False otherwise :)

def hero(bullets, dragons):
    p = bullets >= 2*dragons
    return p


Solve in Python:
A high school has a strange principal. On the first day, he has his students perform an odd opening day ceremony:

There are number of lockers "n" and number of students "n" in the school. The principal asks the first student to go to every locker and open it. Then he has the second student go to every second locker and close it. The third goes to every third locker and, if it is closed, he opens it, and if it is open, he closes it. The fourth student does this to every fourth locker, and so on. After the process is completed with the "n"th student, how many lockers are open?

The task is to write a function which gets any number as an input and returns the number of open lockers after last sudent complets his activity. So input of the function is just one number which shows number of lockers and number of students. For example if there are 1000 lockers and 1000 students in school then input is 1000 and function returns number of open lockers after 1000th student completes his action.

The given input is always an integer greater than or equal to zero that is why there is no need for validation.

import math

def num_of_open_lockers(n):
    return math.floor(math.sqrt(n))


Solve in Python:
A hypergraph is a generalization of a graph, where an edge can connect any number of vertices. A k-uniform hypergraph is a hypergraph such that all its hyperedges have size k. For more information, see Wikipedia.

Let's call a particular hypergraph a hypertree if it is connected (that is, you can move from any vertex to any other vertex using only its hyperedges) and removing any of its hyperedges makes the hypergraph disconnected (note that this definition of hypertrees differs from the standard one).

Given just one integer N, find the number of 3-uniform hypertrees on N vertices. Two 3-uniform hypertrees are considered different if a hyperedge (u, v, w) exists such that it is present in exactly one of these hypertrees (note that the order of vertices in the hyperedge doesn't matter, and neither does the order of hyperedges in the hypertree).

-----Input-----
The first line of the input contains an integer T -- the number of test cases (at most 15). Then T lines follow, each contains an integer N (3 ≤ N ≤ 17).

Important! Please include all code used in solving this problem in your solution.

-----Output-----
For each test case output one line containing the requested number. It's guaranteed that this number won't exceed 263-1.

-----Examples-----
Input:
4
3
4
5
8

Output:
1
6
25
93268

Explanation:
There is just one 3-uniform hypertree on 3 vertices: {(1,2,3)}. There are six of them on 4 vertices: {(1,2,3), (1,2,4)}, {(1,2,3), (1,3,4)}, {(1,2,3), (2,3,4)}, {(1,2,4), (1,3,4)}, {(1,2,4), (2,3,4)}, {(1,3,4), (2,3,4)}. Two of the 25 possible hypertrees on 5 vertices are {(1,2,3), (3,4,5)} and {(1,2,3), (1,2,4), (1,2,5)}.

"""
#this code is a precomputation part.
#it takes about 2 hours.
class Graph:
  def __init__(self,n):
    self.edge=[[0 for j in xrange(n)] for i in xrange(n)]
    self.n=n

  def addedge(self,i,j,m=1):
    assert i!=j and 0<=i<self.n and 0<=j<self.n
    self.edge[i][j]+=m
    self.edge[j][i]+=m

  def deledge(self,i,j,m=1):
    assert i!=j and 0<=i<self.n and 0<=j<self.n
    self.edge[i][j]-=m
    self.edge[j][i]-=m

  def strongconnect(self):
    ret = True
    n=self.n
    for i in xrange(n):
      for j in xrange(i+1,n):
        if self.edge[i][j]:
          self.deledge(i,j)
          ret=self.connect()
          self.addedge(i,j)
          if ret==False:return ret
    return True

  def connect(self):
    n=self.n
    edge=self.edge
    z=[0 for _ in xrange(n)]
    def f(i):
      assert 0<=i<n
      if z[i]==1:return
      z[i]=1
      for j in xrange(n):
        if edge[i][j]:f(j)
    f(0)
    return sum(z)==n

  def Nconnect(self):
    n=self.n
    edge=self.edge
    z=[0 for _ in xrange(n)]
    def f(i):
      assert 0<=i<n
      if z[i]==1:return
      z[i]=1
      for j in xrange(n):
        if edge[i][j]:f(j)
    ret=0
    for ver in xrange(n):
      if z[ver]==0:
        ret+=1
        f(ver)
    return ret

def search(nv,ne):
  graph=Graph(nv)
  init=( graph, (0,0), ne)
  def f(state):
    ret=0
    g,(i,j),e=state
    if e==0:
      if g.strongconnect():
        return fact(ne)
      else:return 0

    if e<g.Nconnect():
      return 0
    for i2 in xrange(nv):
      for j2 in xrange(i2+1,nv):
        if (i2,j2)>(i,j):
          for k in xrange(1,e+1):
            g.addedge(i2,j2,k)
            ret += f((g,(i2,j2),e-k)) / fact(k)
            g.deledge(i2,j2,k)
    return ret
  return f(init)

def fact(n):
  assert n>=0
  ret=1
  for i in xrange(n):ret*=i+1
  return ret

def comb(a,b):
  return fact(a+b)/fact(a)/fact(b)
  pass

nnn=17
sve=dict( ( (v,e),search(v,e) )  for v in xrange(nnn+1) for e in xrange(nnn+1) if e>=v and e+v<=nnn)
sve[(1,0)]=1
print sve
"""

output="""
{(6, 9):...


Solve in Python:
A key feature of the Siruseri railway network is that it has exactly one route between any pair of stations.
The government has chosen three contractors to run the canteens at the stations on the railway network. To ensure that there are no disputes between the contractors it has been decided that if two stations, say $A$ and $B$, are assigned to a particular contractor then all the stations that lie on the route from $A$ to $B$ will also be awarded to the same contractor.
The government would like the assignment of stations to the contractors to be as equitable as possible. The government has data on the number of passengers who pass through each station each year. They would like to assign stations so that the maximum number of passengers passing through any contractor's collection of stations is minimized.
For instance, suppose the railway network is as follows, where the volume of passenger traffic is indicated by the side of each station.

One possible assignment would to award stations $1$ and $3$ to one contractor (there by giving him a traffic of $35$ passengers), station $2$ to the second contractor (traffic of $20$) and stations $4, 5$ and $6$ to the third contractor (traffic of $100$). In this assignment, the maximum traffic for any one contractor is 100. On the other hand if we assigned stations $1, 2$ and $3$ to one contractor, station $4$ and $6$ to the second contractor and station $5$ to the third contractor the maximum traffic for any one contractor is $70$. You can check that you cannot do better. (The assignment $1$, $2$ and $3$ to one contractor, $4$ to the second contractor, and $5$ and $6$ to the third contractor has a lower value for the maximum traffic ($55$) but it is not a valid assignment as the route from $5$ to $6$ passes through $4$.)

-----Input:-----
The first line of the input contains one integer $N$ indicating the number of railways stations in the network. The stations are numbered $1,2,..., N$. This is followed by $N$ lines of input, lines $2,3,...,N+1$, indicating the...

#for _ in range(int(input()):
#n,m = map(int,input().split())
#x = [int(w) for w in input().split()]
#n = int(input())
#x = [int(input()) for _ in range(n)]
#for i in range(n):
#dt = {} for i in x:dt[i] = dt.get(i,0)+1
#dt = {k:v for k,v in sorted(x.items(), key=lambda i: i[1])}

def dfs(v):
    visited.add(v)
    parents.append(v)
    for u in parents:
        desc[v][u] = True
    for u in graph[v]:
        if u not in visited:
            dfs(u)
            val[v] += val[u]
    parents.pop()

n = int(input())
cost,graph,val = {},{},{}
# val(i) is sum of cost of descendants of i
for i in range(1,n+1):
    cost[i] = int(input())
    graph[i] = []
    val[i] = cost[i]
for _ in range(n-1):
    a,b = map(int,input().split())
    graph[a].append(b)
    graph[b].append(a)

desc = [[False for i in range(n+1)] for i in range(n+1)]
# desc(i,j) is true if i is descendant of j
visited = set()
parents =[]   # Ancestors stack

dfs(1)
total = sum(cost.values())
best = float('inf')
for i in range(1,n):
    for j in range(i+1,n+1):
        split = 0
        s1 = val[i]
        s2 = val[j]
        if desc[i][j]:
            s2 -= val[i]
        if desc[j][i]:
            s1 -= val[j]
        s3 = total-s1-s2
        split = max(s1,s2,s3)
        best = min(best,split)
print(best)


Solve in Python:
A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a child is born.
The kingdom has a well-defined order of inheritance that consists of the king as the first member. Let's define the recursive function Successor(x, curOrder), which given a person x and the inheritance order so far, returns who should be the next person after x in the order of inheritance.
Successor(x, curOrder):
    if x has no children or all of x's children are in curOrder:
        if x is the king return null
        else return Successor(x's parent, curOrder)
    else return x's oldest child who's not in curOrder

For example, assume we have a kingdom that consists of the king, his children Alice and Bob (Alice is older than Bob), and finally Alice's son Jack.

In the beginning, curOrder will be ["king"].
Calling Successor(king, curOrder) will return Alice, so we append to curOrder to get ["king", "Alice"].
Calling Successor(Alice, curOrder) will return Jack, so we append to curOrder to get ["king", "Alice", "Jack"].
Calling Successor(Jack, curOrder) will return Bob, so we append to curOrder to get ["king", "Alice", "Jack", "Bob"].
Calling Successor(Bob, curOrder) will return null. Thus the order of inheritance will be ["king", "Alice", "Jack", "Bob"].

Using the above function, we can always obtain a unique order of inheritance.
Implement the ThroneInheritance class:

ThroneInheritance(string kingName) Initializes an object of the ThroneInheritance class. The name of the king is given as part of the constructor.
void birth(string parentName, string childName) Indicates that parentName gave birth to childName.
void death(string name) Indicates the death of name. The death of the person doesn't affect the Successor function nor the current inheritance order. You can treat it as just marking the person as dead.
string[] getInheritanceOrder() Returns a list representing the current order of inheritance excluding dead people.

Example 1:
Input
["ThroneInheritance",...

class Person:
    def __init__(self, name):
        self.name = name
        self.alive = True
        self.children = []

class ThroneInheritance:

    def __init__(self, kingName: str):
        self.king = Person(kingName)
        self.name_person_map = {kingName: self.king}

    def birth(self, parentName: str, childName: str) -> None:
        parent = self.name_person_map[parentName]
        child = Person(childName)
        parent.children.append(child)
        self.name_person_map[childName] = child

    def death(self, name: str) -> None:
        person = self.name_person_map[name]
        person.alive = False

    def getInheritanceOrder(self) -> List[str]:
        res = []
        self.preorder_dfs(self.king, res)
        return res

    def preorder_dfs(self, person, res):
        if person.alive:
            res.append(person.name)
        for child in person.children:
            self.preorder_dfs(child, res)

# Your ThroneInheritance object will be instantiated and called as such:
# obj = ThroneInheritance(kingName)
# obj.birth(parentName,childName)
# obj.death(name)
# param_3 = obj.getInheritanceOrder()


Solve in Python:
A list of integers is sorted in “Wave” order if alternate items are not less than their immediate neighbors (thus the other alternate items are not greater than their immediate neighbors).

Thus, the array `[4, 1, 7, 5, 6, 2, 3]` is in **Wave** order because 4 >= 1, then 1 <= 7, then 7 >= 5, then 5 <= 6, then 6 >= 2, and finally 2 <= 3.

The wave-sorted lists has to begin with an element not less than the next, so `[1, 4, 5, 3]` is not sorted in Wave because 1 < 4

Your task is to implement a function that takes a list of integers and sorts it into wave order in place; your function shouldn't return anything.

Note:
- The resulting array shouldn't necessarily match anyone in the tests, a function just checks if the array is now wave sorted.

def wave_sort(a):
    a.sort()
    for i in range(1, len(a), 2):
        a[i], a[i-1] = a[i-1], a[i]


Solve in Python:
A little weird green frog speaks in a very strange variation of English: it reverses sentence, omitting all puntuation marks  `, ; ( ) - ` except the final exclamation, question or period. We urgently need help with building a proper translator.
To simplify the task, we always use lower-case letters. Apostrophes are forbidden as well.

Translator should be able to process multiple sentences in one go. Sentences are separated by arbitrary amount of spaces.

**Examples**

`you should use python.` -> `python use should you.`

`look, a fly!` -> `fly a look!`

`multisentence is good. is not it?` -> `good is multisentence. it not is?`

import re

def reverse_sentence(m):
    words = m.group(1).split()
    rev = ' '.join(reversed(words))
    return m.expand(r' {}\2'.format(rev))

def frogify(s):
    s = re.sub(r'[,;{}\-\(\)]', '', s)
    return re.sub(r'(.*?)([.!?])', reverse_sentence, s).strip()


Solve in Python:
A long way back I have taken $5000 from Golu when I used to live in Jodhpur. Now, time has passed and I am out of Jodhpur. While Golu still in Jodhpur, one day called me and asked about his money.
I thought of giving Golu a chance. I told him that he can still take his money back if he reaches my home anyhow just in 2 days but not after that.
In excitement he made his way toward my hometown i.e. Gorakhpur. To cover up the petrol cost he started giving paid lift to whoever needs it throughout the way in order to earn some money. Help him to get the maximum profit.

His car has a capacity of k + 1 person, so in a certain moment he can transport k persons (and himself).
From Jodhpur to Gorakhpur, there are l localities (cities, towns, villages), Jodhpur being the first and Gorakhpur being the lth.
There are n groups of lift takers along the road. The ith
group consists of pi persons, wants to travel from locality si  to locality di and will pay an amount of mi money.
A group must be taken into the car as a whole. Assume that lift takers are found only in localities.

Restrictions
• 1 ≤ k ≤ 7
• 1 ≤ l ≤ 1000000
• 1 ≤ n ≤ 50
• 1 ≤ pi ≤ k
• 1 ≤ si ≤ l – 1
• 2 ≤ di ≤ l
• si < di
• 1 ≤ mi ≤ 1000000

-----Input-----
The first line of the input contains the number of test cases.
The first line of each test case contains the numbers n, l and k separated by a single space.
n lines follow, the ith line containing pi, si, di and mi separated by a single space.

-----Output-----
For each test case output a single line containing the maximum amount of money Golu can earn.

-----Example-----
Input:
2
5 5 4
2 1 5 50
1 2 4 20
2 3 4 40
2 4 5 50
3 4 5 80
10 10 5
2 5 10 17300
2 1 8 31300
5 4 10 27600
4 8 10 7000
5 9 10 95900
2 7 10 14000
3 6 10 63800
1 7 10 19300
3 8 10 21400
2 2 10 7000

Output:
140
127200

By:
Chintan, Asad, Ashayam, Akanksha

'''Well I found the bug, but I don't understand why it was doing that. I mean, as
far as I can tell, it shouldn't be a bug!
Note to self: deleting from (supposedly) local lists through recursion is dangerous!'''

class Group(object):
    def __init__(self,size,start,end,value):
        self.size = size
        self.start = start
        self.end = end
        self.value = value

    def __lt__(self,other):
        return self.start < other.start

    def __str__(self):
        return "%i: %i->%i, $%i" %(self.size,self.start,self.end,self.value)

def hash(car,i):
    people = []
    for group in car:
        people.extend([group.end]*group.size)
    people.sort()
    return tuple(people+[i])

def optimize(groups,car,capacity,i):
    if i == len(groups):
        return 0

    newcar = []
    pos = groups[i].start
    for group in car:
        if group.end > pos:
            newcar.append(group)
        else:
            capacity += group.size

    state = hash(newcar,i)
    try:
        return memo[state]
    except:
        v = optimize(groups,newcar,capacity,i+1)
        if groups[i].size <= capacity:
            w = optimize(groups,newcar+[groups[i]],capacity-groups[i].size,i+1) + groups[i].value
        else:
            w = 0

        if v > w:
            ie[state] = -1
        elif v < w:
            ie[state] = 1
        else:
            ie[state] = 0

        ans = max(v,w)
        memo[state] = ans
        return ans

cases = int(input())
for case in range(cases):
    memo = {}
    ie = {}
    groups = []
    n,_,capacity = list(map(int,input().split()))

    for g in range(n):
        size,start,end,value = list(map(int,input().split()))
        groups.append(Group(size,start,end,value))
    groups.sort()
    print(optimize(groups,[],capacity,0))


Solve in Python:
A lot of goods have an  International Article Number (formerly known as "European Article Number") abbreviated "EAN". EAN is a 13-digits barcode consisting of 12-digits data followed by a single-digit checksum (EAN-8 is not considered in this kata).

The single-digit checksum is calculated as followed (based upon the 12-digit data):

The digit at the first, third, fifth, etc. position (i.e. at the odd position) has to be multiplied with "1".
The digit at the second, fourth, sixth, etc. position (i.e. at the even position) has to be multiplied with "3".
Sum these results.

If this sum is dividable by 10, the checksum is 0. Otherwise the checksum has the following formula:

  checksum = 10 - (sum mod 10)

For example, calculate the checksum for "400330101839" (= 12-digits data):

4·1 + 0·3 + 0·1 + 3·3 + 3·1 + 0·3 + 1·1 + 0·3 + 1·1 + 8·3 + 3·1 + 9·3
= 4 + 0 + 0 + 9 + 3 + 0 + 1 + 0 + 1 + 24 + 3 + 27
= 72
10 - (72 mod 10) = 8 ⇒ Checksum: 8

Thus, the EAN-Code is 4003301018398 (= 12-digits data followed by single-digit checksum).

Your Task
Validate a given EAN-Code. Return true if the given EAN-Code is valid, otherwise false.

Assumption
You can assume the given code is syntactically valid, i.e. it only consists of numbers and it exactly has a length of 13 characters.

Examples

```python
validate_ean("4003301018398") # => True
validate_ean("4003301018392") # => False
```

Good Luck and have fun.

def validate_ean(code):
    data, last = code[:12], int(code[12])
    checksum = -sum(int(d) * 3**(i % 2) for i, d in enumerate(data)) % 10
    return last == checksum


Solve in Python:
A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it!

You are given integers $n,k$. Construct a grid $A$ with size $n \times n$ consisting of integers $0$ and $1$. The very important condition should be satisfied: the sum of all elements in the grid is exactly $k$. In other words, the number of $1$ in the grid is equal to $k$.

Let's define:  $A_{i,j}$ as the integer in the $i$-th row and the $j$-th column.  $R_i = A_{i,1}+A_{i,2}+...+A_{i,n}$ (for all $1 \le i \le n$).  $C_j = A_{1,j}+A_{2,j}+...+A_{n,j}$ (for all $1 \le j \le n$).  In other words, $R_i$ are row sums and $C_j$ are column sums of the grid $A$.  For the grid $A$ let's define the value $f(A) = (\max(R)-\min(R))^2 + (\max(C)-\min(C))^2$ (here for an integer sequence $X$ we define $\max(X)$ as the maximum value in $X$ and $\min(X)$ as the minimum value in $X$).

Find any grid $A$, which satisfies the following condition. Among such grids find any, for which the value $f(A)$ is the minimum possible. Among such tables, you can find any.

-----Input-----

The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 100$) — the number of test cases. Next $t$ lines contain descriptions of test cases.

For each test case the only line contains two integers $n$, $k$ $(1 \le n \le 300, 0 \le k \le n^2)$.

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

-----Output-----

For each test case, firstly print the minimum possible value of $f(A)$ among all tables, for which the condition is satisfied.

After that, print $n$ lines contain $n$ characters each. The $j$-th character in the $i$-th line should be equal to $A_{i,j}$.

If there are multiple answers you can print any.

-----Example-----
Input
4
2 2
3 8
1 0
4 16

Output
0
10
01
2
111
111
101
0
0
0
1111
1111
1111
1111

-----Note-----

In the first test case, the sum of all elements in the grid is equal to $2$, so the condition is satisfied. $R_1 = 1, R_2 = 1$ and $C_1 = 1, C_2 = 1$. Then, $f(A)...

t=int(input())
for _ in range(t):
    n,k=map(int,input().split())
    board=[[0]*n for _ in range(n)]
    cnt=0
    for i in range(n):
        for j in range(n):
            if cnt==k:
                break
            board[(j+i)%n][j]=1
            cnt+=1
        if cnt==k:
            break
    if k%n==0:
        print(0)
    else:
        maxs=(k+n-1)//n
        mins=k//n
        print(2*((maxs-mins)**2))
    for i in range(n):
        print(''.join(map(str,board[i])))


Solve in Python:
A manufacturing project consists of exactly $K$ tasks. The board overviewing the project wants to hire $K$ teams of workers — one for each task. All teams begin working simultaneously.
Obviously, there must be at least one person in each team. For a team of $A$ workers, it takes exactly $A$ days to complete the task they are hired for. Each team acts independently, unaware of the status of other teams (whether they have completed their tasks or not), and submits their result for approval on the $A$-th day.
However, the board approves the project only if all $K$ teams complete their tasks on the same day — it rejects everything submitted on any other day. The day after a team finds out that its result was rejected, it resumes work on the same task afresh. Therefore, as long as a team of $A$ workers keeps getting rejected, it submits a new result of their task for approval on the $A$-th, $2A$-th, $3A$-th day etc.
The board wants to hire workers in such a way that it takes exactly $X$ days to complete the project. Find the smallest number of workers it needs to hire.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains two space-separated integers $K$ and $X$.

-----Output-----
For each test case, print a single line containing one integer — the smallest required number of workers.

-----Constraints-----
- $1 \le T \le 40$
- $2 \le K, X \le 10^6$

-----Example Input-----
2
2 3
2 6

-----Example Output-----
4
5

-----Explanation-----
Example case 1: We can hire a team of $3$ workers for task $1$ and $1$ worker for task $2$. The one-man team working on task $2$ completes it and submits the result for approval on each day, but it is rejected on the first and second day. On the third day, the team working on task $1$ also completes their task, so the project gets approved after exactly $3$ days.
Example case 2: We can hire a team of $3$ workers for task $1$ and a...

import math

def primeFactors(n):
 d = {}
 while n % 2 == 0:
  n = n // 2
  if 2 in d:
   d[2] += 1
  else:
   d[2] = 1
 for i in range(3,int(math.sqrt(n))+1,2):
  while n % i== 0:
   if i in d:
    d[i] += 1
   else:
    d[i] = 1
   n = n // i
 if n > 2:
  if n in d:
   d[n] += 1
  else:
   d[n] = 1

 return d

def get_all_combs(arr, left):
 nonlocal g
 if not left:
  g.append(sum(arr))
 else:
  new = left.pop()
  for i in range(len(arr)):
   newarr = arr.copy()
   newarr[i] *= new
   get_all_combs(newarr, left.copy())

for test in range(int(input())):
 k, x = list(map(int, input().split()))
 d = primeFactors(x)

 if k < len(d):
  p = [item**d[item] for item in d]
  xo = [1]*k
  g = []
  get_all_combs(xo, p)

  print(min(g))
  continue

 c2 = 0
 for item in d:
  c2 += item**d[item]
 diff = k - len(d)

 c2 += diff

 print(c2)


Solve in Python:
A marine themed rival site to Codewars has started. Codwars is advertising their website all over the internet using subdomains to hide or obfuscate their domain to trick people into clicking on their site.

Your task is to write a function that accepts a URL as a string and determines if it would result in an http request to codwars.com.

Function should return true for all urls in the codwars.com domain. All other URLs should return false.

The urls are all valid but may or may not contain http://, https:// at the beginning or subdirectories or querystrings at the end.

For additional confusion, directories in can be named "codwars.com" in a url with the codewars.com domain and vise versa. Also, a querystring may contain codewars.com or codwars.com for any other domain - it should still return true or false based on the domain of the URL and not the domain in the querystring. Subdomains can also add confusion: for example `http://codwars.com.codewars.com` is a valid URL in the codewars.com domain in the same way that `http://mail.google.com` is a valid URL within google.com

Urls will not necessarily have either codewars.com or codwars.com in them. The folks at Codwars aren't very good about remembering the contents of their paste buffers.

All urls contain domains with a single TLD; you need not worry about domains like company.co.uk.

```
findCodwars("codwars.com"); // true
findCodwars("https://subdomain.codwars.com/a/sub/directory?a=querystring"); // true
findCodwars("codewars.com"); // false
findCodwars("https://subdomain.codwars.codewars.com/a/sub/directory/codwars.com?a=querystring"); // false
```

import re
def find_codwars(url):
    print(url)
    if(re.search(r"codewars\.com[\?\/].+$",url) != None):
        return False
    return re.search(r"(?<!\w)(codwars\.com[\?\/].+$|codwars\.com$)",url) != None


Solve in Python:
A matrix B (consisting of integers) of dimension N × N is said to be good if there exists an array A (consisting of integers) such that B[i][j]  = |A[i] - A[j]|, where |x| denotes absolute value of integer x.
You are given a partially filled matrix B of dimension N × N. Q of the entries of this matrix are filled by either 0 or 1. You have to identify whether it is possible to fill the remaining entries of matrix B (the entries can be filled by any integer, not necessarily by 0 or 1) such that the resulting fully filled matrix B is good.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases.
The first line of each test case contains two space separated integers N, Q.
Each of the next Q lines contain three space separated integers i, j, val, which means that B[i][j] is filled with value val.

-----Output-----
For each test case, output "yes" or "no" (without quotes) in a single line corresponding to the answer of the problem.

-----Constraints-----
- 1 ≤ T ≤ 106
- 2 ≤ N ≤ 105
- 1 ≤ Q ≤ 106
- 1 ≤ i, j ≤ N
- 0 ≤ val ≤ 1
- Sum of each of N, Q over all test cases doesn't exceed 106

-----Subtasks-----
- Subtask #1 (40 points) 2 ≤ N ≤ 103, 1 ≤ Q ≤ 103, Sum of each of N, Q over all test cases doesn't exceed 104
- Subtask #2 (60 points) Original Constraints

-----Example-----
Input
4
2 2
1 1 0
1 2 1
2 3
1 1 0
1 2 1
2 1 0
3 2
2 2 0
2 3 1
3 3
1 2 1
2 3 1
1 3 1

Output
yes
no
yes
no

-----Explanation-----
Example 1. You can fill the entries of matrix B as follows.

0 1
1 0
This matrix corresponds to the array A = [1, 2].

Example 2. It is impossible to fill the remaining entries of matrix B such that the resulting matrix is good, as B[1][2] = 1 and B[2][1] = 0, which is impossible.

import sys
sys.setrecursionlimit(1000000)

mod = 10**9 + 7
ts = int(input())
while ts > 0:
 n,q = list(map(int,input().split()))
 ncc = n-1
 par = [i for i in range(n)]
 rank = [1]*n
 xor = [0]*n
 flag = 1

 def find(a):
  if par[a] == a:
   return a
  else:
   temp = find(par[a])
   xor[a]^=xor[par[a]]
   par[a] = temp
   return temp

 def union(a,b):
  a,b = find(a),find(b)
  if a ==b:
   return
  if rank[a] > rank[b]:
   par[b] = a

   rank[a]+=rank[b]
  elif rank[a] < rank[b]:
   par[a] = b
   rank[b]+=rank[a]
  else:
   par[b] = a
   rank[a]+=rank[b]
  par[b] =a

 for _ in range(q):

  a,b,x = list(map(int,input().split()))
  a-=1
  b-=1
  if flag == -1:
   continue
  para = find(a)
  parb = find(b)

  if para == parb and xor[a] ^ xor[b] != x:
   flag = -1
   continue
   # print("no")

  if para != parb:
   if rank[para] < rank[parb]:
    xor[para] = xor[a] ^ xor[b] ^ x
    par[para] = parb
    rank[parb]+=rank[para]
   else:
    xor[parb] = xor[a] ^ xor[b] ^ x
    par[parb] = para
    rank[para]+=rank[parb]
   ncc-=1

 if flag != -1:
  print("yes")
 else:
  print("no")

 ts-=1


Solve in Python:
A message containing letters from A-Z is being encoded to numbers using the following mapping:

'A' -> 1
'B' -> 2
...
'Z' -> 26

Given a non-empty string containing only digits, determine the total number of ways to decode it.

Example 1:

Input: "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (12).

Example 2:

Input: "226"
Output: 3
Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).

class Solution:
     def numDecodings(self, s):
         """
         :type s: str
         :rtype: int
         """
         alphabet = 'abcdefghijklmnopqrstuvwxyz'
         char_code = {k:str(v) for k, v in zip(alphabet, list(range(1, 27)))}
         code_char = {v:k for k, v in list(char_code.items())}
         def numDecodingsHelper(s, hist={}):
             if not s: return 0
             if len(s) == 1: return 1 if s in code_char else 0
             if len(s) == 2:
                 tmp = 1 if s in code_char else 0
                 return tmp + numDecodingsHelper(s[0]) * numDecodingsHelper(s[1])
             if s[1:] not in hist:
                 hist[s[1:]] = numDecodingsHelper(s[1:], hist)
             current1 = hist[s[1:]] if s[:1] in code_char else 0
             if s[2:] not in hist:
                 hist[s[2:]] = numDecodingsHelper(s[2:], hist)
             current2 = hist[s[2:]] if s[:2] in code_char else 0
             return current1 + current2
         return numDecodingsHelper(s, {})


Solve in Python:
A move consists of taking a point (x, y) and transforming it to either (x, x+y) or (x+y, y).

Given a starting point (sx, sy) and a target point (tx, ty), return True if and only if a sequence of moves exists to transform the point (sx, sy) to (tx, ty). Otherwise, return False.

Examples:
Input: sx = 1, sy = 1, tx = 3, ty = 5
Output: True
Explanation:
One series of moves that transforms the starting point to the target is:
(1, 1) -> (1, 2)
(1, 2) -> (3, 2)
(3, 2) -> (3, 5)

Input: sx = 1, sy = 1, tx = 2, ty = 2
Output: False

Input: sx = 1, sy = 1, tx = 1, ty = 1
Output: True

Note:

       sx, sy, tx, ty will all be integers in the range [1, 10^9].

class Solution:
     def maxChunksToSorted(self, arr):
         """
         :type arr: List[int]
         :rtype: int
         """
         cnt = 0
         max_curr = -1
         for i in range(len(arr)):
             max_curr = max(max_curr, arr[i])
             if max_curr == i:
                 cnt += 1
         return cnt


Solve in Python:
A nested list (or *array* in JavaScript) is a list that apears as a value inside another list,
```python
[item, item, [item, item], item]
```
in the above list, [item, item] is a nested list.

Your goal is to write a function that determines the depth of the deepest nested list within a given list.
return 1 if there are no nested lists.
The list passed to your function can contain any data types.

A few examples:

```python
list_depth([True])
return 1

list_depth([])
return 1

list_depth([2, "yes", [True, False]])
return 2

list_depth([1, [2, [3, [4, [5, [6], 5], 4], 3], 2], 1])
return 6

list_depth([2.0, [2, 0], 3.7, [3, 7], 6.7, [6, 7]])
return 2
```

def list_depth(l):
  return max(1 + list_depth(x) if type(x) is list else 1 for x in l) if l else 1


Solve in Python:
A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers p_{i}, a_{i} and b_{i}, where p_{i} is the price of the i-th t-shirt, a_{i} is front color of the i-th t-shirt and b_{i} is back color of the i-th t-shirt. All values p_{i} are distinct, and values a_{i} and b_{i} are integers from 1 to 3.

m buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the j-th buyer we know his favorite color c_{j}.

A buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served.

You are to compute the prices each buyer will pay for t-shirts.

-----Input-----

The first line contains single integer n (1 ≤ n ≤ 200 000) — the number of t-shirts.

The following line contains sequence of integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ 1 000 000 000), where p_{i} equals to the price of the i-th t-shirt.

The following line contains sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 3), where a_{i} equals to the front color of the i-th t-shirt.

The following line contains sequence of integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 3), where b_{i} equals to the back color of the i-th t-shirt.

The next line contains single integer m (1 ≤ m ≤ 200 000) — the number of buyers.

The following line contains sequence c_1, c_2, ..., c_{m} (1 ≤ c_{j} ≤ 3), where c_{j} equals to the favorite color of the j-th buyer. The buyers will come to the shop in the order they are given in the input. Each buyer is served only after the previous one is served.

-----Output-----

Print to the first line m integers — the j-th integer should be equal to the price of the t-shirt which the j-th buyer will buy. If the j-th buyer won't buy anything, print -1.

-----Examples-----
Input
5
300 200 400...

import collections
def mp():  return map(int,input().split())
def lt():  return list(map(int,input().split()))
def pt(x):  print(x)
def ip():  return input()
def it():  return int(input())
def sl(x):  return [t for t in x]
def spl(x): return x.split()
def aj(liste, item): liste.append(item)
def bin(x):  return "{0:b}".format(x)
def listring(l): return ' '.join([str(x) for x in l])
def ptlist(l): print(' '.join([str(x) for x in l]))

n = it()
p = lt()
a = lt()
b = lt()
m = it()
c = lt()

shirt = list(zip(p,a,b))
shirt.sort()
pointer = [-1,0,0,0]
l = []
for i in range(m):
    cl = c[i]
    while pointer[cl] < n and (shirt[pointer[cl]] == None or cl not in shirt[pointer[cl]][1:]):
        pointer[cl] += 1
    if pointer[cl] == n:
        l.append(-1)
    else:
        l.append(shirt[pointer[cl]][0])
        shirt[pointer[cl]] = None
ptlist(l)


Solve in Python:
A new school year is approaching, which also means students will be taking tests.

The tests in this kata are to be graded in different ways. A certain number of points will be given for each correct answer and a certain number of points will be deducted for each incorrect answer. For ommitted answers, points will either be awarded, deducted, or no points will be given at all.

Return the number of points someone has scored on varying tests of different lengths.

The given parameters will be:

* An array containing a series of `0`s, `1`s, and `2`s, where `0` is a correct answer, `1` is an omitted answer, and `2` is an incorrect answer.
* The points awarded for correct answers
* The points awarded for omitted answers (note that this may be negative)
* The points **deducted** for incorrect answers (hint: this value has to be subtracted)

**Note:**
The input will always be valid (an array and three numbers)

## Examples

\#1:
```
[0, 0, 0, 0, 2, 1, 0], 2, 0, 1  -->  9
```
because:
* 5 correct answers: `5*2 = 10`
* 1 omitted answer: `1*0 = 0`
* 1 wrong answer: `1*1 = 1`

which is: `10 + 0 - 1 = 9`

\#2:
```
[0, 1, 0, 0, 2, 1, 0, 2, 2, 1], 3, -1, 2)  -->  3
```
because: `4*3 + 3*-1 - 3*2 = 3`

def score_test(tests, right, omit, wrong):
    points = (right, omit, -wrong)
    return sum(points[test] for test in tests)


Solve in Python:
A new task for you!

You have to create a method, that corrects a given time string.
There was a problem in addition, so many of the time strings are broken.
Time-Format is european. So from "00:00:00" to "23:59:59".

Some examples:

"09:10:01" -> "09:10:01"
"11:70:10" -> "12:10:10"
"19:99:99" -> "20:40:39"
"24:01:01" -> "00:01:01"

If the input-string is null or empty return exactly this value! (empty string for C++)
If the time-string-format is invalid, return null. (empty string for C++)

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

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

from re import match
def time_correct(t):
    if not t:return t
    if match("\d{2}:\d{2}:\d{2}",t):
        hour,minute,second=map(int,t.split(":"))
        m,second=divmod(second,60)
        minute+=m
        h,minute=divmod(minute,60)
        hour=(hour+h)%24
        return f"{hour:0>2d}:{minute:0>2d}:{second:0>2d}"


Solve in Python:
A number K$K$ is said to be magical if it can be represented as a power of 2 only.That is K$K$=2x$2^{x}$ for some natural number x$x$.
Given a string of digits S$S$ of length N$N$, Let P be a valid arrangement of S.
By valid arrangement we mean that it should not have any leading zeroes.
Find the sum of all such distinct Pi's, which, when treated as a number is magical.
Two arrangements are said to be distinct, if there is atleast one index where they differ.
As the sum can be very large, print the sum modulo 109+7$10^{9}+7$.

-----Input:-----
-The first line of the input contains a single integer T$T$ denoting the number of test cases.
-Only line of each test case contains a string S$S$ of length N$N$, consisting only of digits between 0 to 9.

-----Output:-----
For each test case, print a single integer denoting the sum of all such magical Pi′s$Pi's$ modulo 109+7$10^{9}+7$.
If no such Pi$Pi$ exists print "-1".

-----Constraints-----
- 1≤T≤1000$1 \leq T \leq 1000$
- 2≤N≤1000$2 \leq N \leq 1000$
- String only consists of digits between 0 to 9, both inclusive.

-----Subtasks-----
- 10 points : 1≤N≤5$1 \leq N \leq 5$
- 40 points : 1≤N≤100$1 \leq N \leq 100$
- 50 points : Original Constraints

-----Sample Input:-----
2
35566

31

-----Sample Output:-----
65536

-1

-----EXPLANATION:-----
Only arrangement is 65536.
No arrangement of 31 gives us a power of two.

from math import log2, ceil
MOD = int(1e9 + 7)
srt = lambda s: ''.join(sorted(s))
for _ in range(int(input())):
    s = srt(input())
    res = -1
    for p in range(ceil(log2(int(s))), int(log2(int(s[::-1]))) + 1):
        if int(srt(str(pow(2, p)))) == int(s):
            if res == -1: res = 0
            res = (res + pow(2, p, MOD)) % MOD
    print(res)


Solve in Python:
A number `n` is called `prime happy` if there is at least one prime less than `n` and the `sum of all primes less than n` is evenly divisible by `n`. Write `isPrimeHappy(n)` which returns `true` if `n` is `prime happy` else `false`.

def isPrime(n):
    for i in range(2,int(n**.5)+1):
        if n%i == 0:
            return False
    return True
def is_prime_happy(n):
    sum = 0
    for i in range(2,n):
        if isPrime(i):
            sum += i
    if sum > 0 and not sum%n:
        return True
    return False


Solve in Python:
A number is self-descriptive when the n'th digit describes the amount n appears in the number.

E.g. 21200:

There are two 0's in the number, so the first digit is 2.

There is one 1 in the number, so the second digit is 1.

There are two 2's in the number, so the third digit is 2.

There are no 3's in the number, so the fourth digit is 0.

There are no 4's in the number, so the fifth digit is 0

Numbers can be of any length up to 9 digits and are only full integers. For a given number derive a function ```selfDescriptive(num)``` that returns; ```true``` if the number is self-descriptive or ```false``` if the number is not.

def self_descriptive(num):
  from collections import Counter

  snum = str(num)
  c = Counter(snum)
  return all(int(d) == c[str(i)] for i, d in enumerate(snum))


Solve in Python:
A number is simply made up of digits.
The number 1256 is made up of the digits 1, 2, 5, and 6.
For 1256 there are 24 distinct permutations of the digits:
1256, 1265, 1625, 1652, 1562, 1526, 2156, 2165, 2615, 2651, 2561, 2516,
5126, 5162, 5216, 5261, 5621, 5612, 6125, 6152, 6251, 6215, 6521, 6512.

Your goal is to write a program that takes a number, n, and returns the average value of all distinct permutations of the digits in n.  Your answer should be rounded to the nearest integer. For the example above the return value would be 3889. *

  n will never be negative

A few examples:
```python
permutation_average(2)
return 2

permutation_average(25)
>>> 25 + 52 = 77
>>> 77 / 2 = 38.5
return 39 *

permutation_average(20)
>>> 20 + 02 = 22
>>> 22 / 2 = 11
return 11

permutation_average(737)
>>> 737 + 377 + 773 = 1887
>>> 1887 / 3 = 629
return 629

```

Note: Your program should be able to handle numbers up to 6 digits long
~~~if:python
\* Python version 3 and above uses Banker Rounding so the expected values for those tests would be 3888 and 38 respectively
~~~
~~~if-not:python
\* ignore these marks, they're for Python only
~~~

def permutation_average(n):
    n = str(n)
    avg = sum(map(int, n)) / len(n)
    return round(avg * int("1" * len(n)))


Solve in Python:
A number is ternary if it contains only digits $0$, $1$ and $2$. For example, the following numbers are ternary: $1022$, $11$, $21$, $2002$.

You are given a long ternary number $x$. The first (leftmost) digit of $x$ is guaranteed to be $2$, the other digits of $x$ can be $0$, $1$ or $2$.

Let's define the ternary XOR operation $\odot$ of two ternary numbers $a$ and $b$ (both of length $n$) as a number $c = a \odot b$ of length $n$, where $c_i = (a_i + b_i) \% 3$ (where $\%$ is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by $3$. For example, $10222 \odot 11021 = 21210$.

Your task is to find such ternary numbers $a$ and $b$ both of length $n$ and both without leading zeros that $a \odot b = x$ and $max(a, b)$ is the minimum possible.

You have to answer $t$ independent test cases.

-----Input-----

The first line of the input contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Then $t$ test cases follow. The first line of the test case contains one integer $n$ ($1 \le n \le 5 \cdot 10^4$) — the length of $x$. The second line of the test case contains ternary number $x$ consisting of $n$ digits $0, 1$ or $2$. It is guaranteed that the first digit of $x$ is $2$. It is guaranteed that the sum of $n$ over all test cases does not exceed $5 \cdot 10^4$ ($\sum n \le 5 \cdot 10^4$).

-----Output-----

For each test case, print the answer — two ternary integers $a$ and $b$ both of length $n$ and both without leading zeros such that $a \odot b = x$ and $max(a, b)$ is the minimum possible. If there are several answers, you can print any.

-----Example-----
Input
4
5
22222
5
21211
1
2
9
220222021

Output
11111
11111
11000
10211
1
1
110111011
110111010

tc = int(input())
for _ in range(tc):
    n = int(input())
    s = input()
    a = b = '1'
    flag = None
    for i in s[1:]:
        if int(i) % 2 == 0 and not flag:
            num = int(i) // 2
            a += str(num)
            b += str(num)
        else:
            num = int(i) // 2
            if not flag:
                a += str(num + 1)
                b += str(num)
                flag = True
            else:
                a += str(0)
                b += str(i)
    print(a, b, sep="\n")


Solve in Python:
A number m of the form 10x + y is divisible by 7 if and only if x − 2y is divisible by 7. In other words, subtract twice the last digit
from the number formed by the remaining digits. Continue to do this until a number known to be divisible or not by 7 is obtained;
you can stop when this number has *at most* 2 digits because you are supposed to know if a number of at most 2 digits is divisible by 7 or not.

The original number is divisible by 7 if and only if the last number obtained using this procedure is divisible by 7.

Examples:

1 - `m = 371 -> 37 − (2×1) -> 37 − 2 = 35` ; thus, since 35 is divisible by 7, 371 is divisible by 7.

The number of steps to get the result is `1`.

2 - `m = 1603 -> 160 - (2 x 3) -> 154 -> 15 - 8 = 7` and 7 is divisible by 7.

3 - `m = 372 -> 37 − (2×2) -> 37 − 4 = 33` ; thus, since 33 is not divisible by 7, 372 is not divisible by 7.

The number of steps to get the result is `1`.

4 - `m = 477557101->47755708->4775554->477547->47740->4774->469->28` and 28 is divisible by 7, so is 477557101.

The number of steps is 7.

# Task:
Your task is to return to the function ```seven(m)``` (m integer >= 0) an array (or a pair, depending on the language) of numbers,
the first being the *last* number `m` with at most 2 digits obtained by your function (this last `m` will be divisible or not by 7), the second one being the number of steps to get the result.

## Forth Note:
Return on the stack `number-of-steps, last-number-m-with-at-most-2-digits `

## Examples:
```
seven(371) should return [35, 1]
seven(1603) should return [7, 2]
seven(477557101) should return [28, 7]
```

def seven(m):
    ctr = 0
    while m >= 100:
        m = m // 10 - 2*(m % 10)
        ctr += 1
    return (m, ctr)


Solve in Python:
A pair of numbers has a unique LCM but a single number can be the LCM of more than one possible
pairs. For example `12` is the LCM of `(1, 12), (2, 12), (3,4)` etc. For a given positive integer N, the number of different integer pairs with LCM is equal to N can be called the LCM cardinality of that number N. In this kata your job is to find out the LCM cardinality of a number.

def lcm_cardinality(n):
    res = 1
    for i in [2] + list(range(3, int(n**0.5)+1, 2)):
        count = 0
        while not n%i: n, count = n//i, count+1
        res *= 2*count + 1
    if n > 1: res *= 3
    return (res + 1) // 2


Solve in Python:
A palindrome is a series of characters that read the same forwards as backwards such as "hannah", "racecar" and "lol".

For this Kata you need to write a function that takes a string of characters and returns the length, as an integer value, of longest alphanumeric palindrome that could be made by combining the characters in any order but using each character only once. The function should not be case sensitive.

For example if passed "Hannah" it should return 6 and if passed "aabbcc_yYx_" it should return 9 because one possible palindrome would be "abcyxycba".

from collections import Counter
from string import ascii_letters, digits

def longest_palindrome(data):
    cnt = Counter([d for d in data.lower() if d in ascii_letters + digits])
    even = sum([n for n in list(cnt.values()) if n % 2 == 0 ])
    odd = sorted( [n for n in list(cnt.values()) if n % 2 != 0] )[::-1]
    if len(odd) == 0:
        ans = even
    if len(odd) == 1:
        ans = even + odd[0]
    if len(odd) >  1:
        ans = even + odd[0] + sum([n-1 for n in odd[1:]])

    return ans


Solve in Python:
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are:

2332
110011
54322345

You'll be given 2 numbers as arguments: ```(num,s)```.  Write a function which returns an array of ```s``` number of numerical palindromes that come after ```num```. If ```num``` is a palindrome itself, it should be included in the count.

Return "Not valid" instead if any one of the inputs is not an integer or is less than 0.

For this kata, single digit numbers will NOT be considered numerical palindromes.

```
palindrome(6,4) => [11,22,33,44]
palindrome(59,3) => [66,77,88]
palindrome(101,2) => [101,111]
palindrome("15651",5) => "Not valid"
palindrome(1221,"8") => "Not valid"
```

```Haskell

In Haskell, the return type is a Maybe which returns Nothing if either of the inputs is negative."
```

Other Kata in this Series:
Numerical Palindrome #1
Numerical Palindrome #1.5
Numerical Palindrome #2
Numerical Palindrome #3
Numerical Palindrome #3.5
Numerical Palindrome #4
Numerical Palindrome #5

def palindrome(num,s):
    if isinstance(num,str) or num<0 or isinstance(s,str) or s<0:
        return 'Not valid'
    t = []
    i=1
    while i<=s:
        if pali(num):
            t.append(num)
            i+=1
        num+=1
    return t
def pali(n):
    if n>10 and str(n)==str(n)[::-1]:
        return True
    return False


Solve in Python:
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are:

2332
110011
54322345

For a given number `num`, write a function to test if it's a numerical palindrome or not and return a boolean (true if it is and false if not).

```if-not:haskell
Return "Not valid" if the input is not an integer or less than `0`.
```
```if:haskell
Return `Nothing` if the input is less than `0` and `Just True` or `Just False` otherwise.
```

Other Kata in this Series:
Numerical Palindrome #1
Numerical Palindrome #1.5
Numerical Palindrome #2
Numerical Palindrome #3
Numerical Palindrome #3.5
Numerical Palindrome #4
Numerical Palindrome #5

def palindrome(a):
    if type(a)==int:
        if a>0:
            a=str(a)
            b=a[::-1]
            if a==b:
                return True
            else:
                return False
        else:
            return "Not valid"
    else:
        return "Not valid"


Solve in Python:
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are:

* 232
* 110011
* 54322345

Complete the function to test if the given number (`num`) **can be rearranged** to form a numerical palindrome or not. Return a boolean (`true` if it can be rearranged to a palindrome, and `false` if it cannot). Return `"Not valid"` if the input is not an integer or is less than 0.

For this kata, single digit numbers are **NOT** considered numerical palindromes.

## Examples

```
5        =>  false
2121     =>  true
1331     =>  true
3357665  =>  true
1294     =>  false
"109982" =>  "Not valid"
-42      =>  "Not valid"
```

def palindrome(n):
    if type(n) != int or n < 0:
        return "Not valid"
    s = str(n)
    return n > 10 and sum(s.count(d) % 2 for d in set(s)) < 2


Solve in Python:
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are:

2332
110011
54322345

For a given number ```num```, return its closest numerical palindrome which can either be smaller or larger than ```num```. If there are 2 possible values, the larger value should be returned. If ```num``` is a numerical palindrome itself, return it.

For this kata, single digit numbers will NOT be considered numerical palindromes.

Also, you know the drill - be sure to return "Not valid" if the input is not an integer or is less than 0.

```
palindrome(8) => 11
palindrome(281) => 282
palindrome(1029) => 1001
palindrome(1221) => 1221
palindrome("1221") => "Not valid"

```

```Haskell
In Haskell the function should return a Maybe Int with Nothing for cases where the argument is less than zero.
```
Other Kata in this Series:
Numerical Palindrome #1
Numerical Palindrome #1.5
Numerical Palindrome #2
Numerical Palindrome #3
Numerical Palindrome #3.5
Numerical Palindrome #4
Numerical Palindrome #5

def palindrome(num):
    if type(num) is not int or num < 0:
        return "Not valid"
    else:
        c =0
        for i in range(num,num**2):
            if is_pal(i):
                return i
            elif is_pal(i-c):
                return i-c
            else:
                c +=2

def is_pal(n):
    return n > 10 and n == int(str(n)[::-1])


Solve in Python:
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are:

2332
110011
54322345

For a given number ```num```, write a function which returns the number of numerical palindromes within each number. For this kata, single digit numbers will NOT be considered numerical palindromes.

Return "Not valid" if the input is not an integer or is less than 0.

```
palindrome(5) => 0
palindrome(1221) => 2
palindrome(141221001) => 5
palindrome(1294) => 0
palindrome("1221") => "Not valid"

```

```Haskell
In Haskell, return a Maybe Int with Nothing for negative numbers.
```

Other Kata in this Series:
Numerical Palindrome #1
Numerical Palindrome #1.5
Numerical Palindrome #2
Numerical Palindrome #3
Numerical Palindrome #3.5
Numerical Palindrome #4
Numerical Palindrome #5

def palindrome(num):
    if not isinstance(num, int) or num < 0:
        return "Not valid"
    s = str(num)
    l = len(s)
    return sum(1 for p in (s[i:i+1+j] for j in range(1, l) for i in range(l-j)) if p == p[::-1])


Solve in Python:
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are:

2332
110011
54322345

For this kata, single digit numbers will not be considered numerical palindromes.

For a given number ```num```, write a function to test if the number contains a numerical palindrome or not and return a boolean (true if it does and false if does not). Return "Not valid" if the input is not an integer or is less than 0.

Note: Palindromes should be found without permutating ```num```.

```
palindrome(5) => false
palindrome(1221) => true
palindrome(141221001) => true
palindrome(1215) => true
palindrome(1294) => false
palindrome("109982") => "Not valid"
```

import re

def palindrome(num):
    if not (isinstance(num, int) and num > 0):
        return 'Not valid'
    return bool(re.search(r'(.)\1|(.).\2', str(num)))


Solve in Python:
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are: `2332, 110011, 54322345`

For a given number ```num```, write a function which returns an array of all the numerical palindromes contained within each number. The array should be sorted in ascending order and any duplicates should be removed.

In this kata, single digit numbers and numbers which start or end with zeros (such as `010` and `00`) are **NOT** considered valid numerical palindromes.

If `num` contains no valid palindromes, return `"No palindromes found"`.
Otherwise, return `"Not valid"` if the input is not an integer or is less than `0`.

## Examples

```
palindrome(1221)      =>  [22, 1221]
palindrome(34322122)  =>  [22, 212, 343, 22122]
palindrome(1001331)   =>  [33, 1001, 1331]
palindrome(1294)      =>  "No palindromes found"
palindrome("1221")    =>  "Not valid"
```

---

### Other Kata in this Series:

Numerical Palindrome #1
Numerical Palindrome #1.5
Numerical Palindrome #2
Numerical Palindrome #3
Numerical Palindrome #3.5
Numerical Palindrome #4
Numerical Palindrome #5

def palindrome(num):
    if not (isinstance(num, int) and num > 0):
        return 'Not valid'
    s = str(num)
    result = set()
    for i in range(0, len(s)-1):
        for j in range(i+2, len(s)+1):
            if s[i] == '0':
                continue
            x = s[i:j]
            if x == x[::-1]:
                result.add(int(x))
    if result:
        return sorted(result)
    return 'No palindromes found'


Solve in Python:
A password is considered strong if below conditions are all met:

 It has at least 6 characters and at most 20 characters.
 It must contain at least one lowercase letter, at least one uppercase letter, and at least one digit.
 It must NOT contain three repeating characters in a row ("...aaa..." is weak, but "...aa...a..." is strong, assuming other conditions are met).

Write a function strongPasswordChecker(s), that takes a string s as input, and return the MINIMUM change required to make s a strong password. If s is already strong, return 0.

Insertion, deletion or replace of any one character are all considered as one change.

class Solution:
     def strongPasswordChecker(self, s):
         """
         :type s: str
         :rtype: int
         """
         def length_requirement(password):
             length = len(password)
             # positive means addition, negative means deletion
             if length < 6:
                 return 6 - length
             elif length > 20:
                 return 20 - length
             else:
                 return 0

         def category_requirement(password):
             # input
             string = set(password)
             lowercase = set('qwertyuiopasdfghjklzxcvbnm')
             uppercase = set('QWERTYUIOPASDFGHJKLZXCVBNM')
             digit = set('1234567890')
             condition = [lowercase, uppercase, digit]
             # output positive for addition
             missing = 0
             for s in condition:
                 if not s & string:
                     missing += 1
             return missing

         def repeat_requirement(password):
             # store the repeated character and counts its occurrence
             count = 1
             repeat = None
             weak_pair = []
             for c in password:
                 if c == repeat:
                     # the same character
                     count += 1
                 else:
                     # new character
                     if count >= 3:
                         weak_pair.append([repeat, count])
                     count = 1
                     repeat = c
             # add last pair
             if count >= 3:
                 weak_pair.append([repeat, count])
             # length of 'aaaaaa' divide by 3 returns the time of change
             change = 0
             one = 0
             two = 0
             for _, length in weak_pair:
                 change += length // 3
                 if length % 3 == 0:
                     one += 1
                 elif length % 3 == 1:
                     two += 1
             return change, one, two

         def...


Solve in Python:
A peak element is an element that is greater than its neighbors.

Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.

The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.

You may imagine that nums[-1] = nums[n] = -∞.

Example 1:

Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.

Example 2:

Input: nums = [1,2,1,3,5,6,4]
Output: 1 or 5
Explanation: Your function can return either index number 1 where the peak element is 2,
             or index number 5 where the peak element is 6.

Note:

Your solution should be in logarithmic complexity.

class Solution:
     def findPeakElement(self, nums):
         """
         :type nums: List[int]
         :rtype: int
         """
         if len(nums) == 1:
             return 0
         left, right = 0, len(nums) - 1
         length = len(nums)
         while left + 1 < right:
             mid = (left + right) // 2
             if mid == 0:
                 if nums[mid] > nums[mid + 1]:
                     return 0
                 else:
                     left = mid + 1
             elif mid == length - 1:
                 if nums[-1] > nums[-2]:
                     return mid
                 else:
                     right = mid - 1
             elif nums[mid] > nums[mid - 1] and nums[mid] > nums[mid + 1]:
                 return mid
             elif nums[mid] < nums[mid - 1] and nums[mid] < nums[mid + 1]:
                 right = mid - 1
             elif nums[mid] > nums[mid + 1]:
                 right = mid - 1
             else:
                 left = mid + 1
         for idx in range(left, right + 1):
             if idx == 0 and nums[idx] > nums[idx + 1]:
                 return 0
             if idx == length - 1 and nums[-1] > nums[-2]:
                 return idx
             if nums[idx] > nums[idx - 1] and nums[idx] > nums[idx + 1]:
                 return idx