Solve in Python:
Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:

       You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
       After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)

Example:

Input: [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]

class Solution:
     def maxProfit(self, prices):
         """
         :type prices: List[int]
         :rtype: int
         """
         if not prices:
             return 0
         sell = hold = 0
         buy = -prices[0]

         for i in range(1, len(prices)):

             sell, hold, buy = max(buy + prices[i], 0), max(hold, sell), max(hold-prices[i], buy)

         return max(sell, hold)


Solve in Python:
Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most k transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Example 1:

Input: [2,4,1], k = 2
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.

Example 2:

Input: [3,2,6,5,0,3], k = 2
Output: 7
Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4.
             Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.

class Solution:
     def maxProfit(self, k, prices):
         """
         :type k: int
         :type prices: List[int]
         :rtype: int
         """
         '''
         https://www.youtube.com/watch?v=oDhu5uGq_ic

             i: number of transactions
             j: jth day

             Total[i][j] = max(T[i][j-1], max((price[j] - price[m]) + T[i-1][m] for m in range(0, j-1)))

             NOTEs:
                 1. use cache
                 2. no need to initialize a 2D array, it takes too long

         '''
         prices_length = len(prices)
         if prices_length == 0:
             return 0
         if k == 0:
             return 0

         # For N days, there will be at most N/2 transactions (N/2 buys and N/2 sells)
         # One buy + One sell = One transaction
         # When k is big enough to allow us buy/sell as many as we want, this becomes type-II
         # https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/
         if 2*k > (prices_length+1):
             profit = 0
             max_price = prices[0]
             min_price = prices[0]

             for p in prices:
                 if p < max_price:
                     profit += (max_price - min_price)
                     max_price = min_price = p
                 else:
                     max_price = p

             profit += (max_price - min_price)

             return profit

         # Generic solution
         candidate_max = float('-inf')
         profit = [0] * prices_length
         for trans in range(1, k+1):

             cache = -prices[0]
             max_profit = 0
             for d in range(1, prices_length):
                 if 2*trans > d+1: continue # For a given day, there are too many transaction allowed, no need to compute

                 cache = -prices[d-1] + profit[d-1] if -prices[d-1] + profit[d-1] > cache else cache
                 new_profit = prices[d] + cache

                 # profit[d-1]...


Solve in Python:
Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:

Input: [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
             Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.

Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

class Solution:
     def maxProfit(self, prices):
         """
         :type prices: List[int]
         :rtype: int
         """
         if not prices:
             return 0

         n = len(prices)

         sell1 = 0
         sell2 = 0
         hold1 = -prices[0]
         hold2 = -prices[0]

         for i in range(1, n):
             sell2 = max(prices[i] + hold2, sell2)
             hold2 = max(sell1 - prices[i], hold2)
             sell1 = max(prices[i] + hold1, sell1)
             hold1 = max(-prices[i], hold1)

             #sell1[i] = max(sell1[i-1], prices[i] + hold1[i-1])
             #hold1[i] = max(hold1[i-1],  -prices[i])
             #sell2[i] = max(prices[i] + hold2[i-1], sell2[i-1] )
             #hold2[i] = max(sell1[i-1] - prices[i], hold2[i-1])

         return sell2


Solve in Python:
Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
             Not 7-1 = 6, as selling price needs to be larger than buying price.

Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

class Solution:
     def maxProfit(self, prices):
         """
         :type prices: List[int]
         :rtype: int
         """
         curr_min = float('inf')
         max_profit = 0

         for price in prices:
             curr_min = min(curr_min, price)
             profit = price - curr_min
             max_profit = max(max_profit, profit)

         return max_profit


Solve in Python:
Scheduling is how the processor decides which jobs (processes) get to use the processor and for how long. This can cause a lot of problems. Like a really long process taking the entire CPU and freezing all the other processes. One solution is Round-Robin, which today you will be implementing.

Round-Robin works by queuing jobs in a First In First Out fashion, but the processes are only given a short slice of time. If a processes is not finished in that time slice, it yields the proccessor and goes to the back of the queue.

For this Kata you will be implementing the
```python
  def roundRobin(jobs, slice, index):
```

It takes in:

    1. "jobs" a non-empty positive integer array. It represents the queue and clock-cycles(cc) remaining till the job[i] is finished.

    2. "slice" a positive integer. It is the amount of clock-cycles that each job is given till the job yields to the next job in the queue.

    3. "index" a positive integer. Which is the index of the job we're interested in.

roundRobin returns:

    1. the number of cc till the job at index is finished.

Here's an example:
```
roundRobin([10,20,1], 5, 0)
at 0cc [10,20,1] jobs[0] starts
after 5cc [5,20,1] jobs[0] yields, jobs[1] starts
after 10cc [5,15,1] jobs[1] yields, jobs[2] starts
after 11cc [5,15,0] jobs[2] finishes, jobs[0] starts
after 16cc [0,15,0] jobs[0] finishes
```

so:
```
roundRobin([10,20,1], 5, 0) == 16
```

**You can assume that the processor can switch jobs between cc so it does not add to the total time.

def roundRobin(jobs, slice, index):
    i, res, jobs = 0, 0, jobs[:]
    while jobs[index]:
        res += min(slice, jobs[i])
        jobs[i] = max(0, jobs[i]-slice)
        i = (i+1)%len(jobs)
    return res


Solve in Python:
Scheduling is how the processor decides which jobs(processes) get to use the processor and for how long. This can cause a lot of problems. Like a really long process taking the entire CPU and freezing all the other processes. One solution is Shortest Job First(SJF), which today you will be implementing.

SJF works by, well, letting the shortest jobs take the CPU first. If the jobs are the same size then it is First In First Out (FIFO). The idea is that the shorter jobs will finish quicker, so theoretically jobs won't get frozen because of large jobs. (In practice they're frozen because of small jobs).

You will be implementing:
```python
  def SJF(jobs, index)
```

It takes in:

1. "jobs" a non-empty array of positive integers. They represent the clock-cycles(cc) needed to finish the job.
2. "index" a positive integer. That represents the job we're interested in.

SJF returns:

1. A positive integer representing the cc it takes to complete the job at index.

Here's an example:
```
SJF([3, 10, 20, 1, 2], 0)
at 0cc [3, 10, 20, 1, 2] jobs[3] starts
at 1cc [3, 10, 20, 0, 2] jobs[3] finishes, jobs[4] starts
at 3cc [3, 10, 20, 0, 0] jobs[4] finishes, jobs[0] starts
at 6cc [0, 10, 20, 0, 0] jobs[0] finishes
```

so:
```
SJF([3,10,20,1,2], 0) == 6
```

SJF = lambda jobs, index: sum(j for i, j in enumerate(jobs) if j <= jobs[index] and (jobs[i] != jobs[index] or i <= index))


Solve in Python:
Scheme? - Too loudly said. Just a new idea. Now Chef is expanding his business. He wants to make some new restaurants in the big city of Lviv. To make his business competitive he should interest customers. Now he knows how. But don't tell anyone -  it is a secret plan. Chef knows four national Ukrainian dishes - salo, borsch, varenyky and galushky. It is too few, of course, but enough for the beginning. Every day in his restaurant will be a dish of the day among these four ones. And dishes of the consecutive days must be different. To make the scheme more refined the dish of the first day and the dish of the last day must be different too. Now he wants his assistant to make schedule for some period. Chef suspects that there is more than one possible schedule. Hence he wants his assistant to prepare all possible plans so that he can choose the best one among them. He asks you for help. At first tell him how many such schedules exist. Since the answer can be large output it modulo 109 + 7, that is, you need to output the remainder of division of the actual answer by 109 + 7.

-----Input-----

The first line of the input contains an integer T, the number of test cases. Each of the following T lines contains a single integer N denoting the number of days for which the schedule should be made.

-----Output-----

For each test case output a single integer in a separate line, the answer for the corresponding test case.

-----Constraints-----1 ≤ T ≤ 100
2 ≤ N ≤ 109

-----Example-----
Input:
3
2
3
5

Output:
12
24
240

-----Explanation-----
Case 1. For N = 2 days we have the following 12 schedules:
First day Second day  salo   borsch    salo   varenyky    salo   galushky    borsch   salo    borsch   varenyky    borsch   galushky    varenyky   salo    varenyky   borsch    varenyky   galushky    galushky   salo    galushky   borsch    galushky   varenyky

Case 2. For N = 3 we have the following 24 schedules:
First daySecond dayThird day  salo   borsch   varenyky    salo   borsch   galushky    salo   varenyky   borsch ...


Solve in Python:
Scientists working internationally use metric units almost exclusively. Unless that is, they wish to crash multimillion dollars worth of equipment on Mars.

Your task is to write a simple function that takes a number of meters, and outputs it using metric prefixes.

In practice, meters are only measured in "mm" (thousandths of a meter), "cm" (hundredths of a meter), "m" (meters) and "km" (kilometers, or clicks for the US military).

For this exercise we just want units bigger than a meter, from meters up to yottameters, excluding decameters and hectometers.

All values passed in will be positive integers.
e.g.

```python
meters(5);
// returns "5m"

meters(51500);
// returns "51.5km"

meters(5000000);
// returns "5Mm"
```

See http://en.wikipedia.org/wiki/SI_prefix for a full list of prefixes

def meters(x):
    prefix, power = next((pair for pair in zip("YZEPTGMk", range(24, 0, -3)) if x >= 10 ** pair[1]), ("", 0))
    return "{:g}{}m".format(x / 10 ** power, prefix)


Solve in Python:
Screen resolution of Polycarp's monitor is $a \times b$ pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates $(x, y)$ ($0 \le x < a, 0 \le y < b$). You can consider columns of pixels to be numbered from $0$ to $a-1$, and rows — from $0$ to $b-1$.

Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.

Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.

-----Input-----

In the first line you are given an integer $t$ ($1 \le t \le 10^4$) — the number of test cases in the test. In the next lines you are given descriptions of $t$ test cases.

Each test case contains a single line which consists of $4$ integers $a, b, x$ and $y$ ($1 \le a, b \le 10^4$; $0 \le x < a$; $0 \le y < b$) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that $a+b>2$ (e.g. $a=b=1$ is impossible).

-----Output-----

Print $t$ integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.

-----Example-----
Input
6
8 8 0 0
1 10 0 3
17 31 10 4
2 1 0 0
5 10 3 9
10 10 4 8

Output
56
6
442
1
45
80

-----Note-----

In the first test case, the screen resolution is $8 \times 8$, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window. [Image]

from math import *

zzz = int(input())
for zz in range(zzz):
    a, b, x, y = list(map(int, input().split()))
    print(max(x*b, (a-x-1)*b, y*a, (b - y - 1)*a))


Solve in Python:
Sebi goes to school daily with his father. They cross a big highway in the car to reach to the school. Sebi sits in front seat beside his father at driving seat. To kill boredom, they play a game of guessing speed of other cars on the highway. Sebi makes a guess of other car's speed being SG kph, his father FG kph.

The highway is usually empty, so the drivers use cruise control, i.e. vehicles run at a constant speed. There are markers on the highway at a gap of 50 meters. Both father-son duo wants to check the accuracy of their guesses. For that, they start a timer at the instant at which their car and the other car (which speed they are guessing) are parallel to each other (they need not to be against some marker, they can be in between the markers too). After some T seconds, they observe that both the cars are next to some markers and the number of markers in between the markers of their car and the other car is D - 1 (excluding the markers next to both the cars). Also, they can observe these markers easily because the other car is faster than their. Speed of Sebi's father's car is S. Using this information, one can find the speed of the other car accurately.

An example situation when Sebi's father starts the timer. Notice that both the car's are parallel to each other.

Example situation after T seconds. The cars are next to the markers. Here the value of D is 1. The green car is Sebi's and the other car is of blue color.

Sebi's a child, he does not know how to find the check whose guess is close to the real speed of the car. He does not trust his father as he thinks that he might cheat. Can you help to resolve this issue between them by telling whose guess is closer. If Sebi's guess is better, output "SEBI". If his father's guess is better, output "FATHER". If both the guess are equally close, then output "DRAW".

-----Input-----
The first line of the input contains an integer T denoting the number of test cases.
Each of the next T lines contain five space separated integers S, SG, FG, D, T...

# cook your dish here
for _ in range(int(input())):
    S, SG, FG, D, T = map(int, input().split())
    speed = (D*180)/T + S
    if abs(SG-speed) == abs(FG-speed):
        print('DRAW')
    elif abs(SG-speed) > abs(FG-speed):
        print('FATHER')
    else:
        print('SEBI')


Solve in Python:
Sebi lives in Chefland where the government is extremely corrupt that usually makes fool out of public by announcing eye catching but non-sustainable schemes. Recently there was a move to increase tourism in the country that was highly lauded. Sebi wants to examine whether the move has some potential or is a hogwash as usual.
The Chefland is a city with very old road infrastructure. The city has N tourist places. All the places are reachable from each other. The corrupt administrators of the city constructed as few roads as possible just ensuring that all the places are reachable from each other, and those too have now gone old with potholes every here and there. Upon this, there is a toll tax for each road too, which you have to pay once for using that road. Once you pay the tax for a road, you can visit it again as many times as possible.
The tourists coming to Chefland usually want to see all the N nice places. They usually have visit in their own vehicle and stay for few days. Also, they are usually not very rich, they want to pay as less toll tax as possible. For promoting tourism, the government offered their citizens a scheme. It was announced that citizens can choose any two places and the government will build a high class road between those two places and that too without any toll tax. Note that citizens may choose to have a high class road between two cities which already have an old road between them.
Sebi is very sceptical of the claims of the announcement. So, he wants to understand the expected toll tax a tourist has to pay to tour the entire city considering that the citizens of Chefland vote for the two cities for constructing high road uniformly randomly. Can you please him in finding this?

-----Input-----
There is a single test case per test file.
The first line of the input contains an integer N denoting the number of tourist spots in Chefland.
Each of the he next N - 1 lines contains three space separated integers u, v, c, denoting that there is a road between tourist spot u and v which...

n = int(input())
size = {}
parent = {}

for i in range(1,n+1):
 size[i] = 1
 parent[i] = i

def find(a):
 if parent[a]==a:
  return a
 parent[a] = find(parent[a])
 return parent[a]

edges = []

for i in range(n-1):
 edges.append(list(map(int,input().split())))

edges.sort(key = lambda x:x[2])

c = 0
s = 0
t = 0

for i in range(n-1):
 a = find(edges[i][0])
 b = find(edges[i][1])
 c += edges[i][2]
 s += size[a]*size[b]*edges[i][2]
 t += size[a]*size[b]
 if size[a]>size[b]:
  size[a] += size[b]
  parent[b] = a
 else:
  size[b] += size[a]
  parent[a] = b

print("%.6f" % (c - float(s)/t))


Solve in Python:
Section numbers are strings of dot-separated integers. The highest level sections (chapters) are numbered 1, 2, 3, etc. Second level sections are numbered 1.1, 1.2, 1.3, 2.1, 2.2, 2.3, etc. Next level sections are numbered 1.1.1, 1.1.2, 1.1.2, 1.2.1, 1.2.2, erc. There is no bound on the number of sections a document may have, nor is there any bound on the number of levels.

A section of a certain level may appear directly inside a section several levels higher without the levels between. For example, section 1.0.1 may appear directly under section 1, without there being any level 2 section. Section 1.1 comes after section 1.0.1. Sections with trailing ".0" are considered to be the same as the section with the trailing ".0" truncated. Thus, section 1.0 is the same as section 1, and section 1.2.0.0 is the same as section 1.2.

```if:python
Write a function `compare(section1, section2)` that returns `-1`, `0`, or `1` depending on whether `section1` is before, same as, or after `section2` respectively.
```
```if:javascript
Write a function `cmp(section1, section2)` that returns `-1`, `0`, or `1` depending on whether `section1` is before, same as, or after `section2` respectively.
```
```if:haskell
Write a function `cmp section1 section2` that returns `LT`, `EQ` or `GT` depending on whether `section1` is before, same as, or after `section2` respectively.
```

def compare(s1, s2):
    s1 , s2 = s1.split('.') , s2.split('.')
    for i in range(abs(len(s1)-len(s2))): min(s1,s2,key = len).append('0')
    for num1 , num2 in zip(s1 , s2):
        num1 , num2 = int(num1) , int(num2)
        if num1 > num2: return 1
        elif num1 < num2: return -1
    return 0


Solve in Python:
See the following triangle:
```
____________________________________
 1
 2   4   2
 3   6   9   6   3
 4   8   12  16  12  8   4
 5   10  15  20  25  20  15  10  5
 ___________________________________

```
The total sum of the numbers in the triangle, up to the 5th line included, is ```225```, part of it, ```144```, corresponds to the total sum of the even terms and ```81``` to the total sum of the odd terms.

Create a function that may output an array with three results for each value of n.
```python
triang_mult(n)  ----> [total_sum, total_even_sum, total_odd_sum]
```
Our example will be:
```python
triang_mult(5) ----> [225, 144, 81]
```

Features of the random tests:
```
number of tests = 100
49 < n < 5000
```
Enjoy it!
This kata will be translated in another languages soon

def mult_triangle(n):
  s = n*(n + 1)//2
  s *= s
  d = (n + 1)//2
  d *= d
  return [s, s - d*d, d*d]


Solve in Python:
Sereja has a bracket sequence s_1, s_2, ..., s_{n}, or, in other words, a string s of length n, consisting of characters "(" and ")".

Sereja needs to answer m queries, each of them is described by two integers l_{i}, r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence s_{l}_{i}, s_{l}_{i} + 1, ..., s_{r}_{i}. Help Sereja answer all queries.

You can find the definitions for a subsequence and a correct bracket sequence in the notes.

-----Input-----

The first line contains a sequence of characters s_1, s_2, ..., s_{n} (1 ≤ n ≤ 10^6) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 10^5) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers l_{i}, r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n) — the description of the i-th query.

-----Output-----

Print the answer to each question on a single line. Print the answers in the order they go in the input.

-----Examples-----
Input
())(())(())(
7
1 1
2 3
1 2
1 12
8 12
5 11
2 10

Output
0
0
2
10
4
6
6

-----Note-----

A subsequence of length |x| of string s = s_1s_2... s_{|}s| (where |s| is the length of string s) is string x = s_{k}_1s_{k}_2... s_{k}_{|}x| (1 ≤ k_1 < k_2 < ... < k_{|}x| ≤ |s|).

A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.

For the third query required sequence will be «()».

For the fourth query required sequence will be «()(())(())».

import sys
input = sys.stdin.readline

s = input()

M = int(input())

def next_pow_2(n):
    p = 1
    while p < n:
        p <<= 1
    return p

def represented_range(node, size):
    l = node
    r = node
    while l < size:
        l = 2*l
        r = 2*r + 1
    return l-size, r-size

class SegTree:
    def __init__(self, size):
        self.size = next_pow_2(size)
        self.answer = [0] * (2*self.size)
        self.opened = [0] * (2*self.size)
        self.closed = [0] * (2*self.size)

    # O(size * (O(func) + O(init))
    def build(self, s):
        for i in range(self.size):
            self.answer[self.size + i] = 0
            self.opened[self.size + i] = 1 if i < len(s) and s[i] == '(' else 0
            self.closed[self.size + i] = 1 if i < len(s) and s[i] == ')' else 0

        for i in range(self.size - 1, 0, -1):
            matched = min(self.opened[2*i], self.closed[2*i+1])
            self.answer[i] = self.answer[2*i] + self.answer[2*i+1] + matched
            self.opened[i] = self.opened[2*i] + self.opened[2*i+1] - matched
            self.closed[i] = self.closed[2*i] + self.closed[2*i+1] - matched

    # O(log(size)), [l,r]
    def query(self, l, r):
        l += self.size
        r += self.size

        eventsR = []
        answer = 0
        opened = 0
        while l <= r:
            if l & 1:
                matched = min(self.closed[l], opened)
                answer += self.answer[l] + matched
                opened += self.opened[l] - matched
                l += 1
            if not (r & 1):
                eventsR.append((self.answer[r], self.opened[r], self.closed[r]))
                r -= 1
            l >>= 1
            r >>= 1

        for i in range(len(eventsR)-1, -1, -1):
            a, o, c = eventsR[i]
            matched = min(c, opened)
            answer += a + matched
            opened += o - matched

        return answer

seg = SegTree(len(s))
seg.build(s)

for i in range(M):
    l, r = [int(_) for _ in input().split()]
    print(2*seg.query(l-1, r-1))


Solve in Python:
Sereja has a string A consisting of n lower case English letters.

Sereja calls two strings X and Y each of length n similar if they can be made equal by applying the following operation at most once in each of them.

- Chose any two position i, j in the string (i can be equal to j too). Swap the characters at position i with character at position j.

For example strings "abcd" and "acbd" are similar, strings "ab" and "ab" are similar, but strings "abcde" and "bcdea" are not similar. Note that strings  "abc" and "cab" are also similar, as you can swap 'a' and 'c' in the first string to get "cba" and 'a' and 'b' in the second string to get "cba".

Now Sereja is interested in finding number of ordered pairs of non similar strings X and Y such that they can be constructed from a given string A by permutation of its characters. As answer could be large, please output your answer modulo  (109 + 7).

Note

A string s (of size n) is said to be constructed from string t (also of size n) by permutation of its characters if there exists a permutation P (of length n), such that s[i] = t[P[i]] for each i from 1 to n.

-----Input-----
- First line contain integer T - number of test cases.
- For each of the next T lines:

- Each line contains a string A as defined in the problem.

-----Output-----
For each test case, output answer modulo 1000000007 (109 + 7) in separate line.

-----Constraints-----
- 1 ≤ T ≤  10
- 1 ≤ n ≤  10^5

-----Constraints-----
- Subtask #1: 1 ≤ n ≤  10  (25 points)
- Subtask #2: 1 ≤ n ≤  100  (25 points)
- Subtask #3: 1 ≤ n ≤  1000  (25 points)
- Subtask #4: original constraints (25 points)

-----Example-----
Input:
2
z
abcd

Output:
0
144

import math
def combi(a,b):
	if a < b:
		return 0
	if a == 1:
		return 1
	if b < a/2:
		b = a - b
	temp = 1
	for i in range(b + 1,a + 1):
		temp *= i
	temp /= math.factorial(a - b)
	return temp
for _ in range(eval(input())):
	mod = 10**9 + 7
	string1 = input()
	n = len(string1)
	dict1 = {}
	count = 0
	alpha = set()
	for ele in string1:
		if ele in dict1:
			dict1[ele] += 1
		else:
			dict1[ele] = 1
			alpha.add(ele)
			count += 1

	count_list = []
	total = 1
	rem = n
	for ele in alpha:
		total = (total % mod) * (combi(rem,dict1[ele]) % mod)%mod
		rem -= dict1[ele]
		count_list.append(dict1[ele])

	sum_list = [n - count_list[0]]
	for i in range(1,count):
		sum_list.append(sum_list[i - 1] - count_list[i])

	sub_2 = 0
	sub = 0
	for i in count_list:
		sub_2 += (n - i) * i
	sub_2 /= 2
	# print sub_2

	sub_3 = 0
	for i in range(count):
		for j in range(i + 1,count):
			sub_3 += count_list[i] * count_list[j] * sum_list[j]

	sub_3 = 2 * sub_3

	sub_4_4 = 0
	for i in range(count):
		for j in range(i + 1,count):
			for k in range(j + 1,count):
				sub_4_4 += count_list[i] * count_list[j] * count_list[k] * sum_list[k]

	sub_4_4 *= 3
	sub_4_2 = 0
	for i in range(count):
		for j in range(i + 1,count):
			sub_4_2 += (count_list[i] * (count_list[i] - 1) * count_list[j] * (count_list[j] - 1))/4

	sub_4_3 = 0
	for i in range(count):
		temp = 0
		for j in range(count):
			if j != i:
				temp += count_list[j] * (n - count_list[i] - count_list[j])
		temp /= 2
		sub_4_3 += ((count_list[i] * (count_list[i] - 1)) * temp)/2
		# print sub_4_3
	sub_4_3 *= 2
	print(((total)* (total - 1 - (((sub_3 + sub_2)%mod + (sub_4_4 +sub_4_3)%mod)%mod + sub_4_2%mod)))% mod)


Solve in Python:
Sereja has an array A of N positive integers : A[1], A[2], A[3], ... , A[N].

In a single operation on the array, he performs the following two steps :

- Pick two indices i, j s.t. A[i] > A[j]
- A[i] -= A[j]

Sereja can apply these operations any number of times (possibly zero), such that the sum of resulting elements of the array is as small as possible.

Help Sereja find this minimum sum.

-----Input-----

First line of input contains an integer T - the number of test cases. T test cases follow.

First line of each test case contains the integer N. The next line contains N integers — A[1], A[2], A[3], ... , A[N].

-----Output-----
For each test case, output a single line with the answer.

-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 105
- 1 ≤ A[i] ≤ 109

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

Output:
1
6

-----Explanation-----
Example case 2. In this case, one possible way in which Sereja can perform the operations could be as follows.

-  Pick i = 2, j = 1. A[2] -= A[1]. Now the resulting array would be [2, 2, 6].
-  Pick i = 3, j = 2. A[3] -= A[2]. Now the resulting array would be [2, 2, 4].
-  Pick i = 3, j = 2. A[3] -= A[2]. Now the resulting array would be [2, 2, 2].

As the resulting array is [2 2 2], so the sum is 6.

from functools import reduce
def GCD(a,b):

 a = abs(a)
 b = abs(b)
 while a:

  a, b = b%a, a
 return b

def GCD_List(list):

 return reduce(GCD, list)
a=eval(input())
while(a):

 x=eval(input())
 b=list(map(int,input().split()))
 print(GCD_List(b)*x)

 a-=1


Solve in Python:
Sereja has two integers — A and B — in 7-ary system. He wants to calculate the number C, such that B * C = A. It is guaranteed that B is a divisor of A.

Please, help Sereja calculate the number C modulo 7L.

-----Input-----

First line of input contains an integer T — the number of test cases. T tests follow.

For each test case, the first line contains the integer A, and the second line contains the integer B, and the third line contains the integer L. A and B are given in 7-ary system.

-----Output-----
Output the answer in 7-ary system.

-----Constraints-----
- 1 ≤ T ≤ 10
- A and B are both positive integers.
- Length of A is a positive integer and doesn't exceed 106.
- L and length of B are positive integers and do not exceed 10000.

-----Subtasks-----
- Sub task #1 (20 points): Length of A is a positive integer and doesn't exceed 20.
- Sub task #2 (30 points): Length of A is a positive integer and doesn't exceed 2000.
- Sub task #3 (50 points): Original constraints.

-----Example-----
Input:3
21
5
10
202
13
1
202
13
2

Output:3
3
13


Solve in Python:
Sereja have array A' that contain N integers. Now Sereja want to permute elements of the array, he want to use some permutation p, such that A[i] = A'[p[i]], where A - new array.

Lets function f(A,i) = S - A[i] - A[i +1] - ... - A[j], where j is the maximum possible index, such that A[i] + A[i + 1] + ... + A[j] <= S, if A[i] > S, f(A, i) = S.

Help Sereja to find such permutation p, such that (f(A, 1) + f(A, 2) + ... f(A, k))/k will be as low as possible.

-----Input-----

First line of input contain integer T - number of testcases. Next lines contain T testcases. First line of each testcase contain three integers N, k, S. Next line contain N integers - array A'.

-----Output-----

For each testcase output N numbers in one line - permutation p.

-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 2000
- 1 ≤ k ≤ N
- 1 ≤ A'[i] ≤ 10^4
- 1 ≤ S ≤ 10^9

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

Output:
2 1 3
4 3 2 1

-----Scoring-----

Suppose Sum will be sum of yours (f(A, 1) + f(A, 2) + ... f(A, k))/k per each testcase.
Lets B will be the smallest such sum. Your score will be equal to B/Sum. Lower scores will earn more points.

We have 20 official test files. You must correctly solve all test files to receive OK. During the contest, your overall score is the sum of the scores on the first 4 test files. After the contest, all solutions will be rescored by the sum of the scores on the rest 16 test files. Note, that public part of the tests may not contain some border cases.

import random
t = int(input())
while t>0:
    t -= 1

    n, k, s = list(map(int, input().split()))
    arr = list(map(int, input().split()))
    temp = sorted(list(range(n)), key=lambda x:arr[x])
    arr.sort()
    for j in range(5):
        for i in range(n-1):
            if arr[i]+arr[i+1] > s:
                arr[i], arr[i+1] = arr[i+1], arr[i]
                temp[i], temp[i+1] = temp[i+1], temp[i]
    ans = [str(i+1) for i in temp]
    print(' '.join(ans))


Solve in Python:
Sereja is hosting his birthday dinner. He invited his N close friends. Let us number the people from 1 to N according to the order in which they arrive at the event. The dinner is being held in long straight corridor in which people sit in a way such that they won't leave any empty space in between two consecutive persons at any given time.

When a person number i arrives at the corridor, he must go and stand to the immediate right of the person numbered A[i] (if A[i] = 0, then this person just stands at the leftmost end of the line).

But there is a problem, as there is no space between two consecutive persons at any given time, so for this person to sit, space must be created by moving either all the persons to left of the place to the left one step each, or all the persons to right of the place to the right one step each.

Now, Sereja is wondering about what could be the minimum number of steps people will take so as to sit in the dinner party. Please find it fast, so that Sereja can peacefully entertain his guests.

-----Input-----
First line of input contain an integer T — the number of test cases. T tests follow.
First line of each test case contain the integer N, and the next line contains N integers — A[1], A[2], ... , A[N].

-----Output-----
For each test case, output a single line with the answer — the minimal number of steps required.

-----Constraints-----
- 1 ≤ T ≤ 100
- 1 ≤ N ≤ 100
- 0 ≤ A[i] < i

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

Output:
0
0
3

-----Explanation-----
Example case 3.
- First three persons don't need any steps to sit. The line after the arrangement of these persons will look like [1, 2, 3].

- When person #4 comes in, he wants to sit to the right of person 1, so we need to either move the first person to the left, or the second and third persons to the right. The first case is clearly better. Now the line will look like [1, 4, 2, 3].

- When person #5 arrives, he will need to move 2 persons in either case. The final arrangement will be [1, 4, 5, 2, 3]....

for t in range(int(input())):
 n = int(input())
 s = []
 a = list(map(int,input().split()))
 steps = 0
 for i in range(n):
  if (a[i] == 0):
   s = [i+1] + s
  else:
   pos = s.index(a[i])+1
   steps += min(pos, i-pos)
   s = s[:pos]+[i+1]+s[pos:]
 print(steps)


Solve in Python:
Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q_1q_2... q_{k}. The algorithm consists of two steps:

  Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2.  Rearrange the letters of the found subsequence randomly and go to step 1.

Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.

Sereja wants to test his algorithm. For that, he has string s = s_1s_2... s_{n}, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring s_{l}_{i}s_{l}_{i} + 1... s_{r}_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (l_{i}, r_{i}) determine if the algorithm works correctly on this test or not.

-----Input-----

The first line contains non-empty string s, its length (n) doesn't exceed 10^5. It is guaranteed that string s only contains characters: 'x', 'y', 'z'.

The second line contains integer m (1 ≤ m ≤ 10^5) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers l_{i}, r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n).

-----Output-----

For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise.

-----Examples-----
Input
zyxxxxxxyyz
5
5 5
1 3
1 11
1 4
3 6

Output
YES
YES
NO
YES
NO

-----Note-----

In the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on...

def f(x, y, z): return max(x, y, z) - min(x, y, z) > 1
t = input()
n, m, p = len(t), int(input()), {'x': 0, 'y': 1, 'z': 2}
s = [[0] * (n + 1) for i in range(3)]
for i, c in enumerate(t, 1): s[p[c]][i] = 1
for i in range(3):
    r = s[i]
    for j in range(1, n): r[j + 1] += r[j]
a, b, c = s
q, d = [map(int, input().split()) for i in range(m)], ['YES'] * m
for i, (l, r) in enumerate(q):
    if r - l > 1 and f(a[r] - a[l - 1], b[r] - b[l - 1], c[r] - c[l - 1]): d[i] = 'NO'
print('\n'.join(d))


Solve in Python:
Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm.

Sereja takes a blank piece of paper. Then he starts writing out the sequence in m stages. Each time he either adds a new number to the end of the sequence or takes l first elements of the current sequence and adds them c times to the end. More formally, if we represent the current sequence as a_1, a_2, ..., a_{n}, then after we apply the described operation, the sequence transforms into a_1, a_2, ..., a_{n}[, a_1, a_2, ..., a_{l}] (the block in the square brackets must be repeated c times).

A day has passed and Sereja has completed the sequence. He wonders what are the values of some of its elements. Help Sereja.

-----Input-----

The first line contains integer m (1 ≤ m ≤ 10^5) — the number of stages to build a sequence.

Next m lines contain the description of the stages in the order they follow. The first number in the line is a type of stage (1 or 2). Type 1 means adding one number to the end of the sequence, in this case the line contains integer x_{i} (1 ≤ x_{i} ≤ 10^5) — the number to add. Type 2 means copying a prefix of length l_{i} to the end c_{i} times, in this case the line further contains two integers l_{i}, c_{i} (1 ≤ l_{i} ≤ 10^5, 1 ≤ c_{i} ≤ 10^4), l_{i} is the length of the prefix, c_{i} is the number of copyings. It is guaranteed that the length of prefix l_{i} is never larger than the current length of the sequence.

The next line contains integer n (1 ≤ n ≤ 10^5) — the number of elements Sereja is interested in. The next line contains the numbers of elements of the final sequence Sereja is interested in. The numbers are given in the strictly increasing order. It is guaranteed that all numbers are strictly larger than zero and do not exceed the length of the resulting sequence. Consider the elements of the final sequence numbered starting from 1 from the beginning to the end of the sequence.

Please, do not use the %lld specifier to read or write 64-bit integers in...

from bisect import bisect_left
m = int(input())
t, s = [input().split() for i in range(m)], [0] * m
l, n = 0, int(input())
for j, i in enumerate(t):
    l += 1 if i[0] == '1' else int(i[1]) * int(i[2])
    t[j], s[j] = l, i[1] if i[0] == '1' else int(i[1])
F = {}
def f(i):
    if not i in F:
        k = bisect_left(t, i)
        F[i] = s[k] if type(s[k]) == str else f((i - t[k] - 1) % s[k] + 1)
    return F[i]
print(' '.join(f(i) for i in map(int, input().split())))


Solve in Python:
Serge came to the school dining room and discovered that there is a big queue here. There are $m$ pupils in the queue. He's not sure now if he wants to wait until the queue will clear, so he wants to know which dish he will receive if he does. As Serge is very tired, he asks you to compute it instead of him.

Initially there are $n$ dishes with costs $a_1, a_2, \ldots, a_n$. As you already know, there are the queue of $m$ pupils who have $b_1, \ldots, b_m$ togrogs respectively (pupils are enumerated by queue order, i.e the first pupil in the queue has $b_1$ togrogs and the last one has $b_m$ togrogs)

Pupils think that the most expensive dish is the most delicious one, so every pupil just buys the most expensive dish for which he has money (every dish has a single copy, so when a pupil has bought it nobody can buy it later), and if a pupil doesn't have money for any dish, he just leaves the queue (so brutal capitalism...)

But money isn't a problem at all for Serge, so Serge is buying the most expensive dish if there is at least one remaining.

Moreover, Serge's school has a very unstable economic situation and the costs of some dishes or number of togrogs of some pupils can change. More formally, you must process $q$ queries:

  change $a_i$ to $x$. It means that the price of the $i$-th dish becomes $x$ togrogs.  change $b_i$ to $x$. It means that the $i$-th pupil in the queue has $x$ togrogs now.

Nobody leaves the queue during those queries because a saleswoman is late.

After every query, you must tell Serge price of the dish which he will buy if he has waited until the queue is clear, or $-1$ if there are no dishes at this point, according to rules described above.

-----Input-----

The first line contains integers $n$ and $m$ ($1 \leq n, m \leq 300\ 000$) — number of dishes and pupils respectively. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^{6}$) — elements of array $a$. The third line contains $m$ integers $b_1, b_2, \ldots, b_{m}$ ($1 \leq b_i \leq 10^{6}$) —...

import sys
from itertools import accumulate
class Lazysegtree:
    #RAQ
    def __init__(self, A, intv, initialize = True, segf = min):
        #区間は 1-indexed で管理
        self.N = len(A)
        self.N0 = 2**(self.N-1).bit_length()
        self.intv = intv
        self.segf = segf
        self.lazy = [0]*(2*self.N0)
        if initialize:
            self.data = [intv]*self.N0 + A + [intv]*(self.N0 - self.N)
            for i in range(self.N0-1, 0, -1):
                self.data[i] = self.segf(self.data[2*i], self.data[2*i+1])
        else:
            self.data = [intv]*(2*self.N0)

    def _ascend(self, k):
        k = k >> 1
        c = k.bit_length()
        for j in range(c):
            idx = k >> j
            self.data[idx] = self.segf(self.data[2*idx], self.data[2*idx+1]) \
            + self.lazy[idx]

    def _descend(self, k):
        k = k >> 1
        idx = 1
        c = k.bit_length()
        for j in range(1, c+1):
            idx = k >> (c - j)
            ax = self.lazy[idx]
            if not ax:
                continue
            self.lazy[idx] = 0
            self.data[2*idx] += ax
            self.data[2*idx+1] += ax
            self.lazy[2*idx] += ax
            self.lazy[2*idx+1] += ax

    def query(self, l, r):
        L = l+self.N0
        R = r+self.N0
        Li = L//(L & -L)
        Ri = R//(R & -R)
        self._descend(Li)
        self._descend(Ri - 1)

        s = self.intv
        while L < R:
            if R & 1:
                R -= 1
                s = self.segf(s, self.data[R])
            if L & 1:
                s = self.segf(s, self.data[L])
                L += 1
            L >>= 1
            R >>= 1
        return s

    def add(self, l, r, x):
        L = l+self.N0
        R = r+self.N0

        Li = L//(L & -L)
        Ri = R//(R & -R)

        while L < R :
            if R & 1:
                R -= 1
                self.data[R] += x
               ...


Solve in Python:
Sergey Semyonovich is a mayor of a county city N and he used to spend his days and nights in thoughts of further improvements of Nkers' lives. Unfortunately for him, anything and everything has been done already, and there are no more possible improvements he can think of during the day (he now prefers to sleep at night). However, his assistants have found a solution and they now draw an imaginary city on a paper sheet and suggest the mayor can propose its improvements.

Right now he has a map of some imaginary city with $n$ subway stations. Some stations are directly connected with tunnels in such a way that the whole map is a tree (assistants were short on time and enthusiasm). It means that there exists exactly one simple path between each pair of station. We call a path simple if it uses each tunnel no more than once.

One of Sergey Semyonovich's favorite quality objectives is the sum of all pairwise distances between every pair of stations. The distance between two stations is the minimum possible number of tunnels on a path between them.

Sergey Semyonovich decided to add new tunnels to the subway map. In particular, he connected any two stations $u$ and $v$ that were not connected with a direct tunnel but share a common neighbor, i.e. there exists such a station $w$ that the original map has a tunnel between $u$ and $w$ and a tunnel between $w$ and $v$. You are given a task to compute the sum of pairwise distances between all pairs of stations in the new map.

-----Input-----

The first line of the input contains a single integer $n$ ($2 \leq n \leq 200\,000$) — the number of subway stations in the imaginary city drawn by mayor's assistants. Each of the following $n - 1$ lines contains two integers $u_i$ and $v_i$ ($1 \leq u_i, v_i \leq n$, $u_i \ne v_i$), meaning the station with these indices are connected with a direct tunnel.

It is guaranteed that these $n$ stations and $n - 1$ tunnels form a tree.

-----Output-----

Print one integer that is equal to the sum of distances between all pairs of...

import sys
import threading
sys.setrecursionlimit(2100000)

def main():
    def counter(graph,vert,memo,pard=None):
        d = 0
        for c in graph[vert]:
            if c!=pard:
                if len(graph[c])==1:
                    memo[c]=0
                else:
                    memo[c]=counter(graph, c, memo, vert)[0]
                d += memo[c]+1
        return((d, memo))

    n=int(input())
    vizinhos=[]

    for _ in range(n):
        vizinhos.append([])

    for _ in range(n-1):
        i, j=map(int, input().split())
        vizinhos[i-1].append(j-1)
        vizinhos[j-1].append(i-1)

    same=1
    layer=[0]
    par=[None]
    j=0
    while layer:
        j+=1
        n_layer=[]
        n_pars=[]
        for i in range(len(layer)):
            for vert in vizinhos[layer[i]]:
                if vert!=par[i]:
                    n_layer.append(vert)
                    n_pars.append(layer[i])
        layer=n_layer
        par=n_pars
        if j%2==0:
            same+=len(layer)
    bipartite = same*(n-same)
    info=counter(vizinhos,0,[None]*n)[1]
    dist=0
    for g in info:
        if g!=None:
           dist += (g+1)*(n-g-1)
    print((dist+bipartite)//2)

threading.stack_size(140000000)
main_thread=threading.Thread(target=main)
main_thread.start()
main_thread.join()


Solve in Python:
Sergey recently learned about country codes - two letter strings, denoting countries. For example, BY stands for Belarus and IN stands for India. Mesmerized by this new discovery, Sergey now looks for country codes everywhere!
Sergey has recently found a string S consisting of uppercase Latin letters. He wants to find the number of different country codes that appear in S as contiguous substrings. For the purpose of this problem, consider that every 2-letter uppercase string is a valid country code.

-----Input-----
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first and only line of each test case contains a string S, consisting of uppercase Latin letters.

-----Output-----
For each test case, output a single line containing the number of different country codes appearing in the given string.

-----Constraints-----

- 1 ≤ T ≤ 100
- Subtask 1 (35 points): 2 ≤ |S| ≤ 3
- Subtask 2 (65 points): 2 ≤ |S| ≤ 104

-----Example-----
Input:2
INBY
BYBY

Output:3
2

-----Explanation-----
Example case 1. The codes are IN, NB and BY.
Example case 2. The codes are BY and YB.

for _ in range(int(input())):
    a=input()
    s=set([])
    for i in range(len(a)-1):
        s.add(a[i:i+2])
    print(len(s))


Solve in Python:
Seven is a hungry number and its favourite food is number 9. Whenever it spots 9
through the hoops of 8, it eats it! Well, not anymore, because you are
going to help the 9 by locating that particular sequence (7,8,9) in an array of digits
and tell 7 to come after 9 instead. Seven "ate" nine, no more!
(If 9 is not in danger, just return the same array)

def hungry_seven(arr):

    nums = ''.join(str(a) for a in arr)

    while '789' in nums:
        nums = nums.replace('789','897')

    return [int(n) for n in nums]


Solve in Python:
Share price
===========

You spent all your saved money to buy some shares.

You bought it for `invested`, and want to know how much it's worth, but all the info you can quickly get are just the change the shares price made in percentages.

Your task:
----------
Write the function `sharePrice()` that calculates, and returns the current price of your share, given the following two arguments:

- `invested`(number), the amount of money you initially invested in the given share

- `changes`(array of numbers), contains your shares daily movement percentages

The returned number, should be in string format, and it's precision should be fixed at 2 decimal numbers.

Have fun!

>**Hint:** Try to write the function in a functional manner!

def share_price(invested, changes):
    for change in changes:
        invested = invested + ( invested * (change/100.00) )
    return "%.2f" % invested


Solve in Python:
Shashank is playing a game with his friends.
There are n sticks located in a row at points $a_1,a_2, ...,a_n$. Each stick has a height- $h_i$. A person can chop a stick down, after which it takes over one of the regions [$a_i$ - $h_i$, $a_i$] or [$a_i$, $a_i$ + $h_i$]. The stick that is not chopped remains at the point $a_i$. A person can chop a stick in a particular direction if the region to be taken up by the chopped stick does not overlap with an already existing point. The winner $($s$)$ of the game will be one or more people who can answer the question: What is the maximum number of sticks that can be chopped?
Shashank wants to win the game and hence he needs needs your help in finding out what is the maximum number of sticks that can be chopped down.

-----Input:-----
- The first line of each input contains a single integer n.
- n lines follow. Each of the n lines contain a pair of integers: $a_i,h_i$.

-----Output:-----
Output in a single line answer- the maximum number of sticks that can be chopped down.

-----Constraints-----
- $1 \leq n \leq 10^5$
- $1 \leq a_i,h_i \leq 10^9$
- The pairs are given in the order of ascending $a_i$. No two sticks are located at the same point.

-----Sample Input 1:-----
5
1 2
2 1
5 10
10 9
19 1

-----Sample Input 2:-----
5
1 2
2 1
5 10
10 9
20 1

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

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

-----EXPLANATION:-----
In the first example you can fell the sticks as follows:
- chop the stick 1 to the left — now it will take over the region $[ - 1;1]$
- chop the stick 2 to the right — now it will take over the region $[2;3]$
- spare the stick 3— it will take over the point $5$
- spare the stick 4— it will take over the point $10$
- chop the stick 5 to the right — now it will take over the region $[19;20]$

n=int(input())
l=[]
for i in range(n):
 l.append(list(map(int,(input().split()))))
ans=0
for i in range(n):
 if i==0:
  ans+=1
 elif i==n-1:
  ans+=1
 else:
  if l[i][0]-l[i][1]>l[i-1][0]:
   ans+=1
  else:
   if l[i][0]+l[i][1]<l[i+1][0]:
    ans+=1
    l[i][0] = l[i][0]+l[i][1]
print(ans)


Solve in Python:
Shaun is very much interested in Subarrays. Shaun wants to count the number of subarrays in his chosen array with sum being a multiple of $10^9$. Since, Shaun is interested in huge numbers.He chose his array such that it contains only $10^8$ and $9*10^8$ as its elements.
Help shaun to count the number of required subarrays.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- First line of each testcase contains one integer $N$,size of array $A$.
- Second line of each testcase contains $N$ space separated array elements

-----Output:-----
For each testcase, output in a single line number of subarrays with sum being multiple of $10^9$.

-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq N \leq 10^5$
- $A[i]$=$10^8$ , $9*10^8$

-----Sample Input:-----
2
3
100000000 900000000 100000000
1
900000000

-----Sample Output:-----
2
0

import collections
def subarraysDivByK(A, K):
    P = [0]
    for x in A:
        P.append((P[-1] + x) % K)

    count = collections.Counter(P)
    return sum(v*(v-1)/2 for v in count.values())

t=int(input())
for _ in range(t):
    n=int(input())
    arr=map(int,input().split())
    print(int(subarraysDivByK(arr,1000000000)))


Solve in Python:
Shaun was given $N$ pairs of parenthesis ( )  by his teacher who gave him a difficult task.The task consists of two steps. First,Shaun should colour all $N$ pairs of parenthesis each with different color but opening and closing bracket of a particular pair should be of same colour. Then,Shaun should report to his teacher the number of ways he can arrange all $2*N$ brackets such that sequence form is valid. Teacher defined valid sequence by these rules:
- Any left parenthesis '(' must have a corresponding right parenthesis ')'.
- Any right parenthesis ')' must have a corresponding left parenthesis '('.
- Left parenthesis '(' must go before the corresponding right parenthesis ')'.
Note: Shaun could match opening and closing brackets of different colours.
Since number of ways can be large, Shaun would report the answer as modulo 1000000007 ($10^9 + 7$).

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

-----Output:-----
For each testcase, output in a single line answer given by Shaun to his teacher modulo 1000000007.

-----Constraints-----
- $1 \leq T \leq 100000$
- $1 \leq N \leq 100000$

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

-----Sample Output:-----
1
6
90

-----EXPLANATION:-----
Here numbers from $1$ to $N$ have been used to denote parenthesis.A unique number corresponds to a unique pair of parenthesis.
-In the first test case , you can use only one color to color the parenthesis  you could arrange it only in one way i.e, 1 1
-In the second test case  you can use two colors and the possible ways of arranging it are
1 1 2 2
1 2 2 1
1 2 1 2
2 2 1 1
2 1 1 2
2 1 2 1


Solve in Python:
Sheldon is a little geek living in Texas. While his friends like to play outside, little Sheldon likes to play around with ICs and lasers in his house. He decides to build N clap activated toggle machines each with one power inlet and one outlet. Each machine works when its power source inlet is receiving power. When the machine is in 'ON' state and is receiving power at its inlet, it makes power available at its power outlet to which a bulb or another ToGgLe machine could be attached.

Suppose Sheldon attached 2 such machines to one another with the power inlet of the first machine attached to a power source at his house and the outlet of the second machine to a bulb. Initially both machines are in 'OFF' state and power source to first machine is off too. Now the power source is switched on. The first machine receives power but being in the 'OFF' state it does not transmit any power. Now on clapping the first ToGgLe machine toggles to 'ON' and the second machine receives power. On clapping once more the first toggles to 'OFF' and the second toggles to 'ON'. But since the second ToGgLe machine receives no power the bulb does not light up yet. On clapping once more, the first machine which is still receiving power from the source toggles to 'ON' and the second which was already 'ON' does not toggle since it was not receiving power. So both the machine are in 'ON' state and the bulb lights up and little Sheldon is happy.

But when Sheldon goes out for a while, his evil twin sister attaches N such ToGgLe machines (after making sure they were all in 'OFF' state) and attaches the first to a power source (the power source is initially switched off) and the last ToGgLe machine to a bulb. Sheldon is horrified to find that his careful arrangement has been disturbed.

Coders, help the poor boy by finding out if clapping k times for the N ToGgLe machines (all in 'OFF' state with the first one connected to a switched off power source and last one to a bulb) would light the bulb. Hurry before Sheldon has a nervous...

for _ in range(int(input())):
 n,k=input().split()
 n=int(n)
 k=int(k)

 p=2**n-1

 if p==k:
  print('ON')
 elif p<k:
  if (k-p)%(2**n)==0:
   print('ON')
  else:
   print('OFF')
 else:
  print('OFF')


Solve in Python:
Sherlock Holmes has decided to start a new academy to some of the young lads. He has conducted several tests and finally selected N equally brilliant

students.Now he don't know whether to train all the N students or not. Now since Holmes was in a confusion, Watson came up with an idea. He wanted to

test the obedience of the students. So during the camp, the students were given some Swiss Chocolates as gifts each time when they passed a level.Now some of them have

finished eating all the chocolates, some of them had some remaining. Now to test their team chemistry and IQ skills, Watson told the lads to arrange themselves in such
a way that,  number of chocolates of the ith kid should be equal to the sum of   (i-1)th kid and (i-2)th kid. Now they have arranged themselves in an order.
Now Sherlock announced that he will select the students who have formed the line according to this order. But since there can be many such small groups among the

entire N kids, he will select a sequence of kids such that the length of the sequence is maximized, meanwhile satisfying the above condition

-----Input-----
First line is an integer T which denotes the total number of test cases. Each of the next T lines contains an integer N which denotes, N students. The next
line contains N spaced integers.where it denotes the order in which the kids arranged themselves.

-----Output-----
Each line contains an integer which denotes the maximum number of students among the N students who have arranged themselves according the rule said by Watson.It is guaranteed that Holmes will select atleast 1 or 2 students

-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 10^5
- 1 ≤ Each of next N integers ≤ 10^9

-----Subtasks-----
Subtask #1 : (20 points)
- 1 ≤ T ≤ 10
- 1 ≤ N≤ 100
- 1 ≤ Each element≤ 10^3

Subtask 2 : (80 points)

- 1 ≤ T ≤ 10
- 1 ≤ N≤ 100000
- 1 ≤ Each element≤ 10^9

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

Output:
3
3

-----Explanation-----
Example case 1. Here the first kid has 2 chocolates, second has 3 chocolates,...

for _ in range(int(input())):
 n = int(input())
 a = list(map(int, input().split()))
 mx = 1
 if n < 3:
  if n == 2 and a[0] == a[1]:
   mx = 2
 else:
  c = 2
  for i in range(2, n):
   if a[i] == a[i-1] + a[i-2]:
    c += 1
    continue
   else:
    mx = max(c, mx)
    c = 2
  mx = max(c, mx)
 print(mx)


Solve in Python:
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.

He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1.

Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.

Help Sherlock complete this trivial task.

-----Input-----

The only line contains single integer n (1 ≤ n ≤ 100000) — the number of jewelry pieces.

-----Output-----

The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints.

The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price.

If there are multiple ways to color the pieces using k colors, you can output any of them.

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

Output
2
1 1 2
Input
4

Output
2
2 1 1 2

-----Note-----

In the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.

In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.

n = int(input())+2

prime = [i%2 for i in range(n)]
prime[1] = 0
prime[2] = 1
for p in range(3, int(n**0.5)+2, 2):
    if not prime[p]:
        continue
    for q in range(p*p, n, p+p):
        prime[q] = 0

l = [2-x for x in prime[2:]]
print(max(l))
print(" ".join(map(str, l)))


Solve in Python:
Shivam is the youngest programmer in the world, he is just 12 years old. Shivam is learning programming and today he is writing his first program.

Program is very simple, Given two integers A and B, write a program to add these two numbers.

-----Input-----

The first line contains an integer T, the total number of test cases. Then follow T lines, each line contains two Integers A and B.

-----Output-----
For each test case, add A and B and display it in a new line.

-----Constraints-----
- 1 ≤ T ≤ 1000
- 0 ≤ A,B ≤ 10000

-----Example-----
Input
3
1 2
100 200
10 40

Output
3
300
50

T = int(input())
for tc in range(T):
	(a, b) = map(int, input().split(' '))
	ans = a + b
	print(ans)


Solve in Python:
Shivam is working on electric circuits. He requires some connecting wires. He needs to make a total of N connections and he has mentioned his wire length requirements for each connection in an integer sequence A. For buying wires, he need to decide the length of each wire piece, and he’ll get as many wire pieces of the chosen length each at unit cost (cost 1 per piece) but he can't get wires of different lengths. Also, he can't cut wire pieces to make new pieces of different (smaller) length(s).
But he can connect any number of wires together to form a new single wire piece whose length is the sum of lengths of the wires connected. So, Shivam needs to choose an integer length for buying wires. Shivam hates to waste anything, and he hates it even more if that thing is money.
Shivam is weak in mathematics and is asking you to help him in this situation. Help him decide the length of wires and total number of wires so as to minimize the total expenditure.
Note: You cannot make a connection which requires a wire piece of length X with a wire piece of length Y if X≠Y.
Input:
·        The first line of the input contains T = Number of Test cases
·        The first line of each test case contains an integer N
·        The second line contains N space separated integers A1, A2, …., AN.
Output:
For each test case print a single line containing two space separated integers, length of each wire and the corresponding minimum cost.
Constraints:
·       1 <= T <= 10
·       1 <= N <= 10^5
·        1 <= Ai <= 10^5, for each valid i
Sample Input:
1
3
2 4 8
Sample Output:
2 7

# cook your dish here
def gcd(a, b):
 if(b==0):
  return a
 else:
  return gcd(b,a%b)

t = int(input())
for _ in range(t):
 n = int(input())
 a = list(map(int, input().split()))
 res = a[0]
 for i in a[1:]:
  res = gcd(res, i)
 tot = 0
 for i in a:
  tot += i//res
 print(res, tot)


Solve in Python:
Shivam owns a gambling house, which has a special wheel called The Wheel of Fortune.
This wheel is meant for giving free coins to people coming in the house.

The wheel of fortune is a game of chance. It uses a spinning wheel with exactly N numbered pockets and a coin is placed in between every consecutive pocket. The wheel is spun in either of the two ways.
Before the wheel is turned, all the coins are restored and players bet on a number K.
Then a needle is made to point to any one of the pocket which has number K written on it.
Wheel is then spun till the needle encounters number K again and the player gets all the coins the needle has encountered.

Shivam being the owner of the gambling house, has the authority to place the needle on any of the K numbered pockets and also he could rotate the wheel in either of the two ways.
Shivam has to figure out a way to minimize number of coins that he has to spend on every given bet.
You are given a wheel having N elements and Q players. Each player bets on a number K from the wheel. For each player you have to print minimum number of coins Shivam has to spend.

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

- The first line of each test case contains single integer N .

- The second line of each test case contains N space seperated integers denoting the numbers on the wheel.

- The third line of each test case contains a single integer Q denoting the number of players.
- Then, Q lines follow a single integer K from the N numbers of the wheel

-----Output-----
For each player, output the minimum number of coins Shivam has to spend.

-----Constraints-----

- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 100000
- 1 ≤ Number written on the Wheel ≤ 1000
- 1 ≤ Q ≤ 10000
- 1 ≤ K ≤ 1000
-  It is guaranteed that K belongs to the N numbers written on the wheel.

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

2

3

1 2 3

3

1

2

3

6

2 1 5 3 2 1

4

1

2

3

5
Output:

3

3

3

2

2

6

6

t=int(input())
for _ in range(t):
    n=int(input())
    arr=list(map(int,input().split()))
    d={}
    for i in range(n):
        if arr[i] in d:
            d[arr[i]].append(i)
        else:
            d[arr[i]]=[i]
    q=int(input())
    for i in range(q):
        m=int(input())
        if len(d[m])==1:
            print(n)
        elif len(d[m])==2:
            print(min((d[m][1]-d[m][0]),((n-d[m][1])+d[m][0])))
        else:
            k=100000
            for j in range(len(d[m])-1):
                if (d[m][j+1]-d[m][j])<k:
                    k=d[m][j+1]-d[m][j]
                else:
                    pass
            print(min(k,((n-d[m][len(d[m])-1])+d[m][0])))


Solve in Python:
Shubham recently learned the lexicographical order in strings.

Now, he has two strings s1  and  s2  of the equal size and Shubham wants to compare those two strings lexicographically.

Help Shubham with the strings comparison.

Note:

Letters are case insensitive.

-----Input-----

First line contains a integer T denoting the number of test cases. Each test case contains two strings of equal size in two separate lines.

-----Output-----

For each test case,

If s1 < s2, print "first".

If s1 > s2, print "second".

If s1=s2, print "equal".

in separate lines.

-----Constraints-----

- 1 ≤ T ≤ 10^2
- 1 ≤ Length of the string ≤ 500

-----Example-----
Input:
2
abc
acb
AB
ba

Output:
first
first

# cook your code here
n=int(input())
while n>0:
 s1=input()

 s2=input()
 if s1.lower()<s2.lower():
  print("first")
 elif s1.lower()>s2.lower():
  print("second")
 elif s1.lower()==s2.lower():
  print("equal")
 n-=1


Solve in Python:
Sig has built his own keyboard. Designed for ultimate simplicity, this keyboard only has 3 keys on it: the 0 key, the 1 key and the backspace key.
To begin with, he is using a plain text editor with this keyboard. This editor always displays one string (possibly empty). Just after the editor is launched, this string is empty. When each key on the keyboard is pressed, the following changes occur to the string:
 - The 0 key: a letter 0 will be inserted to the right of the string.
 - The 1 key: a letter 1 will be inserted to the right of the string.
 - The backspace key: if the string is empty, nothing happens. Otherwise, the rightmost letter of the string is deleted.
Sig has launched the editor, and pressed these keys N times in total. As a result, the editor displays a string s. Find the number of such ways to press the keys, modulo 10^9 + 7.

-----Constraints-----
 - 1 ≦ N ≦ 5000
 - 1 ≦ |s| ≦ N
 - s consists of the letters 0 and 1.

-----Partial Score-----
 - 400 points will be awarded for passing the test set satisfying 1 ≦ N ≦ 300.

-----Input-----
The input is given from Standard Input in the following format:
N
s

-----Output-----
Print the number of the ways to press the keys N times in total such that the editor displays the string s in the end, modulo 10^9+7.

-----Sample Input-----
3
0

-----Sample Output-----
5

We will denote the backspace key by B. The following 5 ways to press the keys will cause the editor to display the string 0 in the end: 00B, 01B, 0B0, 1B0, BB0. In the last way, nothing will happen when the backspace key is pressed.

N = int(input())
s = len(input())

mod = 10**9 + 7
dp = [1] + [0]*N
for i in range(N):
    dp = [dp[0] + dp[1]] + [(i + 2*j) % mod for i, j in zip(dp[2:] + [0],dp[:-1])]
print(dp[s]*pow(2**s, mod - 2, mod)%mod)


Solve in Python:
Similar setting of the [previous](https://www.codewars.com/kata/progressive-spiral-number-position/), this time you are called to identify in which "branch" of the spiral a given number will end up.

Considering a square of numbers disposed as the 25 items in [the previous kata](https://www.codewars.com/kata/progressive-spiral-number-position/), the branch are numbered as it follows:

```
17 16 15 14 13    1 1 1 1 0
18 05 04 03 12    2 1 1 0 0
19 06 01 02 11 => 2 2 0 0 0
20 07 08 09 10    2 2 3 3 0
21 22 23 24 25    2 3 3 3 3
```

Meaning that, for example, numbers in the `10-13` range will be in branch `0`, numbers in the range `14-17` are inside branch `1`, all those nice numbers in the `18-21` can call branch `2` their house and finally the `21-25` team all falls under the `3` branch.

Your function must return the number of the index of each number [`1` being a special case you might consider equivalent to being in the first branch, `0`], as per examples:

```python
branch(1) == 0 #kind of special case here
branch(5) == 1
branch(25) == 3
branch(30) == 0
branch(50) == 0
```

It might help A LOT to both solve the [previous kata](https://www.codewars.com/kata/progressive-spiral-number-position/) and to visualize the diagonals of the square. Be ready for big numbers and, as usual, inspired by [AoC](http://adventofcode.com/2017/day/3). Finally, when ready, go to compute [the distance](https://www.codewars.com/kata/progressive-spiral-number-distance/) of the series.

def branch(n):
    if n==1:
        return 0
    i=1
    while(True):
        if n<=(2*i-1)**2:
            break
        i+=1
    return int((n-(2*i-3)**2-1)/(2*i-2))


Solve in Python:
Similar to the [previous kata](https://www.codewars.com/kata/string-subpattern-recognition-ii/), but this time you need to operate with shuffled strings to identify if they are composed repeating a subpattern

Since there is no deterministic way to tell which pattern was really the original one among all the possible permutations of a fitting subpattern, return a subpattern with sorted characters, otherwise return the base string with sorted characters (you might consider this case as an edge case, with the subpattern being repeated only once and thus equalling the original input string).

For example:

```python
has_subpattern("a") == "a"; #no repeated pattern, just one character
has_subpattern("aaaa") == "a" #just one character repeated
has_subpattern("abcd") == "abcd" #base pattern equals the string itself, no repetitions
has_subpattern("babababababababa") == "ab" #remember to return the base string sorted"
has_subpattern("bbabbaaabbaaaabb") == "ab" #same as above, just shuffled
```

If you liked it, go for either the [previous kata](https://www.codewars.com/kata/string-subpattern-recognition-ii/) or the [next kata](https://www.codewars.com/kata/string-subpattern-recognition-iv/) of the series!

from collections import Counter
from functools import reduce
from math import gcd
def has_subpattern(string):
    if len(string)<2:
        return string
    c=Counter(string)
    x=reduce(gcd,c.values())
    if x==1:
        return ''.join(sorted(string))
    return ''.join(k*(c[k]//x) for k in sorted(c.keys()))


Solve in Python:
Similarly to the [previous kata](https://www.codewars.com/kata/string-subpattern-recognition-i/), you will need to return a boolean value if the base string can be expressed as the repetition of one subpattern.

This time there are two small changes:

* if a subpattern has been used, it will be repeated at least twice, meaning the subpattern has to be shorter than the original string;
* the strings you will be given might or might not be created repeating a given subpattern, then shuffling the result.

For example:

```python
has_subpattern("a") == False #no repeated shorter sub-pattern, just one character
has_subpattern("aaaa") == True #just one character repeated
has_subpattern("abcd") == False #no repetitions
has_subpattern("babababababababa") == True #repeated "ba"
has_subpattern("bbabbaaabbaaaabb") == True #same as above, just shuffled
```
Strings will never be empty and can be composed of any character (just consider upper- and lowercase letters as different entities) and can be pretty long (keep an eye on performances!).

If you liked it, go for either the [previous kata](https://www.codewars.com/kata/string-subpattern-recognition-i/) or the [next kata](https://www.codewars.com/kata/string-subpattern-recognition-iii/) of the series!

from collections import Counter
from math import gcd
def has_subpattern(string):
    temp=Counter(string)
    if temp.most_common(1)[0][1]==1:
        return False
    res=sorted(temp.items(), key=lambda x:x[1])
    if len(res)==1:
        return True
    check=res[-1][1]
    for i in range(1, len(res)):
        check=min(check, gcd(res[i][1], res[i-1][1]))
    if check==1:
        return False
    for i in res:
        if i[1]%check!=0:
            return False
    return True


Solve in Python:
Simple enough this one - you will be given an array. The values in the array will either be numbers or strings, or a mix of both. You will not get an empty array, nor a sparse one.

Your job is to return a single array that has first the numbers sorted in ascending order, followed by the strings sorted in alphabetic order. The values must maintain their original type.

Note that numbers written as strings are strings and must be sorted with the other strings.

def db_sort(arr):
	strings,integers=[],[]
	for i in arr:
		integers.append(i) if type(i) is int else strings.append(i)
	return sorted(integers)+sorted(strings)


Solve in Python:
Simple interest on a loan is calculated by simply taking the initial amount (the principal, p) and multiplying it by a rate of interest (r) and the number of time periods (n).

Compound interest is calculated by adding the interest after each time period to the amount owed, then calculating the next interest payment based on the principal PLUS the interest from all previous periods.

Given a principal *p*, interest rate *r*, and a number of periods *n*, return an array [total owed under simple interest, total owed under compound interest].

```
EXAMPLES:

interest(100,0.1,1) = [110,110]
interest(100,0.1,2) = [120,121]
interest(100,0.1,10) = [200,259]
```

Round all answers to the nearest integer. Principal will always be an integer between 0 and 9999; interest rate will be a decimal between 0 and 1; number of time periods will be an integer between 0 and 49.

---

More on [Simple interest, compound interest and continuous interest](https://betterexplained.com/articles/a-visual-guide-to-simple-compound-and-continuous-interest-rates/)

def interest(p,r,n):
    simple = p + p * r * n
    while n > 0:
        n -= 1
        p += p * r
    return [round(simple), round(p)]


Solve in Python:
Simple transposition is a basic and simple cryptography technique. We make 2 rows and put first a letter in the Row 1, the second in the Row 2, third in Row 1 and so on until the end. Then we put the text from Row 2 next to the Row 1 text and thats it.

Complete the function that receives a string and encrypt it with this simple transposition.

## Example
For example if the text to encrypt is: `"Simple text"`, the 2 rows will be:

Row 1
S
m
l

e
t

Row 2
i
p
e
t
x

So the result string will be: `"Sml etipetx"`

def simple_transposition(text):
    text1=text[0::2]
    text2=text[1::2]
    return text1+text2


Solve in Python:
Simple, given a string of words, return the length of the shortest word(s).

String will never be empty and you do not need to account for different data types.

def find_short(s):
    l = 100000;
    a = s.split(" ")
    for i in a:
        if(len(i)<l):
            l = len(i)
    return l # l: shortest word length


Solve in Python:
Simple, remove the spaces from the string, then return the resultant string.

~~~if:c
For C, you must return a new dynamically allocated string.
~~~

def no_space(x):
    x1 = ""
    for i in range(len(x)):
        if x[i].isspace() == True:
            pass
        else:
            x1 += x[i]
    return x1


Solve in Python:
Simply find the closest value to zero from the list. Notice that there are negatives in the list.

List is always not empty and contains only integers. Return ```None``` if it is not possible to define only one of such values. And of course, we are expecting 0 as closest value to zero.

Examples:
```code
[2, 4, -1, -3]  => -1
[5, 2, -2]      => None
[5, 2, 2]       => 2
[13, 0, -6]     => 0
```

def closest(lst):
    min_v = min(lst, key=lambda x: abs(x))
    return None if -min_v in lst and min_v else min_v


Solve in Python:
Since due to COVID 19, India has undergone a complete 21 day lockdown. So Amol was attending an online lecture where his professor asked him to solve a question. Amol was unable to solve the question so he asked you to solve the question and give him the correct answer.

The question was asked a such that his professor gave him a number M and a list of integers of length N (i.e. A1, A2,..... AN) and you have to find out all the subsets that add up to M and the total number of subsets will be the final answer.

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 a single integer N.

• The second line of each test case contains a single integer M.

• The third line contains N space-separated integers A1, A2,..... AN.

Output:
For each test case, print a single line containing one integer ― the no. of subsets that adds upto M.

Constraints:
• 1≤T≤5

• 1≤N≤100

• 10≤M≤100

• 1≤Ai≤100

ExampleInput:

2

4

16

2 4 6 10

4

20

2 8 12 10

Output:

2

2

Explanation:
In the 1st example there are two subsets {2,4,10} and {6,10} that adds upto 16 so the output is 2.

# cook your dish here
def subset_sum(numbers, target, partial=[]):
    count=0
    s = sum(partial)

    # check if the partial sum is equals to target
    if s == target:
        count+=1
        return 1
    if s >= target:
        return 0# if we reach the number why bother to continue

    for i in range(len(numbers)):
        n = numbers[i]
        remaining = numbers[i+1:]
        count+=subset_sum(remaining, target, partial + [n])
    return count

t=int(input())
for i in range(t):
    input()
    n=int(input())
    s=list(map(int,input().split()))
    print(subset_sum(s,n))


Solve in Python:
Sinchan and his friends loves to eat. They have a 2D rectangular cake which they want to share. Sinchan is very kind and offers his friends to eat the cake first, all friends goes one by one to eat the cake. Each friend will cut cake into two parts. First part of the cake will be largest possible square from the cake, that the friend will eat, and will leave the second part for others, it continues untill cake is over or every friend gets to eat the cake.
Now Sinchan wonder how much cake would he be able to get.

-----Input-----
- First line of input contain T, denoting number of test case.
- First line of each test case contains N, denoting number of friends.
- Second line of test case contain L, B (L x B) denoting dimension of cake.

-----Output-----
- For each test case, if Sinchan gets to eat the cake print (without quotes) "Yes #" where # is area of cake that Sinchan gets. Otherwise print  (without quotes) "No"

-----Constraints-----
- 1 ≤ T, N, L, B ≤ 1000

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

Output:
Yes 2
No
Yes 1

-----Explanation-----
Example case 1. First friend divides 5x3 cake in 3x3 and 2x3 since 3x3 is largest possible square, second Friend divides 2x3 cake in 2x2 and 1x2 and eat 2x2 piece. Finaly Sinchan gets to eat and area of cake is 1*2 hence Output is (without quotes) "Yes 2"

testcases=int(input())
results=[]
for i in range(0,testcases):
 friends=int(input())
 l,b=list(map(int,input().split()))
 over=False
 if b>l:
  temp=b
  b=l
  l=temp
 for counter in range(0,friends):
  if l==b:
   over=True
   break
  elif l>b:
   l=l-b
   if b>l:
    temp=b
    b=l
    l=temp

 if over:
  results.append("No")
 else:
  results.append("Yes "+str(l*b))

for i in range(0,testcases):
 print(results[i])


Solve in Python:
Skier rides on a snowy field. Its movements can be described by a string of characters 'S', 'N', 'W', 'E' (which correspond to $1$ meter movement in the south, north, west or east direction respectively).

It is known that if he moves along a previously unvisited segment of a path (i.e. this segment of the path is visited the first time), then the time of such movement is $5$ seconds. If he rolls along previously visited segment of a path (i.e., this segment of the path has been covered by his path before), then it takes $1$ second.

Find the skier's time to roll all the path.

-----Input-----

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

Each set is given by one nonempty string of the characters 'S', 'N', 'W', 'E'. The length of the string does not exceed $10^5$ characters.

The sum of the lengths of $t$ given lines over all test cases in the input does not exceed $10^5$.

-----Output-----

For each test case, print the desired path time in seconds.

-----Example-----
Input
5
NNN
NS
WWEN
WWEE
NWNWS

Output
15
6
16
12
25

import sys
import heapq as hq

readline = sys.stdin.readline

ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: list(map(int, readline().split()))
nl = lambda: list(map(int, readline().split()))

# eps = 10**-7

def solve():
    s = ns()
    d = dict()
    cnt = 0
    g = [(0, 1), (1, 0), (-1, 0), (0, -1)]
    cur = (0, 0)
    d[cur] = ''
    for x in s:
        for i in range(4):
            if x == 'NEWS'[i]:
                nx = (cur[0] + g[i][0], cur[1] + g[i][1])
                if nx in d and x in d[cur]:
                    cnt += 1
                else:
                    cnt += 5
                    if nx not in d:
                        d[nx] = ''
                    d[nx] += 'NEWS'[3-i]
                    d[cur] += x
                cur = nx
                break
    print(cnt)

# solve()

T = ni()
for _ in range(T):
    solve()


Solve in Python:
Slime and his $n$ friends are at a party. Slime has designed a game for his friends to play.

At the beginning of the game, the $i$-th player has $a_i$ biscuits. At each second, Slime will choose a biscuit randomly uniformly among all $a_1 + a_2 + \ldots + a_n$ biscuits, and the owner of this biscuit will give it to a random uniform player among $n-1$ players except himself. The game stops when one person will have all the biscuits.

As the host of the party, Slime wants to know the expected value of the time that the game will last, to hold the next activity on time.

For convenience, as the answer can be represented as a rational number $\frac{p}{q}$ for coprime $p$ and $q$, you need to find the value of $(p \cdot q^{-1})\mod 998\,244\,353$. You can prove that $q\mod 998\,244\,353 \neq 0$.

-----Input-----

The first line contains one integer $n\ (2\le n\le 100\,000)$: the number of people playing the game.

The second line contains $n$ non-negative integers $a_1,a_2,\dots,a_n\ (1\le a_1+a_2+\dots+a_n\le 300\,000)$, where $a_i$ represents the number of biscuits the $i$-th person own at the beginning.

-----Output-----

Print one integer: the expected value of the time that the game will last, modulo $998\,244\,353$.

-----Examples-----
Input
2
1 1

Output
1

Input
2
1 2

Output
3

Input
5
0 0 0 0 35

Output
0

Input
5
8 4 2 0 1

Output
801604029

-----Note-----

For the first example, in the first second, the probability that player $1$ will give the player $2$ a biscuit is $\frac{1}{2}$, and the probability that player $2$ will give the player $1$ a biscuit is $\frac{1}{2}$. But anyway, the game will stop after exactly $1$ second because only one player will occupy all biscuits after $1$ second, so the answer is $1$.

import sys

def II(): return int(sys.stdin.readline())
def LI(): return list(map(int, sys.stdin.readline().split()))

class mint:
    def __init__(self, x):
        self.__x = x % md

    def __repr__(self):
        return str(self.__x)

    def __neg__(self):
        return mint(-self.__x)

    def __add__(self, other):
        if isinstance(other, mint): other = other.__x
        return mint(self.__x + other)

    def __sub__(self, other):
        if isinstance(other, mint): other = other.__x
        return mint(self.__x - other)

    def __rsub__(self, other):
        return mint(other - self.__x)

    def __mul__(self, other):
        if isinstance(other, mint): other = other.__x
        return mint(self.__x * other)

    __radd__ = __add__
    __rmul__ = __mul__

    def __truediv__(self, other):
        if isinstance(other, mint): other = other.__x
        return mint(self.__x * pow(other, md - 2, md))

    def __rtruediv__(self, other):
        return mint(other * pow(self.__x, md - 2, md))

    def __pow__(self, power, modulo=None):
        return mint(pow(self.__x, power, md))

md = 998244353

def main():
    n=II()
    aa=LI()
    sa=sum(aa)
    # dp[i]...ev from i-1 to i
    dp=[mint(0)]*(sa+1)
    for i in range(1,sa+1):
        dp[i]=((i-1)*dp[i-1]+sa)*(n-1)/(sa+1-i)
    #print(*dp)

    for i in range(sa):dp[i+1]+=dp[i]

    ans=-(n-1)*dp[-1]
    for a in aa:ans+=dp[sa]-dp[a]
    print(ans/n)

main()


Solve in Python:
Snackdown 2019 is coming! People have started to spread the word and tell other people about the contest.
There are $N$ people numbered $1$ through $N$. Initially, only person $1$ knows about Snackdown. On each day, everyone who already knows about Snackdown tells other people about it. For each valid $i$, person $i$ can tell up to $A_i$ people per day. People spread the information among the people who don't know about Snackdown in the ascending order of their indices; you may assume that no two people try to tell someone about Snackdown at the same moment. Each person is only allowed to start telling other people about Snackdown since the day after he/she gets to know about it (person $1$ can start telling other people already on day $1$). How many days does it take for all people to know about Snackdown?

-----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 a single integer $N$.
- 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 number of days.

-----Constraints-----
- $1 \le T \le 1,000$
- $2 \le N \le 10^5$
- the sum of $N$ for all test cases does not exceed $10^6$
- $0 \le A_i \le N$ for each valid $i$
- $1 \le A_1$

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

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

-----Explanation-----
Example case 1: On day $1$, person $1$ tells people $2$ and $3$ about Snackdown. On day $2$, the first three people know about Snackdown, so they can tell $2+1+1 = 4$ people about it in a single day. That means the last four people get to know about Snackdown on day $2$, so the total number of days is $2$.
Example case 2: On each day, person $1$ can tell up to $5$ people about Snackdown, so on the first day, he simply tells all people about it and the total number of days is $1$.

import sys
input=sys.stdin.readline
t=int(input())
for you in range(t):
 n=int(input())
 l=input().split()
 li=[int(i) for i in l]
 z=[]
 for i in range(n):
  z.append(li[i])
 maxpref=[0 for i in range(n)]
 maxa=0
 for i in range(n):
  maxa+=z[i]
  maxpref[i]=maxa
 curr=0
 count=0
 while(curr<n-1):
  curr+=maxpref[curr]
  count+=1
  #print(curr)
 print(count)


Solve in Python:
Snackdown 2019 is coming! There are two rounds (round A and round B) after the qualification round. From both of them, teams can qualify to the pre-elimination round. According to the rules, in each of these two rounds, teams are sorted in descending order by their score and each team with a score greater or equal to the score of the team at the $K=1500$-th place advances to the pre-elimination round (this means it is possible to have more than $K$ qualified teams from each round in the case of one or more ties after the $K$-th place).
Today, the organizers ask you to count the number of teams which would qualify for the pre-elimination round from round A for a given value of $K$ (possibly different from $1500$). They provided the scores of all teams to you; you should ensure that all teams scoring at least as many points as the $K$-th team qualify.

-----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 $S_1, S_2, \dots, S_N$.

-----Output-----
For each test case, print a single line containing one integer — the number of qualified teams.

-----Constraints-----
- $1 \le T \le 1,000$
- $1 \le K \le N \le 10^5$
- $1 \le S_i \le 10^9$ for each valid $i$
- the sum of $N$ for all test cases does not exceed $10^6$

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

-----Example Output-----
2
4

# cook your dish here
#t = int(input())
for i in range(int(input())):
 n,k = map(int,input().split())
 l = list(map(int,input().split()))
 l.sort(reverse = True)
 c = 0
 for i in l:
  if i >= l[k-1]:
   c += 1
 print(c)


Solve in Python:
Snakeland is a well organised city. The houses of the city are organised in an orderly rectangular fashion with dimensions 2 * n, i.e. there are total two rows and n columns. The house in the i-th row and j-th column is also said to be the house at coordinates (i, j). Some of the houses are occupied by snakes, while the others are empty. You are given this information through an array s of dimension 2 * n, where, if s[i][j] = '*', it denotes that there is a snake in the house at coordinates (i, j), and if s[i][j] = '.', it denotes that the house is empty.
These snakes are planning a coup against a mongoose who controls their city from outside. So, they are trying their best to meet with other snakes and spread information about the date of the coup. For spreading this information, they can just hiss from their house and usually their hiss is so loud that it will be heard in all the cells except if there is a soundproof fence built that cuts the voice. Note that the external borders of Snakeland are already built of soundproof material. The mongoose got to know about the plan, and he wants to construct sound proof fences along the borders of the houses so that no two people should be able to communicate with each other. The fence can be either vertical or horizontal.  Each fence can be of any length, but the mongoose wants to minimize the number of fences to be built. Find out the minimum number of fences that the mongoose should build.

-----Input-----
The first line of the input contains an integer T denoting number of test cases. The descriptions of the T test cases follow.
The first line of each test case contains a single integer, n.
Each of the next two lines contains n characters denoting the first and the second rows of Snakeland respectively.

-----Output-----
For each test case, output a single integer corresponding to the minimum number of fences that the mongoose needs to build.

-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ n ≤...

# cook your dish here
t=int(input())
while t:
 n=int(input())
 r1=input()
 r2=input()
 r1count=0
 r2count=0
 count=0
 for i in range(n):
  if(r1[i]=="*"):
   r1count+=1
  if(r2[i]=="*"):
   r2count+=1
 if(r1count>0) and (r2count>0):
  count=1
  r1count=0
  r2count=0
  i=0
  while(i<n):
   if(r1[i]=="*"):
    r1count+=1
   if(r2[i]=="*"):
    r2count+=1
   if(r1count>1) or (r2count>1):
    count+=1
    r1count=0
    r2count=0
    i-=1
   i+=1
 elif(r1count==0 and r2count>0) or (r2count==0 and r1count>0):
  count=max(r1count,r2count)-1
 else:
  count=0
 print(count)
 t-=1


Solve in Python:
Snuke has a rooted tree with N+1 vertices.
The vertices are numbered 0 through N, and Vertex 0 is the root of the tree.
The parent of Vertex i (1 \leq i \leq N) is Vertex p_i.
Besides this tree, Snuke also has an box which is initially empty and many marbles, and playing with them.
The play begins with placing one marble on some of the vertices, then proceeds as follows:
 - If there is a marble on Vertex 0, move the marble into the box.
 - Move each marble from the vertex to its parent (all at once).
 - For each vertex occupied by two or more marbles, remove all the marbles from the vertex.
 - If there exists a vertex with some marbles, go to Step 1. Otherwise, end the play.
There are 2^{N+1} ways to place marbles on some of the vertices.
For each of them, find the number of marbles that will be in the box at the end of the play, and compute the sum of all those numbers modulo 1,000,000,007.

-----Constraints-----
 - 1 \leq N < 2 \times 10^{5}
 - 0 \leq p_i < i

-----Partial Scores-----
 - In the test set worth 400 points, N < 2{,}000.

-----Input-----
Input is given from Standard Input in the following format:
N
p_1 p_2 ... p_{N}

-----Output-----
Print the answer.

-----Sample Input-----
2
0 0

-----Sample Output-----
8

When we place a marble on both Vertex 1 and 2, there will be multiple marbles on Vertex 0 by step 2. In such a case, these marbles will be removed instead of being moved to the box.

import sys
readline = sys.stdin.readline

def parorder(Edge, p):
    N = len(Edge)
    par = [0]*N
    par[p] = -1
    stack = [p]
    order = []
    visited = set([p])
    ast = stack.append
    apo = order.append
    while stack:
        vn = stack.pop()
        apo(vn)
        for vf in Edge[vn]:
            if vf in visited:
                continue
            visited.add(vf)
            par[vf] = vn
            ast(vf)
    return par, order

def getcld(p):
    res = [[] for _ in range(len(p))]
    for i, v in enumerate(p[1:], 1):
        res[v].append(i)
    return res

MOD = 10**9+7
limit = 1341398
p2 = [1]*limit
for i in range(1, limit):
    p2[i] = 2*p2[i-1]%MOD

N = int(readline())
P = [None] + list(map(int, readline().split()))
Edge = [[] for _ in range(N+1)]
for i in range(1, N+1):
    Edge[i].append(P[i])
    Edge[P[i]].append(i)
_, L = parorder(Edge, 0)
C = getcld(P)
dist = [0]*(N+1)
for l in L[1:]:
    p = P[l]
    dist[l] = 1 + dist[p]
md = dist[:]
for l in L[:0:-1]:
    p = P[l]
    md[p] = max(md[p], md[l])

Ci = [None]*(N+1)
for i in range(N+1):
    if C[i]:
        res = -1
        cc = None
        for ci in C[i]:
            if md[ci] > res:
                res = md[ci]
                cc = ci
    Ci[i] = cc
ans = 0

res = [[0]]
val = [1]*(N+1)
size = [1]*(N+1)
used = [0]*(N+1)
name = [None]*(N+1)
mark = [None]*(N+1)
while res:
    newres = []
    for a in res:
        ts = 1
        ks = 0
        ss = 0
        dic = []
        ctr = []

        for i in a:
            ts = ts*(p2[size[i]] - val[i])%MOD
            ks = (ks + val[i]*pow(p2[size[i]] - val[i], MOD-2, MOD))%MOD
            ss += size[i]

            if not used[i]:
                used[i] = 1
                if C[i]:
                    dic.append(C[i])
                    if name[i] is None:
                        name[i] = Ci[i]
            if name[i] is not None:
                ctr.append(name[i])
        newres.extend(dic)
        if len(ctr) > 1:
            newres.append(ctr)
        for a0 in a:
       ...