Solve in Python:
Let's pretend your company just hired your friend from college and paid you a referral bonus. Awesome! To celebrate, you're taking your team out to the terrible dive bar next door and using the referral bonus to buy, and build, the largest three-dimensional beer can pyramid you can. And then probably drink those beers, because let's pretend it's Friday too.

A beer can pyramid will square the number of cans in each level - 1 can in the top level, 4 in the second, 9 in the next, 16, 25...

Complete the beeramid function to return the number of **complete** levels of a beer can pyramid you can make, given the parameters of:

1) your referral bonus, and

2) the price of a beer can

For example:

def beeramid(bonus, price):
    i = 0
    while bonus > 0:
        i += 1
        bonus -= price * i**2
        if bonus < 0: i -= 1
    return i


Solve in Python:
Let's say take 2 strings, A and B, and define the similarity of the strings to be the length of the longest prefix common to both strings. For example, the similarity of strings `abc` and `abd` is 2, while the similarity of strings `aaa` and `aaab` is 3.

write a function that calculates the sum of similarities of a string S with each of it's **suffixes**.

```python
string_suffix('ababaa') => returns 11
string_suffix('abc') => returns 3
```

Explanation:

In the first case, the suffixes of the string are `ababaa`, `babaa`, `abaa`, `baa`, `aa` and `a`. The similarities of each of these strings with the string `ababaa` are 6,0,3,0,1,1 respectively. Thus the answer is 6 + 0 + 3 + 0 + 1 + 1 = 11.

For the second case, the answer is simply 3 + 0 + 0 = 3.

Note : Each string will have at least one character - no need to check for empty strings :)

def string_suffix(s):
  sim = lambda s1, s2: ([c1 == c2 for c1, c2 in zip(s1, s2)]+[False]).index(False)
  return sum(sim(s, s[i:]) for i in range(len(s)))


Solve in Python:
Let's say that in a hypothetical platform that resembles Codewars there is a clan with 2 warriors. The 2nd one in ranking (lets call him **D**) wants to at least reach the honor score of his ally (lets call her **M**).
*(Let's say that there is no antagonism here, he just wants to prove his ally that she should be proud to have him in the clan and sees this as the only way to achieve it! :P )*

Your task is to help **D** by providing him with the **quickest path** to reach **M**'s honor score.

In this hypothetical platform there are 2 kinds of kata to be solved:
```
'2kyu' worth of 1 point
'1kyu' worth of 2 points
```

So if for example:
```
M has honor 11
D has honor 2
```
**D** could reach **M`s** honor by solving kata worth of `9`. He has many options to do this:
```
Solve 9 '2kyus' (9*1 -> 9) => Solve 9 kata
Solve 4 '1kyus' and 1 '2kyus' (4*2 + 1*1-> 9) => Solve 5 kata
Solve 2 '1kyus' and 5 '2kyus' (2*2 + 5*1 -> 9) => Solve 7 kata
etc etc...
```
The **quickest path** to reach the honor score is:
```
4 '1kyus' and 1 '2kyus' => Solve only 5 kata
```

Create a function `getHonorPath` that accepts 2 arguments `honorScore` & `targetHonorScore` with score integers of 2 warriors and returns an object with the **quickest path** for the first one to reach the 2nd's honor. For example:

```
getHonorPath(2, 11) should return { '1kyus': 4, '2kyus': 1 }
getHonorPath(20, 11) should return {}
```

**For the purpose of this kata you do not have to worry about any non-integer arguments for honor scores**

get_honor_path=lambda s,o:o>s and{'%skyus'%k:n for k,n in enumerate(divmod(o-s,2),1)}or{}


Solve in Python:
Let's say we have a number, `num`. Find the number of values of `n` such that: there exists `n` consecutive **positive** values that sum up to `num`. A positive number is `> 0`. `n` can also be 1.

```python
#Examples
num = 1
#1
return 1

num = 15
#15, (7, 8), (4, 5, 6), (1, 2, 3, 4, 5)
return 4

num = 48
#48, (15, 16, 17)
return 2

num = 97
#97, (48, 49)
return 2
```
The upper limit is `$10^8$`

from math import sqrt
def consecutive_sum(n):
    cnt = 0
    lim = int(sqrt(2 * n))
    m = 1
    while m <= lim:
        u = n / m + m / 2 + 0.5
        if int(u) == u:
            cnt += 1
        m += 1
    return cnt


Solve in Python:
Let's say you have a bunch of points, and you want to round them all up and calculate the area of the smallest polygon containing all of the points (nevermind why, you just want a challenge). What you're looking for is the area of the *convex hull* of these points. Here is an example, delimited in blue :

## Your task

Implement a function that will compute the area covered by the convex hull that can be formed from an array of points, the area being rounded to two decimal places. The points are given as `(x,y)`, like in an orthonormal coordinates system.

```python
points = [(0, 0), (0, 3), (4, 0)]
convex_hull_area(points) == 6.00
```

*Note* : In Python, the scipy module has a [ready made solution](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.ConvexHull.html) for this. Of course, if you use it here, you are lame.

*P. S.* : If you enjoy this kata, you may also like this one, which asks you to compute a convex hull, without finding its area.

import numpy as np

def slope(p1, p2):
    dx, dy = vectorize(p1, p2)
    return dy/dx if dx else float("inf")

def vectorize(p1, p2):         return [b-a for a,b in zip(p1, p2)]
def getArea  (p1, p2, p3):     return np.cross(vectorize(p1, p2), vectorize(p1, p3)) / 2
def isConcave(p1, pivot, p2):  return getArea(pivot, p1, p2) >= 0

def convex_hull_area(points):
    if len(points) < 3: return 0

    Z = min(points)                                                                      # Leftmost point in the graph (lowest if several ones at the same x)
    q = sorted( (pt for pt in points if pt != Z),
                key = lambda pt: (-slope(pt, Z), -np.linalg.norm(vectorize(Z, pt))))     # sorted points accordingly to the slope of the line formed by "pt" and "Z" (in reversed order)

    hull = [Z, q.pop()]                                                                  # Construct the convex hull (Graham Scan)
    while q:
        pt = q.pop()
        while len(hull) > 1 and isConcave(hull[-2], hull[-1], pt):
            hull.pop()
        hull.append(pt)

    area = sum( getArea(Z, hull[i], hull[i+1]) for i in range(1, len(hull)-1) )          # Calculate area of the hull by adding the area of all the triangles formed by 2 consecutive points in the hull and having Z as summit
    return round(area, 2)


Solve in Python:
Let's take an integer number, ``` start``` and let's do the iterative process described below:

- we take its digits and raise each of them to a certain power, ```n```, and add all those values up. (result = ```r1```)

- we repeat the same process with the value ```r1``` and so on, ```k``` times.

Let's do it with ```start = 420, n = 3, k = 5```

```
420 ---> 72 (= 4³ + 2³ + 0³) ---> 351 (= 7³ + 2³) ---> 153 ---> 153 ----> 153
```

We can observe that it took ```3``` steps to reach a cyclical pattern ```[153]```(```h = 3```). The length of this cyclical pattern is ```1```, ```patt_len```. The last term of our k operations is 153, ```last_term```

Now, ```start = 420, n = 4, k = 30```

```
420 ---> 272 ---> 2433 ---> 434 ---> 593 ---> 7267 --->
6114 ---> 1554 ---> 1507 ---> 3027 ---> 2498 ---> 10929 --->
13139 ---> 6725 ---> 4338 ---> 4514 ---> 1138 ---> 4179 ---> 9219 --->
13139 ---> 6725 ---> 4338 ---> 4514 ---> 1138 ---> 4179 ---> 9219 --->
13139 ---> 6725 ---> 4338 ---> 4514 ---> 1138 ---> 4179 ---> 9219......
```

In this example we can observe that the cyclical pattern (```cyc_patt_arr```) is ```[13139, 6725, 4338, 4514, 1138, 4179, 9219]``` with a length of ```7```, (```patt_len = 7```), and it took ```12``` steps (```h = 12```) to reach the cyclical pattern. The last term after doing ```30``` operations is ```1138```

Make the function ```sum_pow_dig_seq()```, that receives the arguments in the order shown below with the corresponding output:
```python
sum_pow_dig_seq(start, n, k) ---> [h, cyc_patt_arr, patt_len, last_term]
```

For our given examples,
```python
sum_pow_dig_seq(420, 3, 5) == [3, [153], 1, 153]

sum_pow_dig_seq(420, 4, 30) == [12, [13139, 6725, 4338, 4514, 1138, 4179, 9219], 7, 1138]
```

Constraints for tests:
```
500 ≤ start ≤ 8000
2 ≤ n ≤ 9
100 * n ≤ k ≤ 200 * n
```
Do your best!

def sum_pow_dig_seq(n, e, k):
    path = [n]
    while True:
        n = sum(int(d)**e for d in str(n))
        if n in path: break
        path.append(n)
    h = path.index(n)
    loop = path[h:]
    return [h, loop, len(loop), loop[(k-h)%len(loop)]]


Solve in Python:
Lets play some Pong!

![pong](http://gifimage.net/wp-content/uploads/2017/08/pong-gif-3.gif)

For those who don't know what Pong is, it is a simple arcade game where two players can move their paddles to hit a ball towards the opponent's side of the screen, gaining a point for each opponent's miss. You can read more about it [here](https://en.wikipedia.org/wiki/Pong).

___

# Task:

You must finish the `Pong` class. It has a constructor which accepts the `maximum score` a player can get throughout the game, and a method called `play`. This method determines whether the current player hit the ball or not, i.e. if the paddle is at the sufficient height to hit it back. There're 4 possible outcomes: player successfully hits the ball back, player misses the ball, player misses the ball **and his opponent reaches the maximum score winning the game**, either player tries to hit a ball despite the game being over. You can see the input and output description in detail below.

### "Play" method input:

* ball position - The Y coordinate of the ball
* player position - The Y coordinate of the centre(!) of the current player's paddle

### "Play" method output:

One of the following strings:

* `"Player X has hit the ball!"` - If the ball "hits" the paddle
* `"Player X has missed the ball!"` - If the ball is above/below the paddle
* `"Player X has won the game!"` - If one of the players has reached the maximum score
* `"Game Over!"` - If the game has ended but either player still hits the ball

### Important notes:

* Players take turns hitting the ball, always starting the game with the Player 1.
* The paddles are `7` pixels in height.
* The ball is `1` pixel in height.

___

## Example

class Pong:
    def __init__(self, win):
        self.win = win
        self.turn = -1
        self.scores = [0, 0]

    def play(self, ball, player):

        if max(self.scores) == self.win: return 'Game Over!'

        self.turn = (self.turn + 1) % 2

        if abs(ball - player) < 4: return 'Player ' + str(self.turn + 1) + ' has hit the ball!'

        self.scores[(self.turn + 1) % 2] += 1

        return 'Player ' + (str(1 if self.turn else 2) + ' has won the game!' if max(self.scores) == self.win else str(self.turn + 1) + ' has missed the ball!')


Solve in Python:
Lets wish Horsbug98 on his birthday and jump right into the question.
In Chefland, $6$ new mobile brands have appeared each providing a range of smartphones. For simplicity let the brands be represented by numbers $1$ to $6$. All phones are sold at the superstore.
There are total $N$ smartphones. Let $P_i$ & $B_i$ be the price and the brand of the $i^{th}$ smartphone. The superstore knows all the price and brand details beforehand.
Each customer has a preference for brands. The preference is a subset of the brands available (i.e $1$ to $6$). Also, the customer will buy the $K^{th}$ costliest phone among all the phones of his preference.
You will be asked $Q$ queries. Each query consists of the preference of the customer and $K$.
Find the price the customer has to pay for his preference. If no such phone is available, print $-1$
Note that for each query the total number of smartphones is always $N$ since, after each purchase, the phones are replaced instantly.

-----Input:-----
- First Line contains $N$ and $Q$
- Second-line contains $N$ integers $P_1,P_2,...,P_N$ (Price)
- Third line contains $N$ integers $B_1,B_2,...,B_N$ (Brand)
- Each of the next Q lines contains a query, the query is describes below
- First line of each quey contains $b$ and $K$ where $b$ is the size of the preference subset.
- Second line of each query contains $b$ integers, describing the preference subset.

-----Output:-----
For each query, print the price to be paid.

-----Constraints-----
- $1 \leq N, Q, P_i \leq 10^5$
- $1 \leq B_i, b \leq 6$
- $1 \leq K \leq N$

-----Sample Input:-----
4 2
4 5 6 7
1 2 3 4
3 3
1 2 3
3 4
4 5 6

-----Sample Output:-----
4

-1

-----Explaination-----
Query 1: The preference subset is {1, 2, 3}, The prices of phones available of these brands are {4, 5, 6}. The third costliest phone is 4.
Query 2: The preference subset is {4, 5, 6}, The prices of phones available of these brands are {7}.
Fouth costliest phone is required, which is not available. Hence, answer is $-1$.

import sys
from collections import defaultdict
from copy import copy

R = lambda t = int: t(eval(input()))
RL = lambda t = int: [t(x) for x in input().split()]
RLL = lambda n, t = int: [RL(t) for _ in range(n)]

def solve():
    N, Q = RL()
    P = RL()
    B = RL()
    phones = sorted(zip(P, B))
    S = defaultdict(lambda : [])

    for p, b in phones:
        for i in range(2**7):
            if (i>>b) & 1:
                S[i] += [p]
    B = set(B)
    I = [0] * len(B)

    for _ in range(Q):
        b, K = RL()
        s = RL()
        x = 0
        for b in s:
            x += 1<<b
        if len(S[x]) < K:
            print(-1)
        else:
            print(S[x][-K])

T = 1#R()
for t in range(1, T + 1):
    solve()


Solve in Python:
Let’s get to know our hero: Agent #134 - Mr. Slayer.

He was sent by his CSV agency to Ancient Rome in order to resolve some important national issues. However, something incredible has happened - the enemies have taken Julius Caesar as a prisoner!!!

Caesar, not a simple man as you know, managed to send cryptic message with coordinates of his location hoping that somebody would break the code. Here our agent of the secret service comes to the stage.

But he needs your help!

**Mission:**

You have to implement the function “Encode” of CaesarCrypto class that codes or decodes text based on Caesar’s algorithm.the function receives 2 parameters: an original text of any length of type “string” and a number of type “int” that represents shifts;only letters in both cases must be encrypted;alphabet contains only letters in this range: a-zA-Z;by encryption the letter can change the case;shift could be either positive or negative (for left shift);If the input text is empty, null or includes only whitespaces, return an empty string.

Time's ticking away. The life of Caesar is on the chopping block! Go for it!

def caesar_crypto_encode(text, shift):
    if text in ("", None):
        return ""
    else:
        from string import ascii_letters as abc
        text = text.strip()
        shift = (shift - 1) % len(abc) + 1
        return text.translate(str.maketrans(abc, abc[shift:] + abc[:shift]))


Solve in Python:
Levko loves array a_1, a_2, ... , a_{n}, consisting of integers, very much. That is why Levko is playing with array a, performing all sorts of operations with it. Each operation Levko performs is of one of two types:

  Increase all elements from l_{i} to r_{i} by d_{i}. In other words, perform assignments a_{j} = a_{j} + d_{i} for all j that meet the inequation l_{i} ≤ j ≤ r_{i}.  Find the maximum of elements from l_{i} to r_{i}. That is, calculate the value $m_{i} = \operatorname{max}_{j = l_{i}}^{r_{i}} a_{j}$.

Sadly, Levko has recently lost his array. Fortunately, Levko has records of all operations he has performed on array a. Help Levko, given the operation records, find at least one suitable array. The results of all operations for the given array must coincide with the record results. Levko clearly remembers that all numbers in his array didn't exceed 10^9 in their absolute value, so he asks you to find such an array.

-----Input-----

The first line contains two integers n and m (1 ≤ n, m ≤ 5000) — the size of the array and the number of operations in Levko's records, correspondingly.

Next m lines describe the operations, the i-th line describes the i-th operation. The first integer in the i-th line is integer t_{i} (1 ≤ t_{i} ≤ 2) that describes the operation type. If t_{i} = 1, then it is followed by three integers l_{i}, r_{i} and d_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n,  - 10^4 ≤ d_{i} ≤ 10^4) — the description of the operation of the first type. If t_{i} = 2, then it is followed by three integers l_{i}, r_{i} and m_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n,  - 5·10^7 ≤ m_{i} ≤ 5·10^7) — the description of the operation of the second type.

The operations are given in the order Levko performed them on his array.

-----Output-----

In the first line print "YES" (without the quotes), if the solution exists and "NO" (without the quotes) otherwise.

If the solution exists, then on the second line print n integers a_1, a_2, ... , a_{n} (|a_{i}| ≤ 10^9) — the recovered array.

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

n, m = map(int, input().split())
a = [10**9 for _ in range(n)]
extra = [0 for _ in range(n)]
query = list()
for _ in range(m):
     t, l, r, x = map(int, input().split())
     l -= 1
     r -= 1
     query.append((t, l, r, x))
     if t == 1:
          for j in range(l, r + 1):
               extra[j] += x
     else:
          for j in range(l, r + 1):
               a[j] = min(a[j], x - extra[j])
extra = a.copy()
for t, l, r, x in query:
     if t == 1:
          for j in range(l, r + 1):
               a[j] += x
     else:
          val = -10**9
          for j in range(l, r + 1):
               val = max(val, a[j])
          if not val == x:
               print('NO')
               return

print('YES')
for x in extra:
     print(x, end=' ')


Solve in Python:
Lexicographic permutations are ordered combinations of a set of items ordered in a specific way.

For instance, the first 8 permutations of the digits 0123, in lexicographic order, are:

```
1st 0123
2nd 0132
3rd 0213
4th 0231
5th 0312
6th 0321
7th 1023
8th 1032
```

Your task is to write a function ```L( n, d )``` that will return a `string` representing the `nth` permutation of the `d` digit, starting with 0 (i.e. d=10 means all digits 0123456789).

So for `d = 4`, `L(7,4)` should return `'1023'`, and `L(4,4)` should return `'0231'`
.

Some things to bear in mind:

• The function should return a `string`, otherwise permutations beginning with a 0 will have it removed.

• Test cases will not exceed the highest possible valid values for `n`

• The function should work for any `d` between `1` and `10`.

• A value of 1 for `n` means the 1st permutation, so `n = 0` is not a valid input.

• Oh, and no itertools ;)

def memoize(func):
    cache = {}
    def decorator(x):
        if not x in cache:
            cache[x] = func(x)
        return cache[x]
    return decorator

@memoize
def permutations(d):
    if d < 1:
        return []
    if d == 1:
        return ["0"]
    return sorted(p[:i] + str(d - 1) + p[i:] for p in permutations(d - 1) for i in range(d))

def nth_perm(n, d):
    return permutations(d)[n - 1]


Solve in Python:
Like all minions Dave also like to eat bananas. So as to his obsession, he is eating banana, but this time in different way. There are N bananas in dish. Dave wants to eat all of them. He starts eating at speed 1 banana/second. He can increase or decrease speed of eating by one only. The condition is that he must end eating at speed 1 banana/second. So, your task is to find minimum time required to finish all bananas in a dish.

-----Input-----
First line contain number of test cases T. Next T lines contain one integer N. Where N is number of bananas in a dish.

-----Output-----
For each test case print minimum time require to eat all N bananas.

-----Constraints-----
- 1 ≤ T ≤ 100
- 1 ≤ N ≤ 105

-----Example-----
Input:
2
2
4

Output:
2
3

-----Explanation-----
Example case 1.Dave will start to eat with rate of 1 banana/second. Then only one banana will remain. He will eat that banana in 1 second. Thus, Total time is 2 seconds.
Example case 2.Dave starts with rate of 1 banana/second, and then increase it to 2 bananas/second and again decrease it to 1 banana/second. So total time is 3 seconds.

t=int(input())
while(t):
 k=1
 j=0
 n=int(input())
 while(n>0):
  if(n<=k):
   j+=1
   n=0
  elif n>2*k:
   j+=2
   n=n-2*k
   k+=1
  else:
   j+=2
   n=0
 print(j)
 t-=1


Solve in Python:
Limak has a string S, that consists of N lowercase English letters.
Limak then created a new string by repeating S exactly K times.
For example, for S = "abcb" and K = 2, he would get "abcbabcb".
Your task is to count the number of subsequences "ab" (not necessarily consecutive) in the new string.
In other words, find the number pairs of indices i < j, such that the i-th and j-th characters in the new string are 'a' and 'b' respectively.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains two integers N and K, denoting the length of the initial string S and the number of repetitions respectively.
The second line contains a string S.
Its length is exactly N, and each of its characters is a lowercase English letter.

-----Output-----
For each test case, output a single line containing one integer — the number of subsequences "ab" in the new string.
For the given constraints, it can be proved that the answer fits in the 64-bit signed type.

-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 105
- 1 ≤ N * K ≤ 109 (in other words, the new string has length up to 109)

-----Example-----
Input:
3
4 2
abcb
7 1
aayzbaa
12 80123123
abzbabzbazab

Output:
6
2
64197148392731290

-----Explanation-----
Test case 1. Limak repeated the string "abcb" 2 times, and so he got "abcbabcb". There are 6 occurrences of the subsequence "ab":
- ABcbabcb (the two letters marked uppercase)
- AbcBabcb
- AbcbaBcb
- AbcbabcB
- abcbABcb
- abcbAbcB
Test case 2. Since K = 1, the new string is equal to the given S ("aayzbaa"). There are 2 occurrences of the subsequence "ab" in this string: AayzBaa and aAyzBaa.

t=int(input())
for _1 in range(t):
	n, k=map(int, input().split())
	s=input().strip()
	a, b, ab=0, 0, 0
	for x in range(len(s)):
		if s[x]=='a':a+=1
		if s[x]=='b':
			b+=1
			ab+=a
	print(ab*k+a*b*((k-1)*k)//2)


Solve in Python:
Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of h_{i} identical blocks. For clarification see picture for the first sample.

Limak will repeat the following operation till everything is destroyed.

Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.

Limak is ready to start. You task is to count how many operations will it take him to destroy all towers.

-----Input-----

The first line contains single integer n (1 ≤ n ≤ 10^5).

The second line contains n space-separated integers h_1, h_2, ..., h_{n} (1 ≤ h_{i} ≤ 10^9) — sizes of towers.

-----Output-----

Print the number of operations needed to destroy all towers.

-----Examples-----
Input
6
2 1 4 6 2 2

Output
3

Input
7
3 3 3 1 3 3 3

Output
2

-----Note-----

The picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color.  [Image]  After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation.

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

a[0] = 1
a[-1] = 1
for i in range(1,n):
    a[i] = min(a[i],a[i-1]+1)
    a[-i] = min(a[-i],a[-(i-1)]+1)

print(max(a))


Solve in Python:
Limak is a little polar bear.
He is playing a video game and he needs your help.
There is a row with N cells, each either empty or occupied by a soldier, denoted by '0' and '1' respectively.
The goal of the game is to move all soldiers to the right (they should occupy some number of rightmost cells).
The only possible command is choosing a soldier and telling him to move to the right as far as possible.
Choosing a soldier takes 1 second, and a soldier moves with the speed of a cell per second.
The soldier stops immediately if he is in the last cell of the row or the next cell is already occupied.
Limak isn't allowed to choose a soldier that can't move at all (the chosen soldier must move at least one cell to the right).
Limak enjoys this game very much and wants to play as long as possible.
In particular, he doesn't start a new command while the previously chosen soldier moves.
Can you tell him, how many seconds he can play at most?

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

The only line of each test case contains a string S describing the row with N cells.
Each character is either '0' or '1', denoting an empty cell or a cell with a soldier respectively.

-----Output-----
For each test case, output a single line containing one integer — the maximum possible number of seconds Limak will play the game.

-----Constraints-----
- 1 ≤ T ≤ 5
- 1 ≤ N ≤ 105 (N denotes the length of the string S)

-----Subtasks-----
- Subtask #1 (25 points): 1 ≤ N ≤ 10
- Subtask #2 (25 points): 1 ≤ N ≤ 2000
- Subtask #3 (50 points): Original constraints.

-----Example-----
Input:
4
10100
1100001
000000000111
001110100011010

Output:
8
10
0
48

-----Explanation-----
Test case 1.
The initial string is 10100.
There are N = 5 cells.
There is one soldier in the first cell, and one soldier in the third cell.
The following scenario maximizes the total time:
- Limak chooses the soldier in the first cell.
This soldier can move only one cell to...

for _ in range(int(input())):
 l=list(map(int,input().strip()))
 for i in range(len(l)-1,-1,-1):
  if l[i]==1:
   l.pop()
  else:
   break
 if l.count(1):
  time,prev,z,c=0,0,0,0
  for i in range(len(l)-1,-1,-1):
   if l[i]==0:
    z+=1
    continue
   if prev!=z:
    prev=z
    c+=1
   time+=c+z

  print(time)
 else:
  print(0)


Solve in Python:
Linear Kingdom has exactly one tram line. It has `n` stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop.

## Your task

Calculate the tram's minimum capacity such that the number of people inside the tram never exceeds this capacity at any time. Note that at each stop all exiting passengers exit before any entering passenger enters the tram.

## Example

```c++
tram(4, {0, 2, 4, 4}, {3, 5, 2, 0}) ==> 6
```

Explaination:
* The number of passengers inside the tram before arriving is 0.
* At the first stop 3 passengers enter the tram, and the number of passengers inside the tram becomes 3.
* At the second stop 2 passengers exit the tram (1 passenger remains inside). Then 5 passengers enter the tram. There are 6 passengers inside the tram now.
* At the third stop 4 passengers exit the tram (2 passengers remain inside). Then 2 passengers enter the tram. There are 4 passengers inside the tram now.
* Finally, all the remaining passengers inside the tram exit the tram at the last stop. There are no passenger inside the tram now, which is in line with the constraints.

Since the number of passengers inside the tram never exceeds 6, a capacity of 6 is sufficient. Furthermore it is not possible for the tram to have a capacity less than 6. Hence, 6 is the correct answer.

def tram(stops, off, on):
    total = 0
    passengers = []
    for i in range(stops):
        total += on[i] - off[i]
        passengers.append(total)

    return max(passengers)


Solve in Python:
Linked Lists - Get Nth

Implement a GetNth() function that takes a linked list and an integer index and returns the node stored at the Nth index position. GetNth() uses the C numbering convention that the first node is index 0, the second is index 1, ... and so on. So for the list 42 -> 13 -> 666, GetNth() with index 1 should return Node(13);

The index should be in the range [0..length-1]. If it is not, GetNth() should throw/raise an exception (`ArgumentException` in C#, `InvalidArgumentException` in PHP). You should also raise an exception (`ArgumentException` in C#, `InvalidArgumentException` in PHP) if the list is empty/null/None.

Prerequisite Kata (may be in beta):

- Linked Lists - Push & BuildOneTwoThree
- Linked Lists - Length & Count

> The push() and buildOneTwoThree() (`BuildOneTwoThree` in C#, `build_one_two_three()` in PHP) functions do not need to be redefined.

class Node(object):
    def __init__(self, data):
        self.data = data
        self.next = None

def get_nth(node, index):
    assert(node and index >= 0)
    for _ in range(index):
        node = node.next
        assert(node)
    return node


Solve in Python:
Linked Lists - Length & Count

Implement Length() to count the number of nodes in a linked list.
Implement Count() to count the occurrences of an integer in a linked list.

I've decided to bundle these two functions within the same Kata since they are both very similar.

The `push()`/`Push()` and `buildOneTwoThree()`/`BuildOneTwoThree()` functions do not need to be redefined.

class Node(object):
    def __init__(self, data):
        self.data = data
        self.next = None

def length(node):
    return 1 + length(node.next) if node else 0

def count(node, data):
    return (1 if node.data == data else 0) + count(node.next, data) if node else 0


Solve in Python:
Linked Lists - Sorted Insert

Write a SortedInsert() function which inserts a node into the correct location of a pre-sorted linked list which is sorted in ascending order. SortedInsert takes the head of a linked list and data used to create a node as arguments. SortedInsert() should also return the head of the list.

The push() and buildOneTwoThree() functions do not need to be redefined.

""" For your information:
class Node(object):
    def __init__(self, data):
        self.data = data
        self.next = None
"""

def sorted_insert(head, data):
    if not head:
        return Node(data)
    elif head.data>data:
        res=Node(data)
        res.next=head
        return res
    else:
        temp=head
        while head.next and head.next.data<data:
            head=head.next
        res=Node(data)
        res.next=head.next
        head.next=res
        return temp
        return temp


Solve in Python:
Linked lists are data structures composed of nested or chained objects, each containing a single value and a reference to the next object.

Here's an example of a list:

```python
class LinkedList:
    def __init__(self, value=0, next=None):
        self.value = value
        self.next = next

LinkedList(1, LinkedList(2, LinkedList(3)))

```

Write a function listToArray (or list\_to\_array in Python) that converts a list to an array, like this:

```
[1, 2, 3]
```

Assume all inputs are valid lists with at least one value. For the purpose of simplicity, all values will be either numbers, strings, or Booleans.

list_to_array = lambda l: list() if l == None else [l.value] + list_to_array(l.next)


Solve in Python:
Lira is now very keen on compiler development. :)
She knows that one of the most important components of a compiler, is its parser.
A parser is, in simple terms, a software component that processes text, and checks it's semantic correctness, or, if you prefer, if the text is properly built.
As an example, in declaring and initializing an integer, in C/C++, you can't do something like:
int = x ;4
as the semantics of such statement is incorrect, as we all know that the datatype must precede an identifier and only afterwards should come the equal sign and the initialization value, so, the corrected statement should be:
int x = 4;
Today, Lira is concerned with an abstract instruction which is composed of the characters "<" and ">" , which she will use on the design of her language, L++ :D.
She is using it as an abstraction for generating XML code Tags in an easier fashion and she understood that, for an expression to be valid, a "<" symbol must always have a corresponding ">" character somewhere (not necessary immediately) after it. Moreover, each ">" symbol should correspond to exactly one "<" symbol.
So, for instance, the instructions:
<<>>
<>
<><>
are all valid. While:
>>
><><
are not.
Given some expressions which represent some instructions to be analyzed by Lira's compiler, you should tell the length of the longest prefix of each of these expressions that is valid, or 0 if there's no such a prefix.

-----Input-----
Input will consist of an integer T denoting the number of test cases to follow.
Then, T strings follow, each on a single line, representing a possible expression in L++.

-----Output-----
For each expression you should output the length of the longest prefix that is valid or 0 if there's no such a prefix.

-----Constraints-----
- 1 ≤ T ≤ 500
- 1 ≤ The length of a single expression ≤ 106
- The total size all the input expressions is no more than 5*106

-----Example-----
Input:
3
<<>>
><
<>>>
Output:
4
0
2

# cook your dish here
t=int(input())
for _ in range(t):
      s=input()
      l=[]
      c=0
      flag=0
      for i in range(len(s)):
            if s[i]=='<':
                  c+=1
            else:
                  c-=1
            if c==0:
                  flag=i+1
            if c<0:
                  break
      print(flag)


Solve in Python:
Little Egor is a huge movie fan. He likes watching different kinds of movies: from drama movies to comedy movies, from teen movies to horror movies. He is planning to visit cinema this weekend, but he's not sure which movie he should watch.
There are n movies to watch during this weekend. Each movie can be characterized by two integers Li and Ri, denoting the length and the rating of the corresponding movie. Egor wants to watch exactly one movie with the maximal value of Li × Ri. If there are several such movies, he would pick a one with the maximal Ri among them. If there is still a tie, he would pick the one with the minimal index among them.
Your task is to help Egor to pick a movie to watch during this weekend.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases.
The first line of the test case description contains an integer n.
The second line of the test case description contains n integers L1, L2, ...,Ln. The following line contains n integers R1, R2, ..., Rn.

-----Output-----
For each test case, output a single integer i denoting the index of the movie that Egor should watch during this weekend. Note that we follow 1-based indexing.

-----Constraints-----
- 1 ≤ T ≤ 5
- 1 ≤ n ≤ 100
- 1 ≤ Li, Ri ≤ 100

-----Example-----
Input:
2
2
1 2
2 1
4
2 1 4 1
2 4 1 4

Output:
1
2

-----Explanation-----
In the first example case, both films have the same value of L × R, but the first film has a better rating.
In the second example case, the second and the fourth movies are equally good, but the second movie has a smaller index.

# -*- coding: utf-8 -*-
"""
Created on Sun Apr 17 21:28:56 2016

@author: Harry
"""
import collections
no_of_testcases = int(input())
for each in range(no_of_testcases):
 to_watch = []
 length = []
 rating = []
 no_of_movies = int(input())
 length = list(map(int,input().split()))
 rating = list(map(int,input().split()))
 for e in range(no_of_movies):
  l_x_r = length[e]*rating[e]
  to_watch.append(l_x_r)
 counter = collections.Counter(to_watch)
 test = max(counter.keys())
 if counter[test] > 1:
  rating_indexes = [0]
  i = 0
  for x in to_watch:
   if x == test:
    if rating[i] > rating_indexes[0]:
     high_ratng = rating[i]
     rating_indexes = [high_ratng]
   i = i+1
  print(rating.index(high_ratng) +1)
 else:
  print(to_watch.index(test)+1)


Solve in Python:
Little Elephant is playing a game with arrays. He is given an array A0, A1, ..., AN−1 of N integers. And then Q queries are given, each containing an integer K. He has to tell how many subarrays satisfy the condition: the function foo returns K when it is applied to the subarray.

In this problem, a subarray is defined as a sequence of continuous elements Ai, Ai+1, ..., Aj  where 0 ≤ i ≤ j ≤ N−1. The function foo, when applied to an array, returns the minimum of all the elements in the array.

For example, foo returns 5 when it is applied to the array [7, 5, 10, 7, 5, 8]. Please note that the subarrays Ai, Ai+1, ..., Aj and Ak, Ak+1, ..., Al are different if and only if i ≠ k or j ≠ l in this problem.

-----Input-----
The first line of input contains N, denoting the size of the array. The next line contains N space separated integers A0, A1, ..., AN−1, denoting the array. Then the next line contains Q, denoting the number of queries. Each query consists of one integer per line, denoting K.

-----Output-----
For each query, print the required number of subarrays.

-----Constraints-----
- 1 ≤ N ≤ 50
- 1 ≤ Ai ≤ 1000000 (106)
- 1 ≤ Q ≤ 10
- 1 ≤ K ≤ 1000000 (106)

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

Output:
2
2
0
8

-----Explanation-----
Query 1. Only the two subarrays [3, 4] and [3] satisfy.
Query 2. Again only the two subarrays [4] and [4] satisfy. Please note that these subarrays (A0 and A4) are considered different.
Query 3. No subarray satisfies.
Query 4. The eight subarrays [4, 1], [4, 1, 2], [4, 1, 2, 3], [4, 1, 2, 3, 4], [1], [1, 2], [1, 2, 3] and [1, 2, 3, 4] satisfy.

N = int(input())
array = list(map(int, input().split()))
for _ in range(int(input())):
    K = int(input())
    count = 0
    for i in range(N):
        for j in range(i+1,N+1):
            if K == min(array[i:j]):
                count += 1
    print(count)


Solve in Python:
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.

Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a_1... a_{|}t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" $\rightarrow$ "nastya" $\rightarrow$ "nastya" $\rightarrow$ "nastya" $\rightarrow$ "nastya" $\rightarrow$ "nastya" $\rightarrow$ "nastya".

Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.

It is guaranteed that the word p can be obtained by removing the letters from word t.

-----Input-----

The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| < |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t.

Next line contains a permutation a_1, a_2, ..., a_{|}t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ a_{i} ≤ |t|, all a_{i} are distinct).

-----Output-----

Print a single integer number, the maximum number of letters that Nastya can remove.

-----Examples-----
Input
ababcba
abb
5 3 4 1 7 6 2

Output
3
Input
bbbabb
bb
1 6 3 4 2 5

Output
4

-----Note-----

In the first sample test sequence of removing made by Nastya looks like this:

"ababcba" $\rightarrow$ "ababcba" $\rightarrow$ "ababcba"...

import heapq
from bisect import bisect_left, bisect_right
from itertools import accumulate

def is_substr(fw, tw, seq):
    i, j = 0, 0
    while i < len(fw) and j < len(tw):
        if i in seq:
            i += 1
        elif fw[i] == tw[j]:
            i, j = i + 1, j + 1
        else:
            i += 1
    return j == len(tw)

R = lambda: map(int, input().split())
fw, tw = input(), input()
seq = [i - 1 for i in list(R())]
l, r = 0, len(seq) - 1
m, res = 0, 0
while l <= r:
    m = (l + r) // 2
    if is_substr(fw, tw, set(seq[:m])):
        res = max(res, m)
        l = m + 1
    else:
        r = m - 1
print(res)


Solve in Python:
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.

Note that the order of the points inside the group of three chosen points doesn't matter.

-----Input-----

The first line contains two integers: n and d (1 ≤ n ≤ 10^5; 1 ≤ d ≤ 10^9). The next line contains n integers x_1, x_2, ..., x_{n}, their absolute value doesn't exceed 10^9 — the x-coordinates of the points that Petya has got.

It is guaranteed that the coordinates of the points in the input strictly increase.

-----Output-----

Print a single integer — the number of groups of three points, where the distance between two farthest points doesn't exceed d.

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

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

Output
4

Input
4 2
-3 -2 -1 0

Output
2

Input
5 19
1 10 20 30 50

Output
1

-----Note-----

In the first sample any group of three points meets our conditions.

In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.

In the third sample only one group does: {1, 10, 20}.

from collections import deque
n,d = [int(i) for i in input().split()]
alist = [int(i) for i in input().split()]
de = deque()
i = 0
m = 0
while i < n:
    while i < n and (len(de) == 0 or alist[i] - de[0] <= d):
        de.append(alist[i])
        if len(de) >= 3:
            m += (len(de)-1) *(len(de)-2) // 2
        i += 1
    de.popleft()
print (m)


Solve in Python:
Little Petya often visits his grandmother in the countryside. The grandmother has a large vertical garden, which can be represented as a set of `n` rectangles of varying height. Due to the newest irrigation system we can create artificial rain above them.

Creating artificial rain is an expensive operation. That's why we limit ourselves to creating the artificial rain only above one section. The water will then flow to the neighbouring sections but only if each of their heights does not exceed the height of the previous watered section.

___

## Example:

Let's say there's a garden consisting of 5 rectangular sections of heights `4, 2, 3, 3, 2`.

Creating the artificial rain over the left-most section is inefficient as the water **WILL FLOW DOWN** to the section with the height of `2`, but it **WILL NOT FLOW UP** to the section with the height of `3` from there. Only 2 sections will be covered: `4, 2`.

The most optimal choice will be either of the sections with the height of `3` because the water will flow to its neighbours covering 4 sections altogether: `2, 3, 3, 2`. You can see this process in the following illustration:

___

As Petya is keen on programming, he decided to find such section that if we create artificial rain above it, the number of watered sections will be maximal.

## Output:
The maximal number of watered sections if we create artificial rain above exactly one section.

**Note: performance will be tested.**

def artificial_rain(garden):
    max_sections = 1
    curr_sections = 1
    flat_sections = 1
    previous = garden[0]
    slope = 'downhill'
    for section in garden[1:]:
        if slope == 'downhill' and section > previous:
            if curr_sections > max_sections:
                max_sections = curr_sections
            curr_sections = flat_sections + 1
            flat_sections = 1
            slope = 'uphill'
        elif slope == 'uphill' and section < previous:
            curr_sections += 1
            flat_sections = 1
            slope = 'downhill'
        else:
            curr_sections += 1
            if section == previous:
                flat_sections += 1
            else:
                flat_sections = 1
        previous = section
    if curr_sections > max_sections:
        max_sections = curr_sections
    return max_sections


Solve in Python:
Little Praneet loves experimenting with algorithms and has devised a new algorithm. The algorithm is performed on an integer as follows:
- if the rearmost digit is $0$, he will erase it.
- else, he will replace the rearmost digit $d$ with $d-1$.
If a point comes when the integer becomes $0$, the algorithm stops.
You are given an integer $n$. Praneet will perform the algorithm on it $a$ times. You have to print the result after $a$ operations.

-----Input:-----
- The first and only line of input contains two integers $n$ — initial number, and $a$ —the number of operations.

-----Output:-----
- Print one integer — the result of performing the algorithm on $n$ $a$ times.

-----Constraints-----
- $2 \leq n \leq 10^9$
- $1 \leq a \leq 50$

-----Sample Input 1-----
1001 2

-----Sample Input 2-----
5 2

-----Sample Output 1-----
100

-----Sample Output 2-----
3

-----Explanation-----
- In the first example, the transformation is as follows: $1001->1000->100$.
- In the second example, the transformation is as follows: $5->4->3$.

# cook your dish here
n,k=map(int,input().split())
while n!=1 and k:
 if n%10==0:
  n//=10
 else:
  n-=1
 k-=1
print(n)


Solve in Python:
Little X has n distinct integers: p_1, p_2, ..., p_{n}. He wants to divide all of them into two sets A and B. The following two conditions must be satisfied:  If number x belongs to set A, then number a - x must also belong to set A.  If number x belongs to set B, then number b - x must also belong to set B.

Help Little X divide the numbers into two sets or determine that it's impossible.

-----Input-----

The first line contains three space-separated integers n, a, b (1 ≤ n ≤ 10^5; 1 ≤ a, b ≤ 10^9). The next line contains n space-separated distinct integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ 10^9).

-----Output-----

If there is a way to divide the numbers into two sets, then print "YES" in the first line. Then print n integers: b_1, b_2, ..., b_{n} (b_{i} equals either 0, or 1), describing the division. If b_{i} equals to 0, then p_{i} belongs to set A, otherwise it belongs to set B.

If it's impossible, print "NO" (without the quotes).

-----Examples-----
Input
4 5 9
2 3 4 5

Output
YES
0 0 1 1

Input
3 3 4
1 2 4

Output
NO

-----Note-----

It's OK if all the numbers are in the same set, and the other one is empty.

import sys
from collections import defaultdict as dd
input = sys.stdin.readline
I = lambda : list(map(int,input().split()))

n,a,b=I()
l=I()
dic=dd(int)
for i in range(n):
	dic[l[i]]=1
bs=[]
pa=dd(int)
for i in range(n):
	if dic[a-l[i]]==0:
		bs.append(l[i])
	else:
		pa[l[i]]=a-l[i]
j=0
while j<len(bs):
	for i in range(j,len(bs)):
		cr=bs[i]
		dic[cr]=2
		if dic[b-cr]==0:
			print("NO");return
		dic[b-cr]=2
		if dic[a-b+cr]==1:
			dic[a-b+cr]=2
			bs.append(a-b+cr)
		j+=1
		#ct=0;vt=a-b+cr
		#while vt!=pa[pa[vt]]:
		#	vt=pa[vt];dic[b-vt]=2
		#	dic[vt]=2
an=[0]*n
for i in range(n):
	an[i]=dic[l[i]]-1
print("YES")
print(*an)


Solve in Python:
Little chef has just been introduced to the world of numbers! While experimenting with addition and multiplication operations, the little chef came up with the following problem:

Given an array A of non-negative integers, how many pairs of indices i and j exist such that  A[i]*A[j] > A[i]+A[j]  where  i < j .

Now being a learner, little chef isn't able to solve this problem efficiently and hence turns to you for help.

-----Input-----
First line of input contains an integer T denoting the number of test cases. For each test case, the first line contains an integer N denoting the number of integers in the array. The next line contains N space separated integers where the ith integer represents A[i].
Note : There may be trailing spaces on each line of input.

-----Output-----
For each test, print the required number of pairs in a single line.

-----Constraints-----
-  1 ≤ T ≤ 10
-  2 ≤ N ≤ 100000 (105)
-  0 ≤ A[i] ≤ 1000000 (106)

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

Output:
3
0

-----Explanation-----

Example case 1.

All pairs of numbers satisfy the criteria. Total number of pairs equals 3.

Example case 2.

No pair of numbers satisfy the criteria.

for _ in range(int(input())):
 n=int(input())
 l=list(map(int,input().split()))
 t_2=0
 tn_2=0
 for i in range(len(l)):
  if l[i]>2:
   tn_2+=1
  elif(l[i]==2):
   t_2+=1
 ans=(tn_2*(tn_2-1))/2
 ans+=t_2*tn_2
 print(int(ans))


Solve in Python:
Little kids, Jack and Evan like playing their favorite game Glass-and-Stone. Today they want to play something new and came across Twitter on their father's laptop.

They saw it for the first time but were already getting bored to see a bunch of sentences having at most 140 characters each. The only thing they liked to play with it is, closing and opening tweets.

There are N tweets on the page and each tweet can be opened by clicking on it, to see some statistics related to that tweet. Initially all the tweets are closed. Clicking on an open tweet closes it and clicking on a closed tweet opens it. There is also a button to close all the open tweets. Given a sequence of K clicks by Jack, Evan has to guess the total number of open tweets just after each click. Please help Evan in this game.

-----Input-----
First line contains two integers N K, the number of tweets (numbered 1 to N) and the number of clicks respectively (1 ≤ N, K ≤ 1000). Each of the following K lines has one of the following.

- CLICK X , where X is the tweet number (1 ≤ X ≤ N)
- CLOSEALL

-----Output-----
Output K lines, where the ith line should contain the number of open tweets just after the ith click.

-----Example-----
Input:
3 6
CLICK 1
CLICK 2
CLICK 3
CLICK 2
CLOSEALL
CLICK 1

Output:
1
2
3
2
0
1

Explanation:

Let open[x] = 1 if the xth tweet is open and 0 if its closed.

Initially open[1..3] = { 0 , 0 , 0 }. Here is the state of open[1..3] after each click and corresponding count of open tweets.

CLICK 1 : { 1, 0, 0 }, open count = 1

CLICK 2 : { 1, 1, 0 }, open count = 2

CLICK 3 : { 1, 1, 1 }, open count = 3

CLICK 2 : { 1, 0, 1 }, open count = 2

CLOSEALL : { 0, 0, 0 }, open count = 0

CLICK 1 : { 1, 0, 0 }, open count = 1

n,k=list(map(int,input().split()))
hit=[0]*n
count=0
for i in range(k):
 cmd=input().split()
 if cmd[0]=='CLICK':
  idx=int(cmd[1])-1
  if hit[idx]==0:
   hit[idx]=1
   count+=1
  else:
   hit[idx]=0
   count-=1
 else:
  hit=[0]*n
  count=0
 print(count)


Solve in Python:
Logical quantifiers are very useful tools for expressing claims about a set. For this problem, let's focus on the set of real numbers specifically. The set of real numbers includes zero and negatives. There are two kinds of quantifiers: universal ($\forall$) and existential ($\exists$). You can read more about them here.

The universal quantifier is used to make a claim that a statement holds for all real numbers. For example:  $\forall x,x<100$ is read as: for all real numbers $x$, $x$ is less than $100$. This statement is false.  $\forall x,x>x-1$ is read as: for all real numbers $x$, $x$ is greater than $x-1$. This statement is true.

The existential quantifier is used to make a claim that there exists some real number for which the statement holds. For example:  $\exists x,x<100$ is read as: there exists a real number $x$ such that $x$ is less than $100$. This statement is true.  $\exists x,x>x-1$ is read as: there exists a real number $x$ such that $x$ is greater than $x-1$. This statement is true.

Moreover, these quantifiers can be nested. For example:  $\forall x,\exists y,x<y$ is read as: for all real numbers $x$, there exists a real number $y$ such that $x$ is less than $y$. This statement is true since for every $x$, there exists $y=x+1$.  $\exists y,\forall x,x<y$ is read as: there exists a real number $y$ such that for all real numbers $x$, $x$ is less than $y$. This statement is false because it claims that there is a maximum real number: a number $y$ larger than every $x$.

Note that the order of variables and quantifiers is important for the meaning and veracity of a statement.

There are $n$ variables $x_1,x_2,\ldots,x_n$, and you are given some formula of the form $$ f(x_1,\dots,x_n):=(x_{j_1}<x_{k_1})\land (x_{j_2}<x_{k_2})\land \cdots\land (x_{j_m}<x_{k_m}), $$

where $\land$ denotes logical AND. That is, $f(x_1,\ldots, x_n)$ is true if every inequality $x_{j_i}<x_{k_i}$ holds. Otherwise, if at least one inequality does not hold, then $f(x_1,\ldots,x_n)$ is false.

Your task is to...

import collections
import sys
input=sys.stdin.readline

n,m=map(int,input().split())
ans=['']*(n+1)
g1=[[] for _ in range(n+1)]
g2=[[] for _ in range(n+1)]
deg=[0]*(n+1)
for _ in range(m):
  a,b=map(int,input().split())
  g1[a].append(b)
  g2[b].append(a)
  deg[a]+=1
status=[0]*(n+1)
q=collections.deque()
for i in range(1,n+1):
  if deg[i]==0:
    q.append(i)
while len(q)!=0:
  v=q.pop()
  status[v]=1
  for u in g2[v]:
    deg[u]-=1
    if deg[u]==0:
      q.append(u)
if status.count(0)>=2:
  print(-1)
else:
  status1=[0]*(n+1)
  status2=[0]*(n+1)
  for i in range(1,n+1):
    if status1[i]==0 and status2[i]==0:
      ans[i]='A'
    else:
      ans[i]='E'
    if status1[i]==0:
      q=collections.deque()
      q.append(i)
      while len(q)!=0:
        v=q.pop()
        status1[v]=1
        for u in g1[v]:
          if status1[u]==0:
            status1[u]=1
            q.append(u)
    if status2[i]==0:
      q=collections.deque()
      q.append(i)
      while len(q)!=0:
        v=q.pop()
        status2[v]=1
        for u in g2[v]:
          if status2[u]==0:
            status2[u]=1
            q.append(u)
  print(ans.count('A'))
  print(''.join(map(str,ans[1:])))


Solve in Python:
Looking at consecutive powers of `2`, starting with `2^1`:

`2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, ...`

Note that out of all the digits `0-9`, the last one ever to appear is `7`. It only shows up for the first time in the number `32768 (= 2^15)`.

So let us define LAST DIGIT TO APPEAR as the last digit to be written down when writing down all the powers of `n`, starting with `n^1`.

## Your task

You'll be given a positive integer ```1 =< n <= 10000```, and must return the last digit to appear, as an integer.

If for any reason there are digits which never appear in the sequence of powers, return `None`/`nil`.

Please note: The Last digit to appear can be in the same number as the penultimate one. For example for `n = 8`, the last digit to appear is `7`, although `3` appears slightly before it, in the same number:
`8, 64, 512, 4096, 32768, ...`

def LDTA(n):
    if n in (1, 10, 100, 1000, 10000):
        return None
    digits = set("0123456789")
    k = 1
    while True:
        p = str(n**k)
        for digit in p:
            digits -= {digit}
            if len(digits) == 1:
                return int(digits.pop())
        k += 1


Solve in Python:
Lot of junior developer can be stuck when they need to change the access permission to a file or a directory in an Unix-like operating systems.

To do that they can use the `chmod` command and with some magic trick they can change the permissionof a file or a directory. For more information about the `chmod` command you can take a look at the [wikipedia page](https://en.wikipedia.org/wiki/Chmod).

`chmod` provides two types of syntax that can be used for changing permissions. An absolute form using octal to denote which permissions bits are set e.g: 766.
Your goal in this kata is to define the octal you need to use in order to set yout permission correctly.

Here is the list of the permission you can set with the octal representation of this one.

- User
  - read (4)
  - write (2)
  - execute (1)
- Group
  - read (4)
  - write (2)
  - execute (1)
- Other
  - read (4)
  - write (2)
  - execute (1)

The method take a hash in argument this one can have a maximum of 3 keys (`owner`,`group`,`other`). Each key will have a 3 chars string to represent the permission, for example the string `rw-` say that the user want the permission `read`, `write` without the `execute`.
If a key is missing set the permission to `---`

**Note**: `chmod` allow you to set some special flags too (`setuid`, `setgid`, `sticky bit`) but to keep some simplicity for this kata we will ignore this one.

from functools import reduce
from operator import or_

SHIFTS = {'user': 6, 'group': 3, 'other': 0}

def chmod_calculator(perm):
    return format(reduce(or_, (
        (('r' in p) << 2 | ('w' in p) << 1 | ('x' in p)) << SHIFTS[user]
        for user, p in perm.items()
    ), 0), '03o')


Solve in Python:
Lot of museum allow you to be a member, for a certain amount `amount_by_year` you can have unlimitted acces to the museum.

In this kata you should complete a function in order to know after how many visit it will be better to take an annual pass. The function take 2 arguments `annual_price` and `individual_price`.

import math
how_many_times = lambda year,ind: math.ceil(year/ind)


Solve in Python:
Lots of geeky customers visit our chef's restaurant everyday. So, when asked to fill the feedback form, these customers represent the feedback using a binary string (i.e a string that contains only characters '0' and '1'.

Now since chef is not that great in deciphering binary strings, he has decided the following criteria to classify the feedback as Good or Bad :

If the string contains the substring "010" or "101", then the feedback is Good, else it is Bad. Note that, to be Good it is not necessary to have both of them as substring.

So given some binary strings, you need to output whether according to the chef, the strings are Good or Bad.

-----Input-----
The first line contains an integer T denoting the number of feedbacks. Each of the next T lines contains a string composed of only '0'  and '1'.

-----Output-----
For every test case, print in a single line Good or Bad as per the Chef's method of classification.

-----Constraints-----
-  1 ≤  T ≤   100
-  1  ≤  |S|   ≤  105

Sum of length of all strings in one test file will not exceed 6*106.

-----Example-----
Input:
2
11111110
10101010101010

Output:
Bad
Good

-----Explanation-----
Example case 1.

The string doesn't contain 010 or 101 as substrings.

Example case 2.

The string contains both 010 and 101 as substrings.

for _ in range(int(input())):
 s = input()
 if "010" in s or "101" in s:
  print("Good")
 else:
  print("Bad")


Solve in Python:
Lucas numbers are numbers in a sequence defined like this:
```
L(0) = 2
L(1) = 1
L(n) = L(n-1) + L(n-2)
```

Your mission is to complete the function that returns the `n`th term of this sequence.

**Note:** It should work for negative numbers as well; how you do this is you flip the equation around, so for negative numbers: `L(n) = L(n+2) - L(n+1)`

## Examples
```
L(-10) = 123
L(-5)  = -11
L(-1)  =  -1
L(0)   =   2
L(1)   =   1
L(5)   =  11
L(10)  = 123
```

def lucasnum(n):
    a, b, i = 2, 1, 0
    while True:
        if i == n:    return a
        if n > 0:
            i += 1
            a, b = b, a+b
        else:
            i -= 1
            b,a = a, b-a


Solve in Python:
Lucy had recently learned the game, called Natural Numbers.
The rules of the game are really simple. There are N players. At the same time, every player says one natural number. Let's call the number said by the i-th player Ai. The person with the smallest unique number (that is, the smallest number that was not said by anybody else) wins. Sometimes, there is a case when there are no unique numbers at all. Then the game is obviously a draw, so nobody wins it.
Sometimes, it's hard to determine the winner, especially, when the number of players is enormous. So in this problem, your assignment will be: given the names of the players and the numbers every of them have said. Please, tell the name of the winner, or determine that nobody wins.

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

The first line of every test case consists of a single integer N - the number of players. Then, N lines will follow. Each of these N lines will consist of the player's name and the number Ai said by her, separated by a single space.

-----Output-----
For each test case, output a single line containing an answer to the corresponding test case - the name of the winner, or a string "Nobody wins.", if nobody wins the game.

-----Example-----
Input:
2
5
Kouta 1
Yuka 1
Mayu 3
Lucy 2
Nana 5
2
Lucy 2
Nana 2

Output:
Lucy
Nobody wins.

-----Scoring-----
Subtask 1 (17 points): T = 10000, 1 <= N <= 10, 1 <= Ai <= 10

Subtask 2 (19 points): T = 10000, 1 <= N <= 10, 1 <= Ai <= 2*109

Subtask 3 (30 points): T = 100, 1 <= N <= 1000, 1<= Ai <= 2*109

Subtask 4 (34 points): T = 10, 1 <= N <= 10000, 1 <= Ai <= 2*109

You can safely assume that in all the test cases the length of any name will not exceed five letters. All the players'  names  are unique.

try:
    t = int(input())
    while t:
        t -= 1
        n = int(input())
        arr = []
        obj = {}
        for i in range(n):
            x,y = input().split()
            y = int(y)
            arr.append([x, y])
            if y in obj: obj[y].append(x)
            else: obj[y] = [x]
        arr.sort(key = lambda i: i[1], reverse = True)
        while len(arr) and len(obj[arr[-1][1]]) > 1:
            arr.pop()
        if len(arr) == 0:
            print('Nobody wins.')
        else:
            print(arr.pop()[0])
except:
    pass


Solve in Python:
Lucy loves to travel. Luckily she is a renowned computer scientist and gets to travel to international conferences using her department's budget.

Each year, Society for Exciting Computer Science Research (SECSR) organizes several conferences around the world. Lucy always picks one conference from that list that is hosted in a city she hasn't been to before, and if that leaves her with more than one option, she picks the conference that she thinks would be most relevant for her field of research.

Write a function `conferencePicker` that takes in two arguments:

- `citiesVisited`, a list of cities that Lucy has visited before, given as an array of strings.
- `citiesOffered`, a list of cities that will host SECSR conferences this year, given as an array of strings. `citiesOffered` will already be ordered in terms of the relevance of the conferences for Lucy's research (from the most to the least relevant).

The function should return the city that Lucy should visit, as a string.

Also note:

- You should allow for the possibility that Lucy hasn't visited any city before.
- SECSR organizes at least two conferences each year.
- If all of the offered conferences are hosted in cities that Lucy has visited before, the function should return `'No worthwhile conferences this year!'` (`Nothing` in Haskell)

Example:

def conference_picker(arr1,arr2):
    L=[]
    for i in arr2:
        if i not in arr1:
            return i
            L.append(i)
    if L==[]:
        return 'No worthwhile conferences this year!'


Solve in Python:
Lumpy is a bus driver. Today, the conductor is absent so Lumpy has to do the conductor's job as well. There are N creatures in the bus. Sometimes the creatures don't carry change and can't pay the exact amount of the fare. Each creature in the bus today has paid an amount
greater than his/her fare. You are given information about the extra amount paid by each creature, by an array A of size N, where Ai denotes the extra amount paid by the i-th creature, in rupees.
After the end of the trip, Lumpy noticed that he had P one rupee coins and Q two rupee coins. He wants to pay back the creatures using this money. Being a kind hearted moose, Lumpy wants to pay back as many creatures as he can. Note that Lumpy will
not pay back the i-th creature if he can't pay the exact amount that the i-th creature requires with the coins that he possesses.
Lumpy is busy driving the bus and doesn't want to calculate the maximum number of creatures he can satisfy - He will surely cause an accident if he tries to do so. Can you help him out with this task?

-----Input-----
- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
- For each test case, first line consists of three space separated integers N, P and Q.
- Second line consists of N space separated integers A containing N space integers, where i-th integer denotes Ai.

-----Output-----
- For each test case, output a single line containing an integer corresponding to maximum number of creatures that Lumpy can pay back.

-----Constraints-----
- 1 ≤ T ≤ 106
- 1 ≤ N ≤ 105
- 1 ≤ Ai ≤ 109
- 0 ≤ P, Q ≤ 1014
- Sum of N over all the cases does not exceed 106

-----Subtasks-----
- Subtask #1 (15 points): P = 0
- Subtask #2 (15 points): Q = 0
- Subtask #3 (70 points): Original constraints

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

Output:2
3
3

-----Explanation-----
Example 1. Lumpy has just 3 one rupee coins.

He can pay creatures numbered {1, 2} or creatures numbered {1, 3} with these...

# cook your dish here
# cook your dish here
t=int(input())
for _ in range(t):
 n,p,q=list(map(int,input().split(" ")))
 l=list(map(int,input().split(" ")))
 l.sort()
 s=sum(l)
 a=p+2*q
 b=0
 for i in l:
  if(p==0):
   if(i%2==0 and a>=i):
    a=a-i
    b=b+1
  elif(q==0):
   if(a>=i):
    a=a-i
    b=b+1
  else:
   if(i%2==0 and a>=i):
    a=a-i
    b=b+1
   elif(i%2!=0 and p!=0 and a>=i):
    a=a-i
    b=b+1
    p=p-1

 print(b)


Solve in Python:
Lyra Belacqua is a very gifted girl. She is one of a very small set of people capable of reading an alethiometer, more commonly known as The Golden Compass. It has one specific use: to tell the truth. The name in fact, is derived from "Aletheia" meaning truth, and "-ometer", meaning "measuring device".

The alethiometer had four needles, out of which the user would direct three of them to lie over symbols on the face of the device to ask a question. The fourth needle then swung into action and pointed to various symbols one after another, thus telling the answer.

For this problem, consider the alethiometer consisting of symbols : digits '0'-'9' and letters 'A'-'Z'. Learned scholars were debating the age of the Universe, and they requested Lyra to find out the age from the alethiometer. Having asked the question, the fourth needle started spouting out symbols, which Lyra quickly recorded. In that long string of characters, she knows that some substring corresponds to the age of the Universe. She also knows that the alethiometer could have wrongly pointed out atmost one digit (0-9) as a letter (A-Z). She then wonders what is the maximum possible age of the Universe.

Given the set of symbols the alethiometer pointed out, help her find the maximum age of the Universe, which could correspond to a substring of the original string with atmost one letter changed.

Note: We consider a substring to be a contiguous part of the string S

Also, the alethiometer wrongly reports only a letter. All the digits remain as they are.

-----Input-----

Each input consists of a single string S which is what Lyra recorded from the fourth needle's pointing.

-----Output-----

Output one number, the maximum possible answer.

-----Constraints-----
-  1  ≤ |S|  ≤ 1,000
-  S will only contain digits 0-9 and uppercase Latin letters.

-----Example-----
Input1:
06454

Input2:
C0D3C43F

Output1:
6454

Output2:
3943

-----Explanation-----

In the first example, there is no choice as to what the number can be. It has to be 6,454.

In the...

string=input()
max_no=0
for i in range(len(string)):
 var_occur=0
 check_no=str()
 j=i
 while(j<len(string) and var_occur<2 ):
  if(string[j].isalpha()):
   if(var_occur==0):
    check_no+='9'
    var_occur+=1
   else:
    var_occur+=1
  else:
   check_no+=string[j]
  j+=1
 #print(check_no)
 max_no=max(max_no,int(check_no))
print(max_no)


Solve in Python:
Lеt's create function to play cards. Our rules:

We have the preloaded `deck`:

```
deck = ['joker','2♣','3♣','4♣','5♣','6♣','7♣','8♣','9♣','10♣','J♣','Q♣','K♣','A♣',
                '2♦','3♦','4♦','5♦','6♦','7♦','8♦','9♦','10♦','J♦','Q♦','K♦','A♦',
                '2♥','3♥','4♥','5♥','6♥','7♥','8♥','9♥','10♥','J♥','Q♥','K♥','A♥',
                '2♠','3♠','4♠','5♠','6♠','7♠','8♠','9♠','10♠','J♠','Q♠','K♠','A♠']
```

We have 3 arguments:

`card1` and `card2` - any card of our deck.

`trump` - the main suit of four ('♣', '♦', '♥', '♠').

If both cards have the same suit, the big one wins.

If the cards have different suits (and no one has trump) return 'Let's play again.'

If one card has `trump` unlike another, wins the first one.

If both cards have `trump`, the big one wins.

If `card1` wins, return 'The first card won.' and vice versa.

If the cards are equal, return 'Someone cheats.'

A few games:

```
('3♣', 'Q♣', '♦') -> 'The second card won.'

('5♥', 'A♣', '♦') -> 'Let us play again.'

('8♠', '8♠', '♣') -> 'Someone cheats.'

('2♦', 'A♠', '♦') -> 'The first card won.'

('joker', 'joker', '♦') -> 'Someone cheats.'

```
P.S. As a card you can also get the string 'joker' - it means this card always wins.

d = '2 3 4 5 6 7 8 9 10 J Q K A'.split()
ret = lambda fn,c1,c2,t:f"The {['first','second'][eval(fn)]} card won." if fn else "Let us play again."
def card_game(c1,c2,t):
    return ret('d.index(c1[:-1])<d.index(c2[:-1])' if c1[-1] == c2[-1] else\
               'c2=="joker"' if 'joker' in [c1,c2] else\
               'c2[-1]==t' if t in [c1[-1],c2[-1]] else \
               '',c1,c2,t) if c1 != c2 else "Someone cheats."  #no effeciency due to eval :(


Solve in Python:
Mad scientist Mike does not use slow hard disks. His modification of a hard drive has not one, but n different heads that can read data in parallel.

When viewed from the side, Mike's hard drive is an endless array of tracks. The tracks of the array are numbered from left to right with integers, starting with 1. In the initial state the i-th reading head is above the track number h_{i}. For each of the reading heads, the hard drive's firmware can move the head exactly one track to the right or to the left, or leave it on the current track. During the operation each head's movement does not affect the movement of the other heads: the heads can change their relative order; there can be multiple reading heads above any of the tracks. A track is considered read if at least one head has visited this track. In particular, all of the tracks numbered h_1, h_2, ..., h_{n} have been read at the beginning of the operation. [Image]

Mike needs to read the data on m distinct tracks with numbers p_1, p_2, ..., p_{m}. Determine the minimum time the hard drive firmware needs to move the heads and read all the given tracks. Note that an arbitrary number of other tracks can also be read.

-----Input-----

The first line of the input contains two space-separated integers n, m (1 ≤ n, m ≤ 10^5) — the number of disk heads and the number of tracks to read, accordingly. The second line contains n distinct integers h_{i} in ascending order (1 ≤ h_{i} ≤ 10^10, h_{i} < h_{i} + 1) — the initial positions of the heads. The third line contains m distinct integers p_{i} in ascending order (1 ≤ p_{i} ≤ 10^10, p_{i} < p_{i} + 1) - the numbers of tracks to read.

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

-----Output-----

Print a single number — the minimum time required, in seconds, to read all the needed tracks.

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

Output
2

Input
3 3
1 2 3
1 2 3

Output
0

Input
1 2
165
142...

import sys
from itertools import *
from math import *
def solve():
    n, m = map(int, input().split())
    h = list(map(int, input().split()))
    p = list(map(int, input().split()))
    ss, ll = 0, int(2.1e10)
    while ss < ll:
        avg = (ss + ll) // 2
        works = True
        hidx = 0
        pidx = 0
        while hidx < len(h) and pidx < len(p):
            leftget = p[pidx]
            curpos = h[hidx]
            if curpos - leftget > avg:
                works = False
                break
            getbacktime = max(0, 2*(curpos - leftget))
            alsotoright = max(0, avg - getbacktime)
            leftime = max(0, curpos - leftget)
            remtime = max(0, (avg - leftime) // 2)
            furthestright = curpos + max(alsotoright, remtime)
            while pidx < len(p) and p[pidx] <= furthestright: pidx += 1
            hidx += 1
        if pidx != len(p): works = False
        if works: ll = avg
        else: ss = avg + 1
    print(ss)

if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
solve()


Solve in Python:
Magic The Gathering is a collectible card game that features wizards battling against each other with spells and creature summons. The game itself can be quite complicated to learn. In this series of katas, we'll be solving some of the situations that arise during gameplay. You won't need any prior knowledge of the game to solve these contrived problems, as I will provide you with enough information.

## Creatures

Each creature has a power and toughness. We will represent this in an array. [2, 3] means this creature has a power of 2 and a toughness of 3.

When two creatures square off, they each deal damage equal to their power to each other at the same time. If a creature takes on damage greater than or equal to their toughness, they die.

Examples:

- Creature 1 - [2, 3]
- Creature 2 - [3, 3]
- Creature 3 - [1, 4]
- Creature 4 - [4, 1]

If creature 1 battles creature 2, creature 1 dies, while 2 survives. If creature 3 battles creature 4, they both die, as 3 deals 1 damage to 4, but creature 4 only has a toughness of 1.

Write a function `battle(player1, player2)` that takes in 2 arrays of creatures. Each players' creatures battle each other in order (player1[0] battles the creature in player2[0]) and so on. If one list of creatures is longer than the other, those creatures are considered unblocked, and do not battle.

Your function should return an object (a hash in Ruby) with the keys player1 and player2 that contain the power and toughness of the surviving creatures.

Example:
```
Good luck with your battles!

Check out my other Magic The Gathering katas:

Magic The Gathering #1: Creatures
Magic The Gathering #2: Mana

from itertools import zip_longest

def battle(player1, player2):
    result = {'player1': [], 'player2': []}
    for (p1, t1), (p2, t2) in zip_longest(player1, player2, fillvalue=[0,0]):
        if t1 > p2:
            result['player1'].append([p1,t1])
        if t2 > p1:
            result['player2'].append([p2,t2])
    return result


Solve in Python:
Maheshmati and Sangu are playing a game. First, Maheshmati gives Sangu a sequence of $N$ distinct integers $a_1, a_2, \dots, a_N$ (not necessarily sorted) and an integer $K$. Sangu has to create all subsequences of this sequence with length $K$. For each subsequence, he has to write down the product of $K-2$ integers: all elements of this subsequence except the minimum and maximum element.
Sangu wins the game if he is able to write down all these numbers and tell Maheshmati their product (modulo $10^9+7$, since it can be very large). However, Sangu is a very lazy child and thus wants you to help him win this game. Compute the number Sangu should tell Maheshmati!

-----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 line of each test case contains two space-separated integers $N$ and $K$.
- The second line contains $N$ space-separated integers $a_1, a_2, \dots, a_N$.

-----Output-----
For each test case, print a single line containing one integer — the product of all numbers written down by Sangu modulo $10^9+7$.

-----Constraints-----
- $1 \le T \le 10$
- $3 \le N \le 5,000$
- $3 \le K \le N$
- $1 \le a_i \le 10,000$ for each valid $i$
- the numbers $a_1, a_2, \dots, a_N$ are pairwise distinct

-----Subtasks-----
Subtask #1 (20 points): $1 \le N \le 10$
Subtask #2 (80 points): original constraints

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

-----Example Output-----
36

-----Explanation-----
Example case 1: There are four possible subsequences:
- $[1, 2, 3]$ (Sangu should write down $2$.)
- $[1, 3, 4]$ (Sangu should write down $3$.)
- $[1, 2, 4]$ (Sangu should write down $2$.)
- $[2, 3, 4]$ (Sangu should write down $3$.)
The required product is $2 \cdot 3 \cdot 2 \cdot 3 = 36$.

# cook your dish here
MOD = (10**9) + 7

def nCrModpDP(n, r, p):

 # The array C is going to store
 # last row of pascal triangle
 # at the end. And last entry
 # of last row is nCr
 C = [0] * (n + 1);

 # Top row of Pascal Triangle
 C[0] = 1;

 # One by constructs remaining
 # rows of Pascal Triangle from
 # top to bottom
 for i in range(1, (n + 1)):

  # Fill entries of current
  # row using previous row
  # values
  j = min(i, r);
  while(j > 0):
   C[j] = (C[j] + C[j - 1]) % p;
   j -= 1;
 return C[r];

# Lucas Theorem based function that
# returns nCr % p. This function
# works like decimal to binary
# conversion recursive function.
# First we compute last digits of
# n and r in base p, then recur
# for remaining digits
def nCrModpLucas(n, r, p):

 # Base case
 if (r == 0):
  return 1;

 # Compute last digits of n
 # and r in base p
 ni = int(n % p);
 ri = int(r % p);

 # Compute result for last digits
 # computed above, and for remaining
 # digits. Multiply the two results
 # and compute the result of
 # multiplication in modulo p.
 # Last digits of n and r
 return (nCrModpLucas(int(n / p), int(r / p), p) *
   nCrModpDP(ni, ri, p)) % p;

for _ in range(int(input())):

 n , k = list(map( int, input().split()))

 arr = list( map( int, input().split()) )

 arr = sorted(arr)

 value = nCrModpLucas(n-1,k-1,MOD)

 ans = 1

 for x in range(1,n-1):

  if (n - x - 1) >= (k-1) :

   temp1 = nCrModpLucas(n-x-1,k-1,MOD)
  else:
   temp1 = 0

  if x >= (k-1):

   temp2 = nCrModpLucas(x,k-1,MOD)
  else:
   temp2 = 0

  # print(value,ans,temp1,temp2)
  ans = ( ans * (arr[x]**( value - temp2 - temp1 )) )%MOD

 print(ans)


Solve in Python:
Make a function **"add"** that will be able to sum elements of **list** continuously and return a new list of sums.

For example:

```
add [1,2,3,4,5] == [1, 3, 6, 10, 15], because it's calculated like
this : [1, 1 + 2, 1 + 2 + 3, 1 + 2 + 3 + 4, 1 + 2 + 3 + 4 + 5]
```

If you want to learn more see https://en.wikipedia.org/wiki/Prefix_sum

from itertools import accumulate
def add(l):
    return list(accumulate(l))


Solve in Python:
Make a function that receives a value, ```val``` and outputs the smallest higher number than the given value, and this number belong to a set of positive integers that have the following properties:

- their digits occur only once

- they are odd

- they are multiple of three

```python
next_numb(12) == 15

next_numb(13) == 15

next_numb(99) == 105

next_numb(999999) == 1023459

next_number(9999999999) == "There is no possible number that
fulfills those requirements"
```

Enjoy the kata!!

def next_numb(val):
    i = val + 1
    while i <= 9999999999:
        if i % 3 == 0 and i % 2 and len(str(i)) == len(set(str(i))):
            return i
        i += 1
    return 'There is no possible number that fulfills those requirements'


Solve in Python:
Make a function that returns the value multiplied by 50 and increased by 6. If the value entered is a string it should return "Error".

Note: in `C#`, you'll always get the input as a string, so the above applies if the string isn't representing a double value.

def problem(a):
    #Easy Points ^_^
    if type (a) == type ("lol"):
        return "Error"
    return a * 50 + 6


Solve in Python:
Make a function that will return a greeting statement that uses an input; your program should return, `"Hello,  how are you doing today?"`.

SQL: return results in a column named ```greeting```

*[Make sure you type the exact thing I wrote or the program may not execute properly]*

def greet(name):
    result = 'Hello, {0} how are you doing today?'.format(name)
    return result


Solve in Python:
Make a program that filters a list of strings and returns a list with only your friends name in it.

If a name has exactly 4 letters in it, you can be sure that it has to be a friend of yours! Otherwise, you can be sure he's not...

Ex: Input = ["Ryan", "Kieran", "Jason", "Yous"], Output = ["Ryan", "Yous"]

i.e.

Note: keep the original order of the names in the output.

def friend(lst):
    return [name for name in lst if len(name) == 4]


Solve in Python:
Make a program that takes a value (x) and returns "Bang" if the number is divisible by 3, "Boom" if it is divisible by 5, "BangBoom" if it divisible by 3 and 5, and "Miss" if it isn't divisible by any of them.
Note: Your program should only return one value

Ex: Input: 105 --> Output: "BangBoom"
Ex: Input: 9 --> Output: "Bang"
Ex:Input: 25 --> Output: "Boom"

def multiple(x):
    if x%15==0 : return "BangBoom"
    if x%3==0 : return "Bang"
    if x%5==0 : return "Boom"
    return "Miss"


Solve in Python:
Make multiple functions that will return the sum, difference, modulus, product, quotient, and the exponent respectively.

Please use the following function names:

addition = **add**

multiply = **multiply**

division = **divide** (both integer and float divisions are accepted)

modulus = **mod**

exponential = **exponent**

subtraction = **subt**

*Note: All math operations will be:
a (operation) b*

def add(a,b):
    return a+b
def multiply(a,b):
    return a*b
def mod(a,b):
    return a%b
def subt(a,b):
    return a-b
def  divide(a,b):
    return a/b
def  exponent(a,b):
    return a**b  #I solved this Kata on  8/2/2019  01:07 AM...#Hussam'sCodingDiary


Solve in Python:
Make the 2D list by the sequential integers started by the ```head``` number.

See the example test cases for the expected output.

```
Note:

-10**20 < the head number <10**20
1 <=  the number of rows <= 1000
0 <=  the number of columms <= 1000
```

import numpy as np

def make_2d_list(head,row,col):
    return np.array(list(range(head, head + row*col))).reshape(row, col).tolist()


Solve in Python:
Make your strings more nerdy: Replace all 'a'/'A' with 4, 'e'/'E' with 3 and 'l' with 1
e.g. "Fundamentals" --> "Fund4m3nt41s"

```if:csharp
Documentation:
Kata.Nerdify Method (String)

Nerdifies a string. Returns a copy of the original string with 'a'/'A' characters replaced with '4', 'e'/'E' characters replaced with '3', and 'l' characters replaced with '1'.

Syntax

public
static
string Nerdify(
string str
    )

Parameters

str

Type: System.String
The string to be nerdified.

Return Value

Type: System.String
  The nerdified string.

Exceptions

Exception
Condition

ArgumentNullException
str is null.

```

def nerdify(txt):
    tex=txt.replace('a','4')
    tex=tex.replace('A','4')
    tex=tex.replace('E','3')
    tex=tex.replace('e','3')
    return tex.replace('l','1')
    pass


Solve in Python:
Mance Rayder, the King-Beyond-the-Wall, has always wanted to lead the largest army the North has ever seen against the NIght’s Watch. For this humungous feat he has banded the waring tribes, the Giants, Thenns and Wildings, together by going to great extents. But the King is facing with an issue he always saw it coming.
The huge army is divided into smaller divisions and each division can be of the type $G, T$ or $W$ standing for Giants, Thenns and Wildings respectively. Mance doesn’t want two divisions of the same type standing together as he fears it might lead to a mutiny or an unorganised charge or retreat.
For a given numbers of $G, T$ and $W$, find whether an army can be organised in accordance to the rules set by Mance. Not to forget that Mance has to include all the divisions in his battle formation in order to stand a chance against the Wall’s defences.

-----Input:-----
- First line will contain $N$, the number of test cases.
- Each of the next $N$ lines will contain three integers $G$, $T$ and $W$ - the number of Giant, Thenn and Wildling divisions respectively.

-----Output:-----
For each testcase, output in a single line $Yes$ if a battle formation is possible or $No$ otherwise.

-----Constraints-----
- $1 \leq N \leq 100$
- $1 \leq G,T,W \leq 10^9$

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

-----Sample Output:-----
Yes

-----Explanation:-----
The first case can be formed as : $ TGWT $. Hence the answer is $ Yes $.

# cook your dish here
T = int(input())
for i in range(T):
 G,T,W = map(int,input().split())
 if G+T<W or G+W<T or W+T<G:
  print("No")
 else:
  print("Yes")


Solve in Python:
Mandarin chinese
, Russian and Vietnamese as well.
Chef is organising a contest with $P$ problems (numbered $1$ through $P$). Each problem has $S$ subtasks (numbered $1$ through $S$).
The difficulty of a problem can be calculated as follows:
- Let's denote the score of the $k$-th subtask of this problem by $SC_k$ and the number of contestants who solved it by $NS_k$.
- Consider the subtasks sorted in the order of increasing score.
- Calculate the number $n$ of valid indices $k$ such that $NS_k > NS_{k + 1}$.
- For problem $i$, the difficulty is a pair of integers $(n, i)$.
You should sort the problems in the increasing order of difficulty levels. Since difficulty level is a pair, problem $a$ is more difficult than problem $b$ if the number $n$ is greater for problem $a$ than for problem $b$, or if $a > b$ and $n$ is the same for problems $a$ and $b$.

-----Input-----
- The first line of the input contains two space-separated integers $P$ and $S$ denoting the number of problems and the number of subtasks in each problem.
- $2P$ lines follow. For each valid $i$, the $2i-1$-th of these lines contains $S$ space-separated integers $SC_1, SC_2, \dots, SC_S$ denoting the scores of the $i$-th problem's subtasks, and the $2i$-th of these lines contains $S$ space-separated integers $NS_1, NS_2, \dots, NS_S$ denoting the number of contestants who solved the $i$-th problem's subtasks.

-----Output-----
Print $P$ lines containing one integer each — the indices of the problems in the increasing order of difficulty.

-----Constraints-----
- $1 \le P \le 100,000$
- $2 \le S \le 30$
- $1 \le SC_i \le 100$ for each valid $i$
- $1 \le NS_i \le 1,000$ for each valid $i$
- in each problem, the scores of all subtasks are unique

-----Subtasks-----
Subtask #1 (25 points): $S = 2$
Subtask #2 (75 points): original constraints

-----Example Input-----
3 3
16 24 60
498 861 589
14 24 62
72 557 819
16 15 69
435 779 232

-----Example Output-----
2
1
3

from collections import defaultdict
from operator import itemgetter

p, s = map(int, input().split())

diff = []
for _ in range(p):
 sc = list(map(int, input().split()))
 nk = list(map(int, input().split()))

 arr_sort = list(zip(sc, nk))

 arr_sort.sort(key=lambda x: x[0])

 temp = 0
 for i in range(s-1):
  if arr_sort[i][1] > arr_sort[i+1][1]:
   temp += 1
 a = [temp, _+1]
 diff.append(a)

diff = sorted(diff, key = lambda x: x[0])

for i in diff:
 print(i[1])


Solve in Python:
Mandarin chinese
, Russian and Vietnamese as well.
Let's denote $S(x)$ by the sum of prime numbers that divides $x$.
You are given an array $a_1, a_2, \ldots, a_n$ of $n$ numbers, find the number of pairs $i, j$ such that $i \neq j$, $a_i$ divides $a_j$ and $S(a_i)$ divides $S(a_j)$.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- First line of each testcase contains one integer $n$ — number of elements of the array.
- Second line of each testcase contains $n$ space-separated integers $a_1, a_2, \ldots, a_n$.

-----Output:-----
For each testcase, output in a single line number of pairs that each of it satisfies given conditions.

-----Constraints-----
- $1 \leq T \leq 100$
- $2 \leq n, a_i \leq 10^6$
- the sum of $n$ for all test cases does not exceed $10^6$

-----Subtasks-----
Subtask #2 (20 points): $2 \leq n \leq 100$, $2 \leq a_i \leq 10^4$
Subtask #2 (80 points): original contsraints

-----Sample Input:-----
1
5
2 30 2 4 3

-----Sample Output:-----
6

-----EXPLANATION:-----
$S(2) = 2, S(30) = 2 + 3 + 5 = 10, S(4) = 2, S(3) = 3$. So using this information, the pairs of indicies are $(1,2)$, $(1, 3)$, $(1, 4)$, $(3, 1)$, $(3, 2)$, $(3, 4)$.

p=10**5+5
def Sieve():
 l=[True]*p
 s=[0]*p
 for i in range(2,p):
  if l[i]:
   for j in range(i,p,i):
    s[j]+=i
    l[j]=False
  i+=1
 l[0]=l[1]=False
 return l,s
isprime,s=Sieve()
from collections import defaultdict
good=defaultdict(list)
for i in range(2,p):
 for j in range(i,p,i):
  if s[j]%s[i]==0:
   good[i].append(j)
from collections import Counter
for _ in range(int(input())):
 n=int(input())
 l=[int(i) for i in input().split()]
 c=Counter(l)
 ans=0
 for i in range(2,p):
  if c[i]:
   for j in good[i]:
    ans+=c[i]*c[j]
 ans-=n
 print(ans)


Solve in Python:
Mandarin chinese
, Russian and Vietnamese as well.
You are given a grid with $n$ rows and $m$ columns. Each cell of this grid can either be empty or it contains one particle. It can never contain more than one particle. Let's denote the cell in the $i$-th row and $j$-th column by $(i, j)$, with the top left corner being $(0, 0)$. From a cell $(i, j)$, a particle could move in one of the following four directions:
- to the left, i.e. to the cell $(i, j - 1)$
- to the right, i.e. to the cell $(i, j + 1)$
- up, i.e. to the cell $(i - 1, j)$
- down, i.e. to the cell $(i + 1, j)$
It is not possible for a particle to move to a cell that already contains a particle or to a cell that does not exist (leave the grid).
It is possible to apply a force in each of these directions. When a force is applied in a given direction, all particles will simultaneously start moving in this direction as long as it is still possible for them to move.
You are given a sequence of forces. Each subsequent force is applied only after all particles have stopped moving. Determine which cells of the grid contain particles after all forces from this sequence are applied in the given order.

-----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 line of each test case contains two space-separated integers $n$ and $m$.
- $n$ lines describing the initial grid follow. For each $i$ ($1 \le i \le n$), the $i$-th of these lines contains a binary string with length $m$ describing the $i$-th row of the grid. For each $j$ ($1 \le j \le m$), if the $j$-th character of this string is '1', then the cell $(i, j)$ contains a particle, and if it is '0', then the cell $(i, j)$ is empty.
- The last line contains a single string $S$ describing the sequence of applied forces. Each character of this string corresponds to applying a force in some direction; forces applied in the directions left, right, up, down correspond to characters 'L', 'R', 'U', 'D'...

def main():
 for _ in range(int(input())):
  rows,column = map(int,input().split())
  arr = []
  for i in range(rows):
   arr.append(list(input()))
  string = input()
  last = string[-1]
  operation = Find(string,last)
  for i in string[0]+operation:
   if i == "L":
    arr = Left(arr)
   if i == "R":
    arr = Right(arr)
   if i == "U":
    arr = Transpose(arr)
    arr = Left(arr)
    arr = Transpose(arr)
   if i == "D":
    arr = Transpose(arr)
    arr = Right(arr)
    arr = Transpose(arr)
  for i in arr:
   print(i)
def Left(arr):
 for i in range(len(arr)):
  ans = arr[i].count("1")
  arr[i] = "1"*ans + (len(arr[i]) - ans)*"0"
 return arr
def Right(arr):
 for i in range(len(arr)):
  ans = arr[i].count("1")
  arr[i] = (len(arr[i]) - ans)*"0"+"1"*ans
 return arr
def Transpose(arr):
 ansss = []
 ans = list(map(list, zip(*arr)))
 for i in ans:
  ass = i
  hello = ""
  for j in ass:
   hello += j
  ansss.append(hello)
 return ansss
def Find(string,last):
 for i in string[-2::-1]:
  if last == "L":
   if i in ["D","U"]:
    last = i + last
    break
  if last == "R":
   if i in ["D","U"]:
    last = i + last
    break
  if last == "D":
   if i in ["L","R"]:
    last = i + last
    break
  if last == "U":
   if i in ["L","R"]:
    last = i + last
    break
 return last

def __starting_point():
 main()
__starting_point()


Solve in Python:
Many internet protocols these days include the option of associating a
media type with the content being sent.
The type is usually inferred from the file extension.
You are to write a program that facilitates the lookup of media types for
a number of files.
You will be given a table of media type associations that associate a certain
file extension with a certain media type.
You will then be given a number of file names, and tasked to determine the correct
media type for each file.
A file extension is defined as the part of the file name after the final period.
If a file name has no periods, then it has no extension and the media type cannot
be determined.
If the file extension is not present in the table, then the media type cannot be
determined.
In such cases you will print "unknown" as the media type.
If the file extension does appear in the table (case matters), then print the associated
media type.

-----Input-----
Input begins with 2 integers N and Q on a line.
N is the number of media type associations, and Q is the number of file names.
Following this are N lines, each containing a file extension and a media type, separated by a space.
Finally, Q lines, each containing the name of a file.
N and Q will be no greater than 100 each.
File extensions will consist only of alphanumeric characters, will have length at most 10, and will be distinct.
Media types will have length at most 50, and will contain only alphanumeric characters and punctuation.
File names will consist only of alphanumeric characters and periods and have length at most 50.

-----Output-----
For each of the Q file names, print on a line the media type of the file.
If there is no matching entry, print "unknown" (quotes for clarity).

-----Sample Input-----
5 6
html text/html
htm text/html
png image/png
svg image/svg+xml
txt text/plain
index.html
this.file.has.lots.of.dots.txt
nodotsatall
virus.exe
dont.let.the.png.fool.you
case.matters.TXT

-----Sample Output-----
text/html
text/plain
unknown
unknown
unknown
unknown

# cook your dish here
n,q=map(int,input().split())
x={}
for j in range(n):
 a,b=map(str,input().split())
 x[a]=b
for i in range(q):
 h=input().strip()
 if("." in h):
  c=h.split(".")[-1]
  if(c in x):
   print(x[c])
  else:
   print("unknown")
 else:
  print("unknown")


Solve in Python:
Many people choose to obfuscate their email address when displaying it on the Web. One common way of doing this is by substituting the `@` and `.` characters for their literal equivalents in brackets.

Example 1:
```
user_name@example.com
=> user_name [at] example [dot] com
```

Example 2:
```
af5134@borchmore.edu
=> af5134 [at] borchmore [dot] edu
```
Example 3:
```
jim.kuback@ennerman-hatano.com
=> jim [dot] kuback [at] ennerman-hatano [dot] com
```

Using the examples above as a guide, write a function that takes an email address string and returns the obfuscated version as a string that replaces the characters `@` and `.` with `[at]` and `[dot]`, respectively.

>Notes

>* Input (`email`) will always be a string object. Your function should return a string.

>* Change only the `@` and `.` characters.

>* Email addresses may contain more than one `.` character.

>* Note the additional whitespace around the bracketed literals in the examples!

def obfuscate(email):
    return email.replace("@", " [at] ").replace(".", " [dot] ")


Solve in Python:
Many things in this first paragraph are references to some pretty famous YouTube stars, so be careful about rephrasing. Thanks!
Michael, Kevin and Jake are sharing a cake, in celebration of their Webby award. They named it VCake. Unlike other cakes they considered, this one has finite volume and surface area. It's shaped as a normal rectangular cake with dimensions R centimeters by C centimeters. For the purposes of this problem, we can forget about three dimensions and think of a cake as just a 2D rectangle.
Chef will now cut the cake into three pieces, one for each person. However, the cake's shape and Chef's really old tools pose a few restrictions:

- Chef can only cut the cake, or a cake piece, across a line parallel to one of its sides.
- Chef can only cut the cake, or a cake piece, from end to end. That is, she cannot cut the cake partially.
- Chef can only cut the cake, or a cake piece, such that the sides of the resulting pieces (which will be rectangular in shape) are integers.

In addition, Michael, Kevin and Jake also have a few preferences of their own:

- They want their pieces to be connected (in one piece), and rectangular in shape.
- Michael wants his piece to have an area exactly M square centimeters. (Again, forget about a third dimension.)
- Kevin wants his piece to have an area exactly K square centimeters.
- Jake wants his piece to have an area exactly J square centimeters.

With these restrictions, Chef is at a loss. Is it possible for Chef to accomplish this task? Please note that the entire cake should be used. There should be no leftover cake.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
Each test case consists of a single line containing five space separated integers R, C M, K and J.

-----Output-----
For each test case, output a single line containing either “Yes” or “No” (without quotes), denoting whether Chef can accomplish the task or not.

-----Constraints-----
- 1 ≤ T ≤ 105
-...

def check2(r,x,k,j):
 if k%r==0 and j%r==0:
  return True
 if (k%x ==0) and j%x ==0:
  return True
 return False

def check(r,c,m,k,j):
 if m%r!=0:
  return False
 x = c - (m/r)
 return check2(r,x,k,j)

for _ in range(int(input())):
 r,c,m,k,j = list(map(int, input().split()))
 if r*c != m+k+j :
  print("No")
 else:
  b =False
  b|=check(r,c,m,k,j);
  b|=check(r,c,k,m,j);
  b|=check(r,c,j,m,k);
  b|=check(c,r,m,k,j);
  b|=check(c,r,k,m,j);
  b|=check(c,r,j,m,k);
  if b:
   print('Yes')
  else:
   print('No')