Solve in Python:
Creatnx has $n$ mirrors, numbered from $1$ to $n$. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The $i$-th mirror will tell Creatnx that he is beautiful with probability $\frac{p_i}{100}$ for all $1 \le i \le n$.

Some mirrors are called checkpoints. Initially, only the $1$st mirror is a checkpoint. It remains a checkpoint all the time.

Creatnx asks the mirrors one by one, starting from the $1$-st mirror. Every day, if he asks $i$-th mirror, there are two possibilities:  The $i$-th mirror tells Creatnx that he is beautiful. In this case, if $i = n$ Creatnx will stop and become happy, otherwise he will continue asking the $i+1$-th mirror next day;  In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the checkpoint with a maximal number that is less or equal to $i$.

There are some changes occur over time: some mirrors become new checkpoints and some mirrors are no longer checkpoints. You are given $q$ queries, each query is represented by an integer $u$: If the $u$-th mirror isn't a checkpoint then we set it as a checkpoint. Otherwise, the $u$-th mirror is no longer a checkpoint.

After each query, you need to calculate the expected number of days until Creatnx becomes happy.

Each of this numbers should be found by modulo $998244353$. Formally, let $M = 998244353$. It can be shown that the answer can be expressed as an irreducible fraction $\frac{p}{q}$, where $p$ and $q$ are integers and $q \not \equiv 0 \pmod{M}$. Output the integer equal to $p \cdot q^{-1} \bmod M$. In other words, output such an integer $x$ that $0 \le x < M$ and $x \cdot q \equiv p \pmod{M}$.

-----Input-----

The first line contains two integers $n$, $q$ ($2 \leq n, q \le 2 \cdot 10^5$)  — the number of mirrors and queries.

The second line contains $n$ integers: $p_1, p_2, \ldots, p_n$ ($1 \leq p_i \leq 100$).

Each of $q$ following lines contains a single integer $u$ ($2 \leq u \leq n$) — next query.

-----Output-----

Print $q$ numbers – the answers after each query by modulo...

import sys
readline = sys.stdin.readline
from itertools import accumulate
from collections import Counter
from bisect import bisect as br, bisect_left as bl
class PMS:
    #1-indexed
    def __init__(self, A, B, issum = False):
        #Aに初期状態の要素をすべて入れる,Bは値域のリスト
        self.X, self.comp = self.compress(B)
        self.size = len(self.X)
        self.tree = [0] * (self.size + 1)
        self.p = 2**(self.size.bit_length() - 1)
        self.dep = self.size.bit_length()

        CA = Counter(A)
        S = [0] + list(accumulate([CA[self.X[i]] for i in range(self.size)]))
        for i in range(1, 1+self.size):
            self.tree[i] = S[i] - S[i - (i&-i)]
        if issum:
            self.sumtree = [0] * (self.size + 1)
            Ssum = [0] + list(accumulate([CA[self.X[i]]*self.X[i] for i in range(self.size)]))
            for i in range(1, 1+self.size):
                self.sumtree[i] = Ssum[i] - Ssum[i - (i&-i)]

    def compress(self, L):
        #座圧
        L2 = list(set(L))
        L2.sort()
        C = {v : k for k, v in enumerate(L2, 1)}
        # 1-indexed
        return L2, C

    def leng(self):
        #今入っている個数を取得
        return self.count(self.X[-1])

    def count(self, v):
        #v(Bの元)以下の個数を取得
        i = self.comp[v]
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s

    def less(self, v):
        #v(Bの元である必要はない)未満の個数を取得
        i = bl(self.X, v)
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s

    def leq(self, v):
        #v(Bの元である必要はない)以下の個数を取得
        i = br(self.X, v)
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s

    def add(self, v, x):
        #vをx個入れる,負のxで取り出す,iの個数以上取り出すとエラーを出さずにバグる
        i = self.comp[v]
        while i <= self.size:
            self.tree[i] += x
            i += i & -i

    def get(self, i):
        # i番目の値を取得
        if i <= 0:
            return -1
       ...


Solve in Python:
Cyael is a teacher at a very famous school in Byteland and she is known by her students for being very polite to them and also to encourage them to get good marks on their tests.
Then, if they get good marks she will reward them with candies :) However, she knows they are all very good at Mathematics, so she decided to split the candies evenly to all the students she considers worth of receiving them, so they don't fight with each other.
She has a bag which initially contains N candies and she intends to split the candies evenly to K students. To do this she will proceed as follows: while she has more than K candies she will give exactly 1 candy to each student until she has less than K candies. On this situation, as she can't split candies equally among all students she will keep the remaining candies to herself.
Your job is to tell how many candies will each student and the teacher
receive after the splitting is performed.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
Each test case will consist of 2 space separated integers, N and K denoting the number of candies and the number of students as described above.

-----Output-----
For each test case, output a single line containing two space separated integers, the first one being the number of candies each student will get, followed by the number of candies the teacher will get.

-----Constraints-----
-  T<=100 in each test file
- 0 <= N,K <= 233 - 1

-----Example-----Input:
2
10 2
100 3

Output:
5 0
33 1

-----Explanation-----
For the first test case, all students can get an equal number of candies and teacher receives no candies at all
For the second test case, teacher can give 33 candies to each student and keep 1 candy to herselfUpdate:
There may be multiple whitespaces before, after or between the numbers in input.

#SPCANDY

t = int(input())
A = []; B = []
for i in range(0, t, 1):
 n, k = input().split()
 n = int(n); k = int(k)
 if k != 0:
  A.append(n//k); B.append(n%k)
 else:
  A.append(0); B.append(n)
for i in range(0, t, 1):
 print(A[i], B[i])


Solve in Python:
DNA is a biomolecule that carries genetic information. It is composed of four different building blocks, called nucleotides: adenine (A), thymine (T), cytosine (C) and guanine (G). Two DNA strands join to form a double helix, whereby the nucleotides of one strand bond to the nucleotides of the other strand at the corresponding positions. The bonding is only possible if the nucleotides are complementary: A always pairs with T, and C always pairs with G.

Due to the asymmetry of the DNA, every DNA strand has a direction associated with it. The two strands of the double helix run in opposite directions to each other, which we refer to as the 'up-down' and the 'down-up' directions.

Write a function `checkDNA` that takes in two DNA sequences as strings, and checks if they are fit to form a fully complementary DNA double helix. The function should return a Boolean `true` if they are complementary, and `false` if there is a sequence mismatch (Example 1 below).

Note:

- All sequences will be of non-zero length, and consisting only of `A`, `T`, `C` and `G` characters.
- All sequences **will be given in the up-down direction**.
- The two sequences to be compared can be of different length. If this is the case and one strand is entirely bonded by the other, and there is no sequence mismatch between the two (Example 2 below), your function should still return `true`.
- If both strands are only partially bonded (Example 3 below), the function should return `false`.

Example 1:

Example 2:

Example 3:

---
#### If you enjoyed this kata, check out also my other DNA kata: [**Longest Repeated DNA Motif**](http://www.codewars.com/kata/longest-repeated-dna-motif)

trans = str.maketrans("ATCG", "TAGC")

def check_DNA(seq1, seq2):
    seq1, seq2 = sorted((seq1, seq2), key=len)
    return seq1[::-1].translate(trans) in seq2


Solve in Python:
DNA sequencing data can be stored in many different formats. In this Kata, we will be looking at SAM formatting. It is a plain text file where every line (excluding the first header lines) contains data about a "read" from whatever sample the file comes from. Rather than focusing on the whole read, we will take two pieces of information: the cigar string and the nucleotide sequence.

The cigar string is composed of numbers and flags. It represents how the read aligns to what is known as a reference genome. A reference genome is an accepted standard for mapping the DNA.

The nucleotide sequence shows us what bases actually make up that section of DNA. They can be represented with the letters A, T, C, or G.

Example Read: ('36M', 'ACTCTTCTTGCGAAAGTTCGGTTAGTAAAGGGGATG')

The M in the above cigar string stands for "match", and the 36 stands for the length of the nucleotide sequence. Since all 36 bases are given the 'M' distinction, we know they all matched the reference.

Example Read: ('20M10S',  'ACTCTTCTTGCGAAAGTTCGGTTAGTAAAG')

In the above cigar string, only 20 have the "M" distinction, but the length of the actual string of nucleotides is 30. Therefore we know that read did not match the reference. (Don't worry about what the other letters mean. That will be covered in a later kata.)

Your job for this kata is to create a function that determines whether a cigar string fully matches the reference and accounts for all bases. If it does fully match, return True. If the numbers in the string do not match the full length of the string, return 'Invalid cigar'. If it does not fully match, return False.

*Note for C++: Return True, False, or Invalid cigar as strings*

import re

def is_matched(read):
    nums = [int(v) for v in re.findall(r'\d+', read[0])]
    return 'Invalid cigar' if sum(nums)!=len(read[1]) else read[0]==f'{len(read[1])}M'


Solve in Python:
DZY loves Physics, and he enjoys calculating density.

Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: $\left\{\begin{array}{ll}{\frac{v}{e}} & {(e > 0)} \\{0} & {(e = 0)} \end{array} \right.$ where v is the sum of the values of the nodes, e is the sum of the values of the edges.

Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.

An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:  $V^{\prime} \subseteq V$;  edge $(a, b) \in E^{\prime}$ if and only if $a \in V^{\prime}, b \in V^{\prime}$, and edge $(a, b) \in E$;  the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.

Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. [Image]

-----Input-----

The first line contains two space-separated integers n (1 ≤ n ≤ 500), $m(0 \leq m \leq \frac{n(n - 1)}{2})$. Integer n represents the number of nodes of the graph G, m represents the number of edges.

The second line contains n space-separated integers x_{i} (1 ≤ x_{i} ≤ 10^6), where x_{i} represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.

Each of the next m lines contains three space-separated integers a_{i}, b_{i}, c_{i} (1 ≤ a_{i} < b_{i} ≤ n; 1 ≤ c_{i} ≤ 10^3), denoting an edge between node a_{i} and b_{i} with value c_{i}. The graph won't contain multiple edges.

-----Output-----

Output a real number denoting the answer, with an absolute or relative error of at most 10^{ - 9}.

-----Examples-----
Input
1 0
1

Output
0.000000000000000

Input
2 1
1 2
1 2 1

Output
3.000000000000000

Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63

Output
2.965517241379311

-----Note-----

In the first sample, you can only choose an empty subgraph, or the subgraph containing...

N, E = 0, 0
Cost, Edges = [], []
Answer = 0.0

def Solve():
    nonlocal Answer
    for e in Edges:
        Answer = max(Answer, (1.0 * (Cost[e[0]] + Cost[e[1]]) / (1.0 * e[2])))

def ReadInput():
    nonlocal N, E, Cost, Edges
    N, E = list(map(int, input().split()))
    Cost = list(map(int, input().split()))
    for i in range(0, E):
        x, y, c = list(map(int, input().split()))
        Edges.append((x - 1, y - 1, c))

def PrintOutput():
    print(Answer)

def main():
    ReadInput()
    Solve()
    PrintOutput()

main()


Solve in Python:
DZY loves planting, and he enjoys solving tree problems.

DZY has a weighted tree (connected undirected graph without cycles) containing n nodes (they are numbered from 1 to n). He defines the function g(x, y) (1 ≤ x, y ≤ n) as the longest edge in the shortest path between nodes x and y. Specially g(z, z) = 0 for every z.

For every integer sequence p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ n), DZY defines f(p) as $\operatorname{min}_{i = 1}^{n} g(i, p_{i})$.

DZY wants to find such a sequence p that f(p) has maximum possible value. But there is one more restriction: the element j can appear in p at most x_{j} times.

Please, find the maximum possible f(p) under the described restrictions.

-----Input-----

The first line contains an integer n (1 ≤ n ≤ 3000).

Each of the next n - 1 lines contains three integers a_{i}, b_{i}, c_{i} (1 ≤ a_{i}, b_{i} ≤ n; 1 ≤ c_{i} ≤ 10000), denoting an edge between a_{i} and b_{i} with length c_{i}. It is guaranteed that these edges form a tree.

Each of the next n lines describes an element of sequence x. The j-th line contains an integer x_{j} (1 ≤ x_{j} ≤ n).

-----Output-----

Print a single integer representing the answer.

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

Output
2

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

Output
3

-----Note-----

In the first sample, one of the optimal p is [4, 3, 2, 1].

n = int(input())
edges = [[int(x) for x in input().split()] for i in range(n-1)]
edges = sorted(edges)
use_count = [0]+[int(input()) for i in range(n)]
lo,hi = 0,10000
def getpar(par,u):
    if par[par[u]] == par[u]:
        return par[u]
    par[u] = getpar(par,par[u])
    return par[u]
def unite(par,sz,use,u,v):
    u = getpar(par,u)
    v = getpar(par,v)
    par[u] = v
    sz[v] += sz[u]
    use[v] += use[u]
def solve(fp):
    par = [i for i in range(n+1)]
    sz = [1 for i in range(n+1)]
    use = [use_count[i] for i in range(n+1)]
    for edge in edges:
        if edge[2] < fp:
            unite(par,sz,use,edge[0],edge[1])
    total_use = sum(use_count)
    for i in range(n+1):
        p = getpar(par,i)
        if(p == i):
            if(total_use - use[p] < sz[p]):
                return False
    return True
while lo < hi:
    mid = (lo+hi+1)//2
    if solve(mid):
        lo = mid
    else:
        hi = mid-1
print(lo)


Solve in Python:
Daenerys Targaryen has been suggested by her counselors to leave the Meereen and start conquering other parts of the world. But she knows giving up on the people of Meereen means victory of slavery. Her plan is to start conquering rest of the world while she remains in Meereen. She can only trust her bravest and most beloved Daario Naharis to undertake this risk. She asks him to conquer a few nations and promises him a help from her dragons. She also promises to marry him if he successfully conquers all the nations and not if he is defeated.
Daario has to conquer 'N' number of nations each nation with army size A[i]. He attacks the nations serially. As promised, he gets help from Daenerys's Dragons. His first 'M' attacks are made with the help of Dragons.

For first 'M' attacks, he gains A[i] soldiers.

For the rest, he looses ceiling of A[i]/2 soldiers.

He is defeated if he is left with no army before he conquers all the 'N' nations. He has no army initially and only has Dragons.

-----Input-----
First line has 'T' which is the number of test cases.
For each test cases there are two space separated integers 'N' and 'M' denoting the number of nations and the number of nations he has Dragon's help for respectively.
Follows N space separated integers denoting the size of army of each nation.

-----Output-----
Print 'VICTORY' if Daario conquers all nations and 'DEFEAT' if he doesn't.

-----Constraints-----
- 1 ≤ T ≤ 500
- 1 ≤ M ≤N ≤ 100000
- 1 ≤ A[i] ≤ 100000

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

3
5 3
1 2 3 4 5
6 2
4 4 4 4 4 4
7 4
10 10 10 10 50 60 70
Output:

VICTORY
VICTORY
DEFEAT

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

First 3 attacks add 1,2,3 to his army making it 6. (1+2+3 = 6)

Then he looses 2 and 3 making it 1. (6-2-3 = 1)

He conquers all so VICTORY.

Example case 2.

First 2 attacks add 4,4 to his army making it 8. (4+4 = 8)

Then he looses 2,2,2,2 making it 0. (8-2-2-2-2 = 0)

He conquers all so VICTORY.

Example case 3.

First 4 attacks add 10,10,10,10 to his army making it 40. (10+10+10+10 = 40)

Then...

loop = int(input())
for iiiiiiiii in range(loop):
 no_sol = 0
 n,m= input().split()
 m=int(m)
 n = int(n)
 l = input().split()
 for nation in range(len(l)):
  l[nation] = int(l[nation])
 for i in range(len(l)):
  if i < m:
   no_sol += l[i]
  else:
   no_sol-=(l[i]/2)
   if no_sol<0:
    print("DEFEAT")
    break

 if no_sol>=0:
  print("VICTORY")


Solve in Python:
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $a$ of $n$ non-negative integers.

Dark created that array $1000$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $k$ ($0 \leq k \leq 10^{9}$) and replaces all missing elements in the array $a$ with $k$.

Let $m$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $|a_i - a_{i+1}|$ for all $1 \leq i \leq n - 1$) in the array $a$ after Dark replaces all missing elements with $k$.

Dark should choose an integer $k$ so that $m$ is minimized. Can you help him?

-----Input-----

The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \leq t \leq 10^4$)  — the number of test cases. The description of the test cases follows.

The first line of each test case contains one integer $n$ ($2 \leq n \leq 10^{5}$) — the size of the array $a$.

The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($-1 \leq a_i \leq 10 ^ {9}$). If $a_i = -1$, then the $i$-th integer is missing. It is guaranteed that at least one integer is missing in every test case.

It is guaranteed, that the sum of $n$ for all test cases does not exceed $4 \cdot 10 ^ {5}$.

-----Output-----

Print the answers for each test case in the following format:

You should print two integers, the minimum possible value of $m$ and an integer $k$ ($0 \leq k \leq 10^{9}$) that makes the maximum absolute difference between adjacent elements in the array $a$ equal to $m$.

Make sure that after replacing all the missing elements with $k$, the maximum absolute difference between adjacent elements becomes $m$.

If there is more than one possible $k$, you can print any of them.

-----Example-----
Input
7
5
-1 10 -1 12 -1
5
-1 40 35 -1 35
6
-1 -1 9 -1 3 -1
2
-1 -1
2
0...

for _ in range(int(input())):
    n=int(input())
    a=list(map(int,input().split()))
    ans,small,big=0,2*10**9,-1
    for i in range(len(a)-1):
        if a[i]==-1 and a[i+1]!=-1:
            small=min(small, a[i+1])
            big=max(big, a[i+1])
        if a[i]!=-1 and a[i+1]==-1:
            small = min(small, a[i])
            big = max(big, a[i])
        if a[i]!=-1 and a[i+1]!=-1:
            ans=max(ans, abs(a[i]-a[i+1]))
    if big==-1:print(ans, 0)
    else:
        x=(small+big)//2
        ans=max(ans, abs(big-x))
        ans=max(ans, abs(x-small))
        print(ans, x)


Solve in Python:
Debug the functions
Should be easy, begin by looking at the code. Debug the code and the functions should work.
There are three functions: ```Multiplication (x)``` ```Addition (+)``` and ```Reverse (!esreveR)```

i {
  font-size:16px;
}

#heading {
  padding: 2em;
  text-align: center;
  background-color: #0033FF;
  width: 100%;
  height: 5em;
}

from functools import reduce

def multi(lst):
    return reduce(lambda m, n: m * n, lst, 1)

def add(lst):
    return sum(lst)

def reverse(string):
    return string[::-1]


Solve in Python:
Decompose a number `num` into an array (tuple in Haskell, array of arrays `long[][]` in C# or Java) of the form `[[k1,k2,k3...], r]`,  `([k1,k2,k3...], r)` in Haskell, `[[k1,k2,k3...], [r]]` in C# or Java) such that:

1. each kn is more than one
2. eack kn is maximized (first maximizing for 2 then 3 then 4 and so on)
3. and 2^(k1) + 3^(k2) + 4^(k3) + ... + n^(kn-1) + r = num

##Examples
```
# when there are no `k` more than 1:

3

[[], 3] =

3

# when the remainder is zero:

8330475

[[22, 13, 10, 8, 7, 6, 6, 5, 5, 5, 4, 4, 4, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2], 0] =

2 ^ 22 + 3 ^ 13 + 4 ^ 10 + 5 ^ 8 + 6 ^ 7 + 7 ^ 6 + 8 ^ 6 + 9 ^ 5 + 10 ^ 5 + 11 ^ 5 + 12 ^ 4 + 13 ^ 4 + 14 ^ 4 + 15 ^ 3 + 16 ^ 3 + 17 ^ 3 + 18 ^ 3 + 19 ^ 3 + 20 ^ 3 + 21 ^ 2 + 22 ^ 2 + 23 ^ 2 + 24 ^ 2 + 0 = 8330475

# when there is both `k` and a remainder:

26

[[4, 2], 1] =

2 ^ 4 + 3 ^ 2 + 1 = 26

# when there is neither `k` nor a remainder:

0

[[], 0] =

0
```

As allways any feedback would be much appreciated

from itertools import count
from math import log

def decompose(n):
    r = []
    for x in count(2):
        if x > n:
            break
        m = int(log(n, x))
        if m == 1:
            break
        r.append(m)
        n -= x**m
    return [r, n]


Solve in Python:
Dee is lazy but she's kind and she likes to eat out at all the nice restaurants and gastropubs in town. To make paying quick and easy she uses a simple mental algorithm she's called The Fair %20 Rule. She's gotten so good she can do this in a few seconds and it always impresses her dates but she's perplexingly still single. Like you probably.

This is how she does it:

 - She rounds the price `P` at the tens place e.g:
   - 25 becomes 30
   - 24 becomes 20
   - 5 becomes 10
   - 4 becomes 0
 - She figures out the base tip `T` by dropping the singles place digit e.g:
   - when `P = 24` she rounds to 20 drops 0 `T = 2`
   - `P = 115` rounds to 120 drops 0 `T = 12`
   - `P = 25` rounds to 30 drops 0 `T = 3`
   - `P = 5` rounds to 10 drops 0 `T = 1`
   - `P = 4` rounds to 0 `T = 0`
 - She then applies a 3 point satisfaction rating `R` to `T` i.e:
   - When she's satisfied: `R = 1` and she'll add 1 to `T`
   - Unsatisfied: `R = 0` and she'll subtract 1 from `T`
   - Appalled: `R = -1` she'll divide `T` by 2, **rounds down** and subtracts 1

## Your Task

Implement a method `calc_tip` that takes two integer arguments for price `p`

where `1 <= p <= 1000` and a rating `r` which is one of `-1, 0, 1`.

The return value `T` should be a non negative integer.

*Note: each step should be done in the order listed.*

Dee always politely smiles and says "Thank you" on her way out. Dee is nice. Be like Dee.


Solve in Python:
Define S = [s,n] as the string S which consists of n connected strings s. For example, ["abc", 3] ="abcabcabc".
On the other hand, we define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1. For example, “abc”  can be obtained from “abdbec” based on our definition, but it can not be obtained from “acbbe”.
You are given two non-empty strings s1 and s2 (each at most 100 characters long) and two integers 0 ≤ n1 ≤ 106 and 1 ≤ n2 ≤ 106. Now consider the strings S1 and S2, where S1=[s1,n1] and S2=[s2,n2]. Find the maximum integer M such that [S2,M] can be obtained from S1.

Example:

Input:
s1="acb", n1=4
s2="ab", n2=2

Return:
2

class Solution:
     def getMaxRepetitions(self, s1, n1, s2, n2):
         start = {} # s2_idx : s1_round, s2_round
         s1_round, s2_round, s2_idx = 0, 0, 0
         while s1_round < n1:
             s1_round += 1
             for ch in s1:
                 if ch == s2[s2_idx]:
                     s2_idx += 1
                     if s2_idx == len(s2):
                         s2_round += 1
                         s2_idx = 0
             if s2_idx in start:
                 prev_s1_round, prev_s2_round = start[s2_idx]
                 circle_s1_round, circle_s2_round = s1_round - prev_s1_round, s2_round - prev_s2_round
                 res = (n1 - prev_s1_round) // circle_s1_round * circle_s2_round
                 left_s1_round = (n1 - prev_s1_round) % circle_s1_round + prev_s1_round
                 for key, val in start.items():
                     if val[0] == left_s1_round:
                         res += val[1]
                         break
                 return res // n2
             else:
                 start[s2_idx] = (s1_round, s2_round)
         return s2_round // n2


Solve in Python:
Define a "prime prime" number to be a rational number written as one prime number over another prime number: `primeA / primeB` (e.g. `7/31`)

Given a whole number `N`, generate the number of "prime prime" rational numbers less than 1, using only prime numbers between `0` and `N` (non inclusive).

Return the count of these "prime primes", and the integer part  of their sum.

## Example

```python
N = 6

# The "prime primes" less than 1 are:
2/3, 2/5, 3/5               # count: 3

2/3 + 2/5 + 3/5 = 1.6667    # integer part: 1

Thus, the function should return 3 and 1.
```

import math

def is_prime(n):
    return n == 2 or n > 2 and n % 2 and all(n % i for i in range(3, int(n ** 0.5) + 1, 2))

def prime_primes(N):
    a = [i for i in range(2, N) if is_prime(i)]
    total, count = 0, 0
    for elem1 in a:
        for elem2 in a:
            if(elem1 < elem2):
                count += 1
                total += elem1 / elem2
    return (count, math.floor(total))


Solve in Python:
Define a function that removes duplicates from an array of numbers and returns it as a result.

The order of the sequence has to stay the same.

distinct = lambda seq: [ seq[i] for i in range(len(seq)) if seq[i] not in seq[:i] + seq[i+1:] or i == seq.index(seq[i]) ]


Solve in Python:
Define a function that takes in two non-negative integers `$a$` and `$b$` and returns the last decimal digit of `$a^b$`. Note that `$a$` and `$b$` may be very large!

For example, the last decimal digit of `$9^7$` is `$9$`, since `$9^7 = 4782969$`.  The last decimal digit of `$({2^{200}})^{2^{300}}$`, which has over `$10^{92}$` decimal digits, is `$6$`.  Also, please take `$0^0$` to be `$1$`.

You may assume that the input will always be valid.

## Examples

```python
last_digit(4, 1)                # returns 4
last_digit(4, 2)                # returns 6
last_digit(9, 7)                # returns 9
last_digit(10, 10 ** 10)        # returns 0
last_digit(2 ** 200, 2 ** 300)  # returns 6
```

___

## Remarks

### JavaScript, C++, R, PureScript

Since these languages don't have native arbitrarily large integers, your arguments are going to be strings representing non-negative integers instead.

def last_digit(n1, n2):
    m1=n1%10
    if m1==1:
        return 1
    if m1==2:
        if n2==0:
            return 1
        elif n2%4==3:
            return 8
        elif n2%4==0:
            return 6
        elif n2%4==2:
            return 4
        else:
            return 2
    if m1==3:
        if n2==0:
            return 1
        elif n2%4==0:
            return 1
        elif n2%2==0:
            return 9
        elif n2%4==3:
            return 7
        else:
            return 3
    if m1==4:
        if n2==0:
            return 1
        elif n2%4==2 or n2%4==0:
            return 6
        else:
            return 4
    if m1==5:
        if n2==0:
            return 1
        else:
            return 5
    if m1==6:
        if n2==0:
            return 1
        else:
            return 6
    if m1==7:
        if n2==0:
            return 1
        elif n2%4==3:
            return 3
        elif n2%4==0:
            return 1
        elif n2%4==2:
            return 9
        else:
            return 7
    if m1==8:
        if n2==0:
            return 1
        elif n2%4==3:
            return 2
        elif n2%4==0:
            return 6
        elif n2%4==2:
            return 4
        else:
            return 8
    if m1==9:
        if n2==0:
            return 1
        elif n2%2==1:
            return 9
        else:
            return 1
    if m1==0:
        if n2==0:
            return 1
        return 0


Solve in Python:
Define a function that takes one integer argument and returns logical value `true` or `false` depending on if the integer is a prime.

Per Wikipedia, a prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.

## Requirements

* You can assume you will be given an integer input.
* You can not assume that the integer will be only positive. You may be given negative numbers as well (or `0`).
* **NOTE on performance**: There are no fancy optimizations required, but still *the* most trivial solutions might time out. Numbers go up to 2^31 (or similar, depends on language version). Looping all the way up to `n`, or `n/2`, will be too slow.

## Example
```nasm
mov edi, 1
call is_prime    ; EAX <- 0 (false)

mov edi, 2
call is_prime    ; EAX <- 1 (true)

mov edi, -1
call is_prime    ; EAX <- 0 (false)
```

from math import sqrt
def is_prime(num):
    if num <= 1:
        return False
    i = 2
    while i <= sqrt(num):
        if num%i == 0:
            return False
        i += 1
    return True


Solve in Python:
Define a method ```hello``` that ```returns``` "Hello, Name!" to a given ```name```, or says Hello, World! if name is not given (or passed as an empty String).

Assuming that ```name``` is a ```String``` and it checks for user typos to return a name with a first capital letter (Xxxx).

Examples:

def hello(name = None):
    if name == '' or name == None:
        return "Hello, World!"
    else:
        name = name.lower()
        name = name.capitalize()

        return "Hello, " + name + "!"


Solve in Python:
Define a method that accepts 2 strings as parameters. The method returns the first string sorted by the second.

```python
sort_string("foos", "of")       == "oofs"
sort_string("string", "gnirts") == "gnirts"
sort_string("banana", "abn")    == "aaabnn"
```

To elaborate, the second string defines the ordering. It is possible that in the second string characters repeat, so you should remove repeating characters, leaving only the first occurrence.

Any character in the first string that does not appear in the second string should be sorted to the end of the result in original order.

def sort_string(s, ordering):
    result = sorted([c for c in s if c in ordering], key=ordering.find)
    result.extend([c for c in s if c not in ordering])
    return ''.join(result)


Solve in Python:
Define n!! as

n!! = 1 \* 3 \* 5 \* ... \* n  if n is odd,

n!! = 2 \* 4 \* 6 \* ... \* n  if n is even.

Hence 8!! = 2 \* 4 \* 6 \* 8 = 384, there is no zero at the end.
30!! has 3 zeros at the end.

For a positive integer n, please count how many zeros are there at
the end of n!!.

Example:

count\_zeros\_n\_double\_fact(30) should return 3

def count_zeros_n_double_fact(n):
    if n % 2 == 1:
        return 0
    return n // 10 + n // 50 + n // 250


Solve in Python:
Define two functions: `hex_to_bin` and `bin_to_hex` (or `hexToBin` and `binToHex`)

# hex_to_bin

Takes a hexadecimal string as an argument .

**Note:** This string can contain upper or lower case characters and start with any amount of zeros.

Returns the binary representation (without leading zeros) of the numerical value of the hexadecimal string.

Examples:

```
"00F"    -->  "1111"
"5"      -->  "101"
"00000"  -->  "0"
"04D2"   -->  "10011010010"
```

# bin_to_hex

Takes a binary string (with or without leading zeros) as an argument .

Returns the hexadecimal representation of the numerical value of the binary string.

**Note:** Any non-numerical characters should be lower case

Examples:

```
"1111"         -->  "f"
"000101"       -->  "5"
"10011010010"  -->  "4d2"
```

**Note:** You can assume all arguments are valid so there is no need for error checking.

Oh, and I've disabled a few things.

Any feedback would be much appreciated

D_S = '0123456789abcdef'
S_D = {d:n for n,d in enumerate(D_S)}

def convert(s,bIn,bOut):
    n = sum( S_D[d] * bIn**p for p,d in enumerate(reversed(s.lower())))
    out=[]
    while n:
        n,r = divmod(n,bOut)
        out.append(D_S[r])
    return ''.join(reversed(out)) or '0'

def bin_to_hex(s): return convert(s,2,16)
def hex_to_bin(s): return convert(s,16,2)


Solve in Python:
Denis was very sad after Nastya rejected him. So he decided to walk through the gateways to have some fun. And luck smiled at him! When he entered the first courtyard, he met a strange man who was selling something.

Denis bought a mysterious item and it was... Random permutation generator! Denis could not believed his luck.

When he arrived home, he began to study how his generator works and learned the algorithm. The process of generating a permutation consists of $n$ steps. At the $i$-th step, a place is chosen for the number $i$ $(1 \leq i \leq n)$. The position for the number $i$ is defined as follows:

  For all $j$ from $1$ to $n$, we calculate $r_j$  — the minimum index such that $j \leq r_j \leq n$, and the position $r_j$ is not yet occupied in the permutation. If there are no such positions, then we assume that the value of $r_j$ is not defined.  For all $t$ from $1$ to $n$, we calculate $count_t$  — the number of positions $1 \leq j \leq n$ such that $r_j$ is defined and $r_j = t$.  Consider the positions that are still not occupied by permutation and among those we consider the positions for which the value in the $count$ array is maximum.  The generator selects one of these positions for the number $i$. The generator can choose any position.

Let's have a look at the operation of the algorithm in the following example:

 [Image]

Let $n = 5$ and the algorithm has already arranged the numbers $1, 2, 3$ in the permutation. Consider how the generator will choose a position for the number $4$:

  The values of $r$ will be $r = [3, 3, 3, 4, \times]$, where $\times$ means an indefinite value.  Then the $count$ values will be $count = [0, 0, 3, 1, 0]$.  There are only two unoccupied positions in the permutation: $3$ and $4$. The value in the $count$ array for position $3$ is $3$, for position $4$ it is $1$.  The maximum value is reached only for position $3$, so the algorithm will uniquely select this position for number $4$.

Satisfied with his purchase, Denis went home. For several days without a...

import sys
input= sys.stdin.readline
t = int(input())
out = []
for _ in range(t):
    n = int(input())
    l = list(map(int,input().split()))

    smol = l[0]
    works = True
    for i in range(1, n):
        if l[i] == l[i-1] + 1:
            pass
        else:
            if l[i] > smol:
                works = False
                break
        smol = min(smol, l[i])

    if works:
        out.append('Yes')
    else:
        out.append('No')
print('\n'.join(out))


Solve in Python:
Deoxyribonucleic acid (DNA) is a chemical found in the nucleus of cells and carries the "instructions" for the development and functioning of living organisms.

If you want to know more http://en.wikipedia.org/wiki/DNA

In DNA strings, symbols "A" and "T" are complements of each other, as "C" and "G".
You have function with one side of the DNA (string, except for Haskell); you need to get the other complementary side. DNA strand is never empty or there is no DNA at all (again, except for Haskell).

More similar exercise are found here http://rosalind.info/problems/list-view/ (source)

```python
DNA_strand ("ATTGC") # return "TAACG"

DNA_strand ("GTAT") # return "CATA"
```

pairs = {'A':'T','T':'A','C':'G','G':'C'}
def DNA_strand(dna):
    return ''.join([pairs[x] for x in dna])


Solve in Python:
Deoxyribonucleic acid, DNA is the primary information storage molecule in biological systems. It is composed of four nucleic acid bases Guanine ('G'), Cytosine ('C'), Adenine ('A'), and Thymine ('T').

Ribonucleic acid, RNA, is the primary messenger molecule in cells. RNA differs slightly from DNA its chemical structure and contains no Thymine. In RNA Thymine is replaced by another nucleic acid Uracil ('U').

Create a function which translates a given DNA string into RNA.

For example:

```
"GCAT"  =>  "GCAU"
```

The input string can be of arbitrary length - in particular, it may be empty.  All input is guaranteed to be valid, i.e. each input string will only ever consist of `'G'`, `'C'`, `'A'` and/or `'T'`.

def dna_to_rna(dna):
    dna_bases = []
    for item in dna:
        dna_bases.append(str(item))
    rna_lst = []
    for item in dna_bases:
        if item == 'A' or item == 'C' or item == 'G':
            rna_lst.append(item)
        elif item == 'T':
            rna_lst.append('U')
        else:
            print("This is no dna structure")
            break
    rna = ''.join(rna_lst)
    return rna


Solve in Python:
Description

In English we often use "neutral vowel sounds" such as "umm", "err", "ahh" as fillers in conversations to help them run smoothly.

Bob always finds himself saying "err". Infact he adds an "err" to every single word he says that ends in a consonant! Because Bob is odd, he likes to stick to this habit even when emailing.

Task

Bob is begging you to write a function that adds "err" to the end of every word whose last letter is a consonant (not a vowel, y counts as a consonant).

The input is a string that can contain upper and lowercase characters, some punctuation but no numbers. The solution should be returned as a string.

NOTE: If the word ends with an uppercase consonant, the following "err" will be uppercase --> "ERR".

eg:
```
"Hello, I am Mr Bob" --> "Hello, I amerr Mrerr Boberr"

"THIS IS CRAZY!"  --> "THISERR ISERR CRAZYERR!"
```

Good luck!

import re

def err_bob(s):
    return re.sub(
        r'[bcdfghjklmnpqrstvwxyz]\b',
        lambda m: m.group() + ('err' if m.group().islower() else 'ERR'),
        s,
        flags=re.IGNORECASE
    )


Solve in Python:
Description

Lets imagine a yoga classroom as a Square 2D Array of Integers ```classroom```, with each integer representing a person, and the value representing their skill level.

```
classroom = [
            [3,2,1,3],
            [1,3,2,1],
            [1,1,1,2],
            ]

poses = [1,7,5,9,10,21,4,3]
```

During a yoga class the instructor gives a list of integers ```poses``` representing a yoga pose that each person in the class will attempt to complete.

A person can complete a yoga pose if the sum of their row and their skill level is greater than or equal to the value of the pose.

 Task

Your task is to return the total amount poses completed for the entire ```classroom```.

Example

```
classroom = [
            [1,1,0,1], #sum = 3
            [2,0,6,0], #sum = 8
            [0,2,2,0], #sum = 4
            ]

poses = [4, 0, 20, 10]

3 people in row 1 can complete the first pose
Everybody in row 1 can complete the second pose
Nobody in row 1 can complete the third pose
Nobody in row 1 can complete the fourth pose

The total poses completed for row 1 is 7

You'll need to return the total for all rows and all poses.
```

Translations are welcomed!

def yoga(classroom, poses):
    result = 0
    for row in classroom:
        s = sum(row)
        result += sum(s+x >= p for x in row for p in poses)
    return result


Solve in Python:
Description overhauled by V

---

I've invited some kids for my son's birthday, during which I will give to each kid some amount of candies.

Every kid hates receiving less amount of candies than any other kids, and I don't want to have any candies left - giving it to my kid would be bad for his teeth.

However, not every kid invited will come to my birthday party.

What is the minimum amount of candies I have to buy, so that no matter how many kids come to the party in the end, I can still ensure that each kid can receive the same amount of candies, while leaving no candies left?

It's ensured that at least one kid will participate in the party.

from operator import mul
from functools import reduce
def candies_to_buy(n):
    ret = []
    for i in range(1, n + 1):
        s = i
        for j in ret:
            if s % j == 0:
                s //= j
            if s == 1:
                break
        ret.append(s)
    return  reduce(mul, ret)


Solve in Python:
Description:

#Task:

Write a function that returns true if the number is a "Very Even" number.

If a number is a single digit, then it is simply "Very Even" if it itself is even.

If it has 2 or more digits, it is "Very Even" if the sum of it's digits is "Very Even".

#Examples:
```
input(88) => returns false -> 8 + 8 = 16 -> 1 + 6 = 7 => 7 is odd

input(222) => returns true

input(5) => returns false

input(841) => returns true -> 8 + 4 + 1 = 13 -> 1 + 3 => 4 is even
```

Note: The numbers will always be 0 or positive integers!

def is_very_even_number(n):
    return is_very_even_number(sum(int(i) for i in str(n))) if n > 9 else not n% 2


Solve in Python:
Description:

The mean (or average) is the most popular measure of central tendency; however it does not behave very well when the data is skewed (i.e. wages distribution). In such cases, it's better to use the median.

Your task for this kata is to find the median of an array consisting of n elements.

You can assume that all inputs are arrays of numbers in integer format. For the empty array your code should return `NaN` (false in JavaScript/`NULL` in PHP/`nil` in Ruby).

Examples:

Input `[1, 2, 3, 4]` --> Median `2.5`

Input `[3, 4, 1, 2, 5]` --> Median `3`

from random import choice

def median(lst):
    return quickselect(lst, len(lst) // 2, len(lst) % 2 == 0)

def quickselect(lst, nth, even):
    # O(n) but what a pain to get right.
    pivot = choice(lst)
    smaller = [n for n in lst if n < pivot]
    n_equal = sum(n == pivot for n in lst)
    bigger = [n for n in lst if n > pivot]
    if even:
        if len(smaller) > nth:
            return quickselect(smaller, nth, True)
        elif len(smaller) == nth:
            return (pivot + quickselect(smaller, nth - 1, False)) / 2
        elif len(smaller) + n_equal > nth:
            return pivot
        elif len(smaller) + n_equal == nth:
            return (pivot + quickselect(bigger, nth - len(smaller) - n_equal, False)) / 2
        else:
            return quickselect(bigger, nth - len(smaller) - n_equal, True)
    else:
        if len(smaller) > nth:
            return quickselect(smaller, nth, False)
        elif len(smaller) + n_equal > nth:
            return pivot
        else:
            return quickselect(bigger, nth - len(smaller) - n_equal, False)


Solve in Python:
Design a Skiplist without using any built-in libraries.
A Skiplist is a data structure that takes O(log(n)) time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists are just simple linked lists.
For example: we have a Skiplist containing [30,40,50,60,70,90] and we want to add 80 and 45 into it. The Skiplist works this way:

Artyom Kalinin [CC BY-SA 3.0], via Wikimedia Commons
You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add , erase and search can be faster than O(n). It can be proven that the average time complexity for each operation is O(log(n)) and space complexity is O(n).
To be specific, your design should include these functions:

bool search(int target) : Return whether the target exists in the Skiplist or not.
void add(int num): Insert a value into the SkipList.
bool erase(int num): Remove a value in the Skiplist. If num does not exist in the Skiplist, do nothing and return false. If there exists multiple num values, removing any one of them is fine.

See more about Skiplist : https://en.wikipedia.org/wiki/Skip_list
Note that duplicates may exist in the Skiplist, your code needs to handle this situation.

Example:
Skiplist skiplist = new Skiplist();

skiplist.add(1);
skiplist.add(2);
skiplist.add(3);
skiplist.search(0);   // return false.
skiplist.add(4);
skiplist.search(1);   // return true.
skiplist.erase(0);    // return false, 0 is not in skiplist.
skiplist.erase(1);    // return true.
skiplist.search(1);   // return false, 1 has already been erased.

Constraints:

0 <= num, target <= 20000
At most 50000 calls will be made to search, add, and erase.

class Node:
    def __init__(self, val):
        self.val = val
        self.right, self.down = None, None

class Skiplist:

    def __init__(self):
        self.head = [Node(float('-inf')) for _ in range(16)]
        self.tail = [Node(float('inf')) for _ in range(16)]

        for h, t in zip(self.head, self.tail):
            h.right = t

        for up, down in zip(self.head, self.head[1:]):
            up.down = down

    def search(self, target: int) -> bool:
        current = self.head[0]
        while current:
            if current.val < target <= current.right.val:
                if current.right.val == target: return True
                current = current.down
            else:
                current = current.right
        return False

    def add(self, num: int) -> None:
        stack = []
        current = self.head[0]
        while current:
            if current.val < num <= current.right.val:
                stack.append(current)
                current = current.down
            else:
                current = current.right
        prev = None
        while stack:
            current = stack.pop()
            node = Node(num)
            node.right, current.right = current.right, node
            if prev: node.down = prev
            prev = node

            if random.randint(0, 1): break

    def erase(self, num: int) -> bool:
        current = self.head[0]
        is_removed = False
        while current:
            if current.val < num <= current.right.val:
                if current.right.val == num:
                    current.right = current.right.right
                    is_removed = True
                current = current.down
            else:
                current = current.right
        return is_removed


Solve in Python:
Design a data structure that supports all following operations in average O(1) time.

insert(val): Inserts an item val to the set if not already present.
remove(val): Removes an item val from the set if present.
getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.

Example:

// Init an empty set.
RandomizedSet randomSet = new RandomizedSet();

// Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomSet.insert(1);

// Returns false as 2 does not exist in the set.
randomSet.remove(2);

// Inserts 2 to the set, returns true. Set now contains [1,2].
randomSet.insert(2);

// getRandom should return either 1 or 2 randomly.
randomSet.getRandom();

// Removes 1 from the set, returns true. Set now contains [2].
randomSet.remove(1);

// 2 was already in the set, so return false.
randomSet.insert(2);

// Since 2 is the only number in the set, getRandom always return 2.
randomSet.getRandom();

class RandomizedSet:

     def __init__(self):
         """
         Initialize your data structure here.
         """
         self.dic = {}
         self.l = []

     def insert(self, val):
         """
         Inserts a value to the set. Returns true if the set did not already contain the specified element.
         :type val: int
         :rtype: bool
         """
         if val in self.dic:
             return False
         self.l.append(val)
         self.dic[val] = len(self.l) - 1
         return True

     def remove(self, val):
         """
         Removes a value from the set. Returns true if the set contained the specified element.
         :type val: int
         :rtype: bool
         """
         if val not in self.dic:
             return False
         self.dic[self.l[-1]] = self.dic[val]
         self.l[self.dic[val]], self.l[-1] = self.l[-1], self.l[self.dic[val]]
         self.l.pop()
         del self.dic[val]
         return True

     def getRandom(self):
         """
         Get a random element from the set.
         :rtype: int
         """
         return random.choice(self.l)

 # Your RandomizedSet object will be instantiated and called as such:
 # obj = RandomizedSet()
 # param_1 = obj.insert(val)
 # param_2 = obj.remove(val)
 # param_3 = obj.getRandom()


Solve in Python:
Design a data structure that supports all following operations in average O(1) time.
Note: Duplicate elements are allowed.

insert(val): Inserts an item val to the collection.
remove(val): Removes an item val from the collection if present.
getRandom: Returns a random element from current collection of elements. The probability of each element being returned is linearly related to the number of same value the collection contains.

Example:

// Init an empty collection.
RandomizedCollection collection = new RandomizedCollection();

// Inserts 1 to the collection. Returns true as the collection did not contain 1.
collection.insert(1);

// Inserts another 1 to the collection. Returns false as the collection contained 1. Collection now contains [1,1].
collection.insert(1);

// Inserts 2 to the collection, returns true. Collection now contains [1,1,2].
collection.insert(2);

// getRandom should return 1 with the probability 2/3, and returns 2 with the probability 1/3.
collection.getRandom();

// Removes 1 from the collection, returns true. Collection now contains [1,2].
collection.remove(1);

// getRandom should return 1 and 2 both equally likely.
collection.getRandom();

import random
 class RandomizedCollection:

     def __init__(self):
         """
         Initialize your data structure here.
         """
         self.val = []
         self.idx = {}

     def insert(self, val):
         """
         Inserts a value to the collection. Returns true if the collection did not already contain the specified element.
         :type val: int
         :rtype: bool
         """
         self.val.append(val)
         if val in self.idx:
             self.idx[val].append(len(self.val) - 1)
             return False
         else:
             self.idx[val] = [len(self.val) - 1]

     def remove(self, val):
         """
         Removes a value from the collection. Returns true if the collection contained the specified element.
         :type val: int
         :rtype: bool
         """
         if val not in self.idx:
             return False
         #print(self.val, self.idx)
         self.val[self.idx[val][-1]] = self.val[-1]
         if self.idx[self.val[-1]][-1] != self.idx[val][-1]:
             self.idx[self.val[-1]].pop()
             self.idx[self.val[-1]].append(self.idx[val][-1])
             self.idx[self.val[-1]].sort()
         self.val.pop()
         self.idx[val].pop()
         if len(self.idx[val]) == 0:
             del self.idx[val]
         return True

     def getRandom(self):
         """
         Get a random element from the collection.
         :rtype: int
         """
         return random.choice(self.val)

 # Your RandomizedCollection object will be instantiated and called as such:
 # obj = RandomizedCollection()
 # param_1 = obj.insert(val)
 # param_2 = obj.remove(val)
 # param_3 = obj.getRandom()


Solve in Python:
Design a data structure that supports the following two operations:

* `addWord` (or `add_word`) which adds a word,
* `search` which searches a literal word or a regular expression string containing lowercase letters `"a-z"` or `"."` where `"."` can represent any letter

You may assume that all given words contain only lowercase letters.

## Examples
```python
add_word("bad")
add_word("dad")
add_word("mad")

search("pad") == False
search("bad") == True
search(".ad") == True
search("b..") == True
```

**Note:** the data structure will be initialized multiple times during the tests!

import re
class WordDictionary:
    def __init__(self):
       self.words = []

    def add_word(self,v):
       self.words.append(v)

    def search(self,rg):
        return any(re.match(r'^{}$'.format(rg),i) for i in self.words)


Solve in Python:
Design a simplified version of Twitter where users can post tweets, follow/unfollow another user and is able to see the 10 most recent tweets in the user's news feed. Your design should support the following methods:

postTweet(userId, tweetId): Compose a new tweet.
getNewsFeed(userId): Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.
follow(followerId, followeeId): Follower follows a followee.
unfollow(followerId, followeeId): Follower unfollows a followee.

Example:

Twitter twitter = new Twitter();

// User 1 posts a new tweet (id = 5).
twitter.postTweet(1, 5);

// User 1's news feed should return a list with 1 tweet id -> [5].
twitter.getNewsFeed(1);

// User 1 follows user 2.
twitter.follow(1, 2);

// User 2 posts a new tweet (id = 6).
twitter.postTweet(2, 6);

// User 1's news feed should return a list with 2 tweet ids -> [6, 5].
// Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5.
twitter.getNewsFeed(1);

// User 1 unfollows user 2.
twitter.unfollow(1, 2);

// User 1's news feed should return a list with 1 tweet id -> [5],
// since user 1 is no longer following user 2.
twitter.getNewsFeed(1);

class Twitter:

     def __init__(self):
         """
         Initialize your data structure here.
         """
         # e.g. [{"user1":"tweet1"}, {"user2":"tweet2"},...] - fast tweets access
         self.tweets = []

         # e.g. {"user1":[0,2,4,5], "user2":[1,3]} - fast user-tweets access
         self.userTweets = {}

         # e.g. {"user1":[0,1,2,3,4,5]}
         self.feeds = {}

         # e.g. {user2:[1]}
         self.followers = {}
         self.followees = {}
         # eg. {(user1,user2):True}
         self.relations = {}

     def postTweet(self, userId, tweetId):
         """
         Compose a new tweet.
         :type userId: int
         :type tweetId: int
         :rtype: void
         """
         # create tweet
         self.tweets.append({"userId":userId, "tweetId":tweetId})
         lastIndex = len(self.tweets)-1

         # create user tweet list
         if userId not in self.userTweets:
             self.userTweets[userId] = []
         self.userTweets[userId].append(lastIndex)

         # update feeds
         followers = self.followers.get(userId, [])
         for followerId in [userId]+followers:
             # add tweet, reverse sort, cut recent 10
             self.feeds[followerId] = ([tweetId] + self.feeds.get(followerId, []))[:10]

     def getNewsFeed(self, userId):
         """
         Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.
         :type userId: int
         :rtype: List[int]
         """
         return self.feeds.get(userId, [])

     def follow(self, followerId, followeeId):
         """
         Follower follows a followee. If the operation is invalid, it should be a no-op.
         :type followerId: int
         :type followeeId: int
         :rtype: void
         """
         # no-op case
         if (followerId,...


Solve in Python:
Design a stack which supports the following operations.
Implement the CustomStack class:

CustomStack(int maxSize) Initializes the object with maxSize which is the maximum number of elements in the stack or do nothing if the stack reached the maxSize.
void push(int x) Adds x to the top of the stack if the stack hasn't reached the maxSize.
int pop() Pops and returns the top of stack or -1 if the stack is empty.
void inc(int k, int val) Increments the bottom k elements of the stack by val. If there are less than k elements in the stack, just increment all the elements in the stack.

Example 1:
Input
["CustomStack","push","push","pop","push","push","push","increment","increment","pop","pop","pop","pop"]
[[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]]
Output
[null,null,null,2,null,null,null,null,null,103,202,201,-1]
Explanation
CustomStack customStack = new CustomStack(3); // Stack is Empty []
customStack.push(1);                          // stack becomes [1]
customStack.push(2);                          // stack becomes [1, 2]
customStack.pop();                            // return 2 --> Return top of the stack 2, stack becomes [1]
customStack.push(2);                          // stack becomes [1, 2]
customStack.push(3);                          // stack becomes [1, 2, 3]
customStack.push(4);                          // stack still [1, 2, 3], Don't add another elements as size is 4
customStack.increment(5, 100);                // stack becomes [101, 102, 103]
customStack.increment(2, 100);                // stack becomes [201, 202, 103]
customStack.pop();                            // return 103 --> Return top of the stack 103, stack becomes [201, 202]
customStack.pop();                            // return 202 --> Return top of the stack 102, stack becomes [201]
customStack.pop();                            // return 201 --> Return top of the stack 101, stack becomes []
customStack.pop();                            // return -1 --> Stack is empty return -1.

Constraints:

1 <= maxSize <= 1000
1 <=...

class CustomStack:

    def __init__(self, maxSize: int):
        self.maxSize = maxSize
        self.stack = []
        self.incre = []

    def push(self, x: int) -> None:
        if len(self.stack) < self.maxSize:
            self.stack.append(x)
            self.incre.append(0)

    def pop(self) -> int:
        if self.stack:
            if len(self.incre) > 1:
                self.incre[-2] += self.incre[-1]
            return self.stack.pop() + self.incre.pop()
        else:
            return -1

    def increment(self, k: int, val: int) -> None:
        if self.incre:
            self.incre[min(len(self.incre), k)-1] += val

# Your CustomStack object will be instantiated and called as such:
# obj = CustomStack(maxSize)
# obj.push(x)
# param_2 = obj.pop()
# obj.increment(k,val)


Solve in Python:
Design an Iterator class, which has:

A constructor that takes a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments.
A function next() that returns the next combination of length combinationLength in lexicographical order.
A function hasNext() that returns True if and only if there exists a next combination.

Example:
CombinationIterator iterator = new CombinationIterator("abc", 2); // creates the iterator.

iterator.next(); // returns "ab"
iterator.hasNext(); // returns true
iterator.next(); // returns "ac"
iterator.hasNext(); // returns true
iterator.next(); // returns "bc"
iterator.hasNext(); // returns false

Constraints:

1 <= combinationLength <= characters.length <= 15
There will be at most 10^4 function calls per test.
It's guaranteed that all calls of the function next are valid.

class CombinationIterator:

    def __init__(self, characters: str, combinationLength: int):
        self.combinations = self.get_combinations(characters,combinationLength,0)
        self.next_item=0

    def next(self) -> str:
        ans= self.combinations[self.next_item]
        self.next_item+=1
        return \"\".join(ans)

    def hasNext(self) -> bool:
        return self.next_item < len(self.combinations)

    def get_combinations(self,chars, k, start):
        ans = []
        if k == 0:
            return ans
        if k==1:
            return [[char] for char in chars[start:] ]
        count = 0
        for c in chars[start:]:
            for comb in self.get_combinations(chars, k - 1,start+count+1):
                    temp = []
                    temp.append(c)
                    temp.extend(comb)
                    ans.append(temp)
            count+=1
        return ans

# Your CombinationIterator object will be instantiated and called as such:
# obj = CombinationIterator(characters, combinationLength)
# param_1 = obj.next()
# param_2 = obj.hasNext()


Solve in Python:
Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

       Each row must contain the digits 1-9 without repetition.
       Each column must contain the digits 1-9 without repetition.
       Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.

A partially filled sudoku which is valid.

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.

Example 1:

Input:
[
  ["5","3",".",".","7",".",".",".","."],
  ["6",".",".","1","9","5",".",".","."],
  [".","9","8",".",".",".",".","6","."],
  ["8",".",".",".","6",".",".",".","3"],
  ["4",".",".","8",".","3",".",".","1"],
  ["7",".",".",".","2",".",".",".","6"],
  [".","6",".",".",".",".","2","8","."],
  [".",".",".","4","1","9",".",".","5"],
  [".",".",".",".","8",".",".","7","9"]
]
Output: true

Example 2:

Input:
[
  ["8","3",".",".","7",".",".",".","."],
  ["6",".",".","1","9","5",".",".","."],
  [".","9","8",".",".",".",".","6","."],
  ["8",".",".",".","6",".",".",".","3"],
  ["4",".",".","8",".","3",".",".","1"],
  ["7",".",".",".","2",".",".",".","6"],
  [".","6",".",".",".",".","2","8","."],
  [".",".",".","4","1","9",".",".","5"],
  [".",".",".",".","8",".",".","7","9"]
]
Output: false
Explanation: Same as Example 1, except with the 5 in the top left corner being
    modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.

Note:

       A Sudoku board (partially filled) could be valid but is not necessarily solvable.
       Only the filled cells need to be validated according to the mentioned rules.
       The given board contain only digits 1-9 and the character '.'.
       The given board size is always 9x9.

class Solution:
     def isValidSudoku(self, board):
         """
         :type board: List[List[str]]
         :rtype: bool
         """
         check = set()
         for i in range(0, 9):
             for j in range(0, 9):
                 if (board[i][j] == '.'):
                     continue
                 if (board[i][j] in check):
                     return False
                 check.add(board[i][j])
             check.clear()

         for j in range(0,9):
             for i in range(0,9):
                 if (board[i][j] == "."):
                     continue
                 if (board[i][j] in check):
                     return False
                 check.add(board[i][j])
             check.clear()

         for k in range(0, 9):
             for i in range(int(k / 3) * 3, int(k / 3) * 3 + 3):
                 for j in range((k % 3) * 3, (k % 3) * 3 + 3):
                     if (board[i][j] == '.'):
                         continue
                     if (board[i][j] in check):
                         return False
                     check.add(board[i][j])
             check.clear()

         return True


Solve in Python:
Determine the **area** of the largest square that can fit inside a circle with radius *r*.

def area_largest_square(r):
    diagonal = r*2
    return diagonal**2/2


Solve in Python:
Determine the total number of digits in the integer (`n>=0`) given as input to the function. For example, 9 is a single digit, 66 has 2 digits and 128685 has 6 digits. Be careful to avoid overflows/underflows.

All inputs will be valid.

def digits(n):
    conv = str(n)
    counter = 0
    for i in conv:
        counter += 1
    return counter


Solve in Python:
DevOps legacy roasting!
Save the business from technological purgatory.

Convert IT to DevOps, modernize application workloads, take it all to the Cloud…….

You will receive a string of workloads represented by words….some legacy and some modern mixed in with complaints from the business….your job is to burn the legacy in a disco inferno and count the value of each roasting and the number of complaints resolved.

```
complaints (in this format, case-insensitive) -> "slow!", "expensive!", "manual!", "down!", "hostage!", "security!"

```

The value is based on real or perceived pain by the business and the expense of keeping it all running.

Pull the values from the list below...

```
1970s Disco Fever Architecture………
Sort of like a design from Saturday night Fever….

            (  .      )
                )           (              )
                      .  '   .   '  .  '  .
             (    , )       (.   )  (   ',    )
              .' ) ( . )    ,  ( ,     )   ( .
           ). , ( .   (  ) ( , ')  .' (  ,    )
          (_,) . ), ) _) _,')  (, ) '. )  ,. (' )
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            Burn Baby Burn in a Disco Inferno

Legacy is identified by the following keywords:

1000 points - COBOL of any kind whatsoever
              keyword => "COBOL"
500 points  - non-object oriented architecture
              keyword => "nonobject"
500 points  - monolithic architecture
              keyword => "monolithic"
100 points  - fax system dependencies
              keyword => "fax"
100 points  - modem dependencies
              keyword => "modem"
50 points   - thick client dependencies
              keyword => "thickclient"
50 points   - tape drive dependencies
              keyword => "tape"
50 points   - floppy drive dependencies
              keyword => "floppy"
50 points   - workloads with DevOps Anti-patterns
              keyword => "oldschoolIT"

The count is based on case-insensitive words!

Return a string in the following format

->'Burn baby burn disco inferno 2400...

def roast_legacy(workloads):
    points = {'cobol': 1000, 'nonobject': 500, 'monolithic': 500, 'fax': 100,
              'modem': 100, 'thickclient': 50, 'tape': 50, 'floppy': 50, 'oldschoolit': 50 }
    complaints = ['slow!', 'expensive!', 'manual!', 'down!', 'hostage!', 'security!']

    work_loads = workloads.lower()

    count = sum(work_loads.count(complaint) for complaint in complaints)
    legacy = sum(p * work_loads.count(k) for k, p in points.items())

    if not count and not legacy: return 'These guys are already DevOps and in the Cloud and the business is happy!'
    return 'Burn baby burn disco inferno {} points earned in this roasting and {} complaints resolved!'.format(legacy, count)


Solve in Python:
Devu and Churu love to play games a lot. Today, they have an array A consisting of N positive integers. First they listed all N × (N+1) / 2 non-empty continuous subarrays of the array A on a piece of paper and then replaced all the subarrays on the paper with the maximum element present in the respective subarray.
Devu and Churu decided to play a game with numbers on the paper. They both have decided to make moves turn by turn. In one turn, the player picks some number from the list and discards that number. The one who is not able to make a valid move will be the loser. To make the game more interesting, they decided to put some constraints on their moves.
A constraint on a game can be any of following three types :
-  > K : They are allowed to choose numbers having values strictly greater than K only.
-  < K : They are allowed to choose numbers having values strictly less than K only.
-  = K : They are allowed to choose numbers having values equal to K only.

Given M constraints and who goes first, you have to tell the outcome of each game. Print 'D' if Devu wins otherwise print 'C' without quotes.
Note that M games are independent, that is, they'll rewrite numbers by using array A after each game. (This is the task for the loser of the previous game!)

-----Input -----
First line of input contains two space separated integers N and M denoting the size of array A and number of game played by them. Next line of input contains N space-separated integers denoting elements of array A. Each of the next M lines of input contains three space-separated parameters describing a game. First two parameter are a character C ∈ {<, >, =} and an integer K denoting the constraint for that game. The last parameter is a character X ∈ {D, C} denoting the player who will start the game.

----- Output -----
Output consists of a single line containing a string of length M made up from characters D and C only, where ith character in the string denotes the outcome of the ith game.

----- Constraints: -----
- 1 ≤ N, M ≤ 106
- 1 ≤...

def left_span(arr,n):
 ans=[0]
 span=[0]
 for i in range(1,n):

  while span and arr[i]>arr[span[-1]]:
   span.pop()

  if not span:
   ans.append(0)

  else:
   ans.append(span[-1]+1)
  span.append(i)
 return ans

def right_span(arr,n):
 ans=[n+1]
 span=[n-1]
 for i in range(n-2,-1,-1):

  while span and arr[i]>=arr[span[-1]]:
   span.pop()

  if not span:
   ans.append(n+1)
  else:
   ans.append(span[-1]+1)
  span.append(i)
 return ans[::-1]
from collections import Counter
from bisect import bisect_left,bisect_right
from operator import itemgetter
n,q=list(map(int,input().split( )))
arr=list(map(int,input().split( )))

left=left_span(arr,n)
right=right_span(arr,n)
c=Counter()
for i in range(n):
 c[arr[i]]+=(right[i]-(i+1))*(i+1-left[i])
a=sorted(c)
f=[]
for v in a:
 f.append(c[v])
prefix_sum=[f[0]]
n=len(f)
for i in range(1,n):
 prefix_sum.append(f[i]+prefix_sum[-1])
r=[0]*q
for i in range(q):
 sign,k,player=list(map(str,input().split( )))
 k=int(k)
 if sign=="=":
  if k in c:
   res=c[k]
  else:
   res=0
 elif sign==">":
  j=bisect_left(a,k)
  if j==n:
   res=0
  elif a[j]==k:
   res=prefix_sum[-1] - prefix_sum[j]
  else:
   if j>0:
    res=prefix_sum[-1] - prefix_sum[j-1]
   else:
    res=prefix_sum[-1]
 else:
  j=bisect_left(a,k)
  if j==0:
   res=0
  else:
   res=prefix_sum[j-1]

 if res%2==0:
  if player=="D":
   r[i]="C"
  else:
   r[i]="D"
 else:
  r[i]=player
print(''.join(r))


Solve in Python:
Devu has n weird friends. Its his birthday today, so they thought that this is the best occasion for testing their friendship with him. They put up conditions before Devu that they will break the friendship unless he gives them a grand party on their chosen day. Formally, ith friend will break his friendship if he does not receive a grand party on dith day.

Devu despite being as rich as Gatsby, is quite frugal and can give at most one grand party daily. Also, he wants to invite only one person in a party. So he just wonders what is the maximum number of friendships he can save. Please help Devu in this tough task !!

-----Input-----
- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
- First line will contain a single integer denoting n.

- Second line will contain n space separated integers where ith integer corresponds to the day dith as given in the problem.

-----Output-----
Print a single line corresponding to the answer of the problem.

-----Constraints-----
- 1 ≤ T ≤ 104
- 1 ≤ n  ≤ 50
- 1 ≤ di ≤ 100

-----Example-----
Input:
2
2
3 2
2
1 1
Output:
2
1

-----Explanation-----
Example case 1. Devu can give party to second friend on day 2 and first friend on day 3, so he can save both his friendships.
Example case 2. Both the friends want a party on day 1, and as the Devu can not afford more than one party a day, so he can save only one of the friendships, so answer is 1.

# cook your dish here
for _ in range(int(input())):
 n=int(input())
 l=list(map(int,input().split()))
 s=set(l)
 l1=list(s)
 print(len(l1))


Solve in Python:
Devu is a class teacher of a class of n students. One day, in the morning prayer of the school, all the students of his class were standing in a line. You are given information of their arrangement by a string s. The string s consists of only letters 'B' and 'G', where 'B' represents a boy and 'G' represents a girl.
Devu wants inter-gender interaction among his class should to be maximum. So he does not like seeing two or more boys/girls standing nearby (i.e. continuous) in the line. e.g. he does not like the arrangements BBG and GBB, but he likes BG, GBG etc.
Now by seeing the initial arrangement s of students, Devu may get furious and now he wants to change this arrangement into a likable arrangement. For achieving that, he can swap positions of any two students (not necessary continuous). Let the cost of swapping people from position i with position j (i ≠ j) be c(i, j). You are provided an integer variable type, then the cost of the the swap will be defined by c(i, j) = |j − i|type.

Please help Devu in finding minimum cost of swaps needed to convert the current arrangement into a likable one.

-----Input-----
The first line of input contains an integer T, denoting the number of test cases. Then T test cases are follow.
The first line of each test case contains an integer type, denoting the type of the cost function. Then the next line contains string s of length n, denoting the initial arrangement s of students.
Note that the integer n is not given explicitly in input.

-----Output-----
For each test case, print a single line containing the answer of the test case, that is, the minimum cost to convert the current arrangement into a likable one. If it is not possible to convert the current arrangement into a likable one, then print -1 instead of the minimum cost.

-----Constraints and Subtasks-----Subtask 1: 25 points
- 1 ≤ T ≤ 105
- 1 ≤ n ≤ 105
- type = 0
- Sum of n over all the test cases in one test file does not exceed 106.
Subtask 2: 25 points
- 1 ≤ T ≤ 105
- 1 ≤ n ≤ 105
- type = 1
- Sum of n over...

def actual_generator(a,N,start):
 result = []
 if a == 'B':
  result = ['B', 'G'] * (N // 2)
  result.append('B')
 elif a == 'G':
  result = ['G', 'B'] * (N // 2)
  result.append('G')
 else:
  if start == 'B':
   result = ['B', 'G'] * (N // 2)
  elif start == 'G':
   result = ['G', 'B'] * (N // 2)
 return result

for _ in range(int(input())):
 typ = int(input())
 s = input()
 N = len(s)
 array = [s[i] for i in range(N)]
 countG = array.count('G')
 countB = array.count('B')
 if abs(countG - countB) > 1:
  print(-1)
 else:
  defectB = []
  defectG = []
  if countG == countB:
   actual1 = actual_generator('X', N, 'B')
   actual2 = actual_generator('X', N, 'G')
   defect1B = []
   defect1G = []
   defect2B = []
   defect2G = []
   for i in range(N):
    if actual1[i] != array[i] and actual1[i] == 'B':
     defect1B.append(i)
    elif actual1[i] != array[i] and actual1[i] == 'G':
     defect1G.append(i)
   for i in range(N):
    if actual2[i] != array[i] and actual2[i] == 'B':
     defect2B.append(i)
    elif actual2[i] != array[i] and actual2[i] == 'G':
     defect2G.append(i)
   if len(defect1B) > len(defect2B):
    defectG = defect2G
    defectB = defect2B
   else :
    defectG = defect1G
    defectB = defect1B
  elif countG > countB:
   actual = actual_generator('G', N, 'X')
   defectB = []
   defectG = []
   for i in range(N):
    if actual[i] != array[i] and actual[i] == 'B':
     defectB.append(i)
    elif actual[i] != array[i] and actual[i] == 'G':
     defectG.append(i)

  elif countB > countG:
   actual = actual_generator('B', N, 'X')
   defectB = []
   defectG = []
   for i in range(N):
    if actual[i] != array[i] and actual[i] == 'B':
     defectB.append(i)
    elif actual[i] != array[i] and actual[i] == 'G':
     defectG.append(i)

  if typ == 0 :
   print(len(defectB))
  elif typ == 1 :
   print(abs(sum(defectG)-sum(defectB)))


Solve in Python:
Devu is a disastrous oracle: his predictions about various events of your life are horrifying. Instead of providing good luck, he "blesses" you with bad luck. The secret behind his wickedness is a hidden omen which is a string of length m. On your visit to him, you can ask a lot of questions about your future, each of which should be a string of length m. In total you asked him n such questions, denoted by strings s1, s2, ... , sn of length m each. Each of the question strings is composed of the characters 'a' and 'b' only.

Amount of bad luck this visit will bring you is equal to the length of longest common subsequence (LCS) of all the question strings and the hidden omen string. Of course, as the omen string is hidden, you are wondering what could be the least value of bad luck you can get.

Can you find out what could be the least bad luck you can get? Find it fast, before Devu tells you any bad omens.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
First line of each test case contains a single integer n denoting number of strings.
For each of next n lines, the ith line contains the string si.

-----Output-----
For each test case, output a single integer corresponding to the answer of the problem.

-----Constraints-----
- All the strings (including the hidden omen) contain the characters 'a' and 'b' only.

Subtask #1: (40 points)

- 1 ≤ T, n, m ≤ 14

Subtask #2: (60 points)

- 1 ≤ T, n, m ≤ 100

-----Example-----
Input:3
2
ab
ba
2
aa
bb
3
aabb
abab
baab

Output:1
0
2

-----Explanation-----
In the first example, the minimum value of LCS of all the strings is 1, the string by oracle can be one of these {aa, ab, ba, bb}.

In the second example, whatever string oracle has does not matter, LCS will always be zero.

t = eval(input())
for i in range(t):
 n = eval(input())
 d = {'a':1000,'b':1000}
 for j in range(n):
  str = input()
  d['a']= min(str.count('a'),d['a'])
  d['b']= min(str.count('b'),d['b'])
 print(min(d['a'],d['b']))


Solve in Python:
Devu loves to play with binary strings a lot. One day he borrowed a binary string s of size n from his friend Churu. Before starting to play with it, he wants to make sure that string does not contain more than  k consecutive equal characters. For achieving that, only kind of operation he is allowed to perform is to flip any ith character of the string.

As Devu is always in hurry to meet his girlfriend, he wants you to help him in finding out the minimum number of operations he will need. Also he wants you to print one of the possible modified string too.

-----Input-----
- First line of input contains an integer T denoting the number of test cases.
- For each test case, there are two lines.
- First line contains two space separated integers n, k as defined in the problem.
- Next line contains string s of size n.

-----Output-----
- For each test case, print two lines.
- First line should contain an integer corresponding to minimum number of operations Devu needs.
- In second line, print one of the possible modified strings.

-----Constraints-----
Subtask #1: 20 points
- 1 ≤ T ≤ 100, 1 ≤ n ≤ 20, 1 ≤ k ≤ n

Subtask #2: 35 points
- 1 ≤ T ≤ 102, 1 ≤ n ≤ 103, 1 ≤ k ≤ n

Subtask #3: 45 points
- 1 ≤ T ≤ 105, 1 ≤ n ≤ 105, 1 ≤ k ≤ n
- Sum of n over all the test cases is ≤ 106

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

Output:
1
10
0
11
2
1010

-----Explanation-----
Example case 1: As 1 is occurring twice consecutively, we can convert 11 to 10 in a single operation.
Example case 2: You don't need to modify the string as it does not have more than 2 equal consecutive character.
Example case 3: As 0 is occurring twice consecutively, we can convert 1001 to 1010 in a two operations (Flip third and fourth character).

T= int(input());

for i in range(T):
 n,k = list(map(int,input().split()));
 s=list(map(int,input()));

 if k==1:
  s_0 ={};
  s_1={};
  c0=0;
  c1=0;
  for j in range(n):
   if(j%2==0):
    s_1[j]=1;
    s_0[j]=0;
   else:
    s_1[j]=0;
    s_0[j]=1;
  for j in range(n):
   if(s_0[j]-s[j]!=0):
    c0+=1;
   if(s_1[j]-s[j]!=0):
    c1+=1;

  if c0<c1:
   print(c0);
   p_s="";
   for j in range(n):
    p_s+=str(s_0[j]);
   print(p_s);
  else:
   print(c1);
   p_s="";
   for j in range(n):
    p_s+=str(s_1[j]);
   print(p_s);

 else:
  count=1;
  c=s[0];
  flips=0
  for j in range(1,n):
   if(s[j]==c):
    count+=1;
    #print count;
    if count > k:
     if(j+1<n and s[j]==s[j+1]):
      if(s[j]==1):
       s[j]=0;
      else:
       s[j]=1;
     else:
      if(s[j-1]==1):
       s[j-1]=0;
      else:
       s[j-1]=1;
     flips+=1;
     count=1;

   elif(s[j]!=c):
    count=1;
   c=s[j];

  print(flips);
  p_s="";
  for j in range(n):
   p_s+=str(s[j]);
  print(p_s);


Solve in Python:
Devu loves to play with his dear mouse Jerry.  One day they play a game on 2 dimensional grid of dimensions n * n (n ≥ 2). Jerry is currently at coordinates (sx, sy) and wants to move to location (ex, ey) where cheese is placed by Devu. Also Devu is very cunning and has placed a bomb at location (bx, by). All these three locations are distinct.

In a single move, Jerry can go either up, down, left or right in the grid such that it never goes out of the grid. Also, it has to avoid the bomb. Find out minimum number of moves Jerry needs. It is guaranteed that it is always possible to do so.

-----Input-----
- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows."
- The first line of each test case contains seven space separated integers n, sx, sy , ex, ey, bx, by.

-----Output-----
- For each test case, output a single line containing an integer corresponding to minimum number of moves Jerry needs.

-----Constraints-----
- 1 ≤ T ≤ 1000
- 2 ≤ n ≤ 20
-  1 ≤ sx, sy , ex, ey, bx, by ≤ n
- No two or more poitns in the three points are same.

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

Output:
2
4

-----Explanation-----
Example case 1. ...
Jerry will move directly (1, 1) to (2, 1) and then to (2, 2) in total 2 moves.

Example case 2. ...

for cas in range(eval(input())):
 n, sx, sy, ex, ey, bx, by = list(map(int, input().strip().split()))
 print(abs(sx - ex) + abs(sy - ey) + 2 * ((sx == ex or sy == ey)
  and min(sx, ex) <= bx <= max(sx, ex)
  and min(sy, ey) <= by <= max(sy, ey)
 ))


Solve in Python:
Dexter, being irritated by DD, gave her a lucrative game to play to keep her busy.
There are $N$ bags numbered $1$ to $N$. The $i_{th}$ bag contains $A_i$ coins. The bags are placed in a circular order such that the $N_{th}$ bag is adjacent to the $1^{st}$ bag.
DD can select $K$ consecutive adjacent bags and take all the coins in them.   Help her find the maximum number of coins she can take by making the ideal choice.
Note that the selected bags must be consecutive. Since they are placed in circular order, bag number $1$ and $N$ are considered to be consecutive.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- First-line contains $N$ and $K$.
- Second-line contains $N$ numbers $A_1, A_2,...,A_N$,

-----Output:-----
For each test case, output in a single line, the maximum money that can be collected by DD.

-----Constraints-----
- $1 \leq T \leq 100$
- $5 \leq N \leq 10^5$
- $1 \leq K < N$
- $1 \leq A_i \leq 10^5$
Sum of $N$ over all test cases is less than $10^6$

-----Sample Input:-----
1
5 3
8 6 9 4 10

-----Sample Output:-----
24

-----EXPLANATION:-----
The ideal choice would be to take the last bag with $10$ coins and the first $2$ bags with $8$ and $6$ coins.

for i in range(int(input())):
    n , k = map(int,input().split())
    li = list(map(int,input().split()))
    s = 0
    s = sum(li[0:k])
    m = s
    for i in range(n-1):
        if(k + i >= n):
            s = s - li[i] + li[k + i - n]
        else:
            s = s - li[i] + li[k + i]
        if(s > m):
            m = s
    print(m)


Solve in Python:
Dhiraj loves Chocolates.He loves chocolates so much that he can eat up to $1000$ chocolates a day. But his mom is fed up by this habit of him and decides to take things in her hand.
Its diwali Season and Dhiraj has got a lot of boxes of chocolates and Dhiraj's mom is afraid that dhiraj might eat all boxes of chocolates.
So she told Dhiraj that he can eat only exactly $k$ number of chocolates and dhiraj has to finish all the chocolates in box selected by him and then move on to next box of chocolate.Now Dhiraj is confused that whether he will be able to eat $k$ number of chocolates or not. Since dhiraj is weak at maths,he asks for your help to tell him whether he can eat $k$ number of chocolates or not.
So given number of chocolates  are $k$ which dhiraj has to eat and the boxes of chocolates each containing some number of chocolates, tell whether dhiraj will be able to eat $k$ number of chocolates or not.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- $k$, representing the number of chocolates dhiraj has to eat.
- the third line contains $N$ representing the no. of boxes of chocolates.
- fourth line contains list of $a[]$ size $N$ specifying the number of chocolates in each Box.

-----Output:-----
- For each testcase, output in a single line answer $0$ or $1$.
- $0$ if dhiraj cant eat $k$ chocolates from given combination and $1$ if he can eat $k$ chocolates from given combination.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 10^7$
- $1 \leq  N \leq 800$
- $1 \leq a[i] \leq 10^3$

-----Sample Input:-----
2
20
5
8 7 2 10 5
11
4
6 8 2 10

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

def isSubsetSum(arr, n, sum):

    # The value of subset[i%2][j] will be true
    # if there exists a subset of sum j in
    # arr[0, 1, ...., i-1]
    subset = [ [False for j in range(sum + 1)] for i in range(3) ]

    for i in range(n + 1):
        for j in range(sum + 1):
            # A subset with sum 0 is always possible
            if (j == 0):
                subset[i % 2][j] = True

            # If there exists no element no sum
            # is possible
            elif (i == 0):
                subset[i % 2][j] = False
            elif (arr[i - 1] <= j):
                subset[i % 2][j] = subset[(i + 1) % 2][j - arr[i - 1]] or subset[(i + 1)
                                                                               % 2][j]
            else:
                subset[i % 2][j] = subset[(i + 1) % 2][j]

    return subset[n % 2][sum]

# Driver program to test above function
for _ in range(int(input())):
    k = int(input())
    n = int(input())
    a = list(map(int,input().split()))
    if sum(a) < k or k < min(a):
        print(0)
        continue
    if (isSubsetSum(a, n, k) == True):
	    print(1)
    else:
	    print(0)


Solve in Python:
Dhote and Shweta went on a tour by plane for the first time.Dhote was surprised by the conveyor belt  at the airport.As Shweta was getting bored Dhote had an idea of playing a game with her.He asked Shweta to count the number of bags whose individual weight is greater than or equal to the half of the total number of bags on the conveyor belt.Shweta got stuck in the puzzle! Help Shweta.

-----Input:-----
- First line will contain T$T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, one  integers N$N$.
- next line conatins N$N$ integers that represents weight of bag

-----Output:-----
For each testcase, print required answer in new line .

-----Constraints-----
- 1≤T≤1000$1 \leq T \leq 1000$
- 1≤N≤105$1 \leq N \leq 10^5$
- 1≤weightofbag≤105$ 1\leq  weight of bag   \leq 10^5$

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

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

T = int(input())
for i in range(T):
    N = int(input())
    S = input()
    S = S.split()
    cntr = 0
    for j in S:
        if(int(j)>=(N/2)):
            cntr+=1
    print(cntr)


Solve in Python:
Dhruvil has always been a studious person and will be completing his Engineering soon. He is always kneen about solving problems and is preparing hard for his next interview at Hackerrank. He has practiced lots of problems and now he came across this problem.
Given a message containing English letters(A-Z), it is being encoded to numbers using the following mapping:
'A' -> 1,'B' -> 2 ……………… 'Z' -> 26.
Now, given a non-empty string containing only digits, help Dhruvil determine the total number of ways to decode it.
While decoding you need to choose a substring of charachters and not a subsequence. Also a chosen substring should not contain any leading "0"s, but can contain trailing "0"s. Since the output can be very large print the answer as modulo 10^9 + 7 i.e 1000000007.

-----Input:-----
The first line of the input consists of single integer T, the number of test cases.
Each test case consists of a string.

-----Output:-----
For each test case print a single integer - the total number of ways to decode the digit string.

-----Constraints-----
- $1 \leq T \leq 1000$
- $2 \leq S \leq 10^9$

-----Sample Input:-----
2
12

226

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

3

-----EXPLANATION:-----
There are 2 possible ways. It could be decoded as "AB" {1,2} or "L" {12}.
There are 3 possible ways. It could be decoded as "BZ" {2,26}, "VF" {22,6}, or "BBF" {2,2,6}.


Solve in Python:
Diana is planning to make a very long journey. Her journey consists of $N$ bus routes, numbered from $1 to N$ in the order she must take them. The buses themselves are very fast but do not run often. The $i-th$ bus route only runs every $Xi$ days.

More specifically, she can only take the $i-th$ bus on day $Xi, 2Xi, 3Xi$, and so on. Since the buses are very fast, she can take multiple buses on the same day.

Diana must finish her journey by day D, but she would like to start the journey as late as possible. What is the latest day she could take the first bus, and still finish her journey by day $D$?
It is guaranteed that it is possible for Diana to finish her journey by day $D$.

-----Input:-----
The first line of the input gives the number of test cases, $T$. $T$ test cases follow. Each test case begins with a line containing the two integers N and D. Then, another line follows containing $N$ integers, the $i-th$ one is $Xi$.

-----Output:-----
For each test case, output one line containing an integer $Y$, where $Y$ is the latest day she could take the first bus, and still finish her journey by day $D$.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq Xi \leq D.$
- $1 \leq N \leq 1000.$
It is guaranteed that it is possible for Diana to finish her journey by day $D$.

-----Sample Input:-----
3

3 10

3 7 2

4 100

11 10 5 50

1 1

1

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

99

1

-----EXPLANATION:-----
In Sample $Case 1$, there are $N = 3$ bus routes and Bucket must arrive by day $D = 10$. She could:
- Take the 1st bus on day 6 $(X1 = 3)$,
- Take the 2nd bus on day 7 $(X2 = 7)$ and
- Take the 3rd bus on day 8 $(X3 = 2)$.
In Sample $Case 2$, there are $N = 4$ bus routes and Bucket must arrive by day $D = 100$. She could:
- Take the 1st bus on day 99 $(X1 = 11)$,
- Take the 2nd bus on day 100$ (X2 = 10)$,
- Take the 3rd bus on day 100 $(X3 = 5)$ and
- Take the 4th bus on day 100 $(X4 = 50)$,
In Sample Case 3, there is $N = 1$ bus route, and Bucket must arrive by day $D = 1$. She could:
- Take the 1st bus...

# cook your dish here
from sys import stdin,stdout,setrecursionlimit
from math import ceil

t = int(stdin.readline())
for _ in range(t):
    n,d = list(map(int,input().split()))
    a = list(map(int,input().split()))
    c = a[:]

    for i in range(n):
        q = d // a[i]
        a[i] *= q
    for i in range(n-1,0,-1):
        if a[i] - a[i-1] < 0:
            q = a[i] // c[i-1]
            a[i-1] = c[i-1] * q
        elif a[i] - a[i-1] > 1:
            q = a[i-1] // c[i]
            a[i] = c[i]*(q+1)

    print(a[0])


Solve in Python:
Did you hear about the Nibiru collision ? It is a supposed disastrous encounter between the earth and a large planetary object. Astronomers reject this idea. But why listen to other people's beliefs and opinions. We are coders above all, so what better way than to verify it by a small code. The earth and N asteroids are in the 2D plane. Each of them is initially located at some integer coordinates at time = 0 and is moving parallel to one of the X or Y axis with constant velocity of 1 unit per second.

Direction of movement is given as 'U' ( Up = towards positive Y ), 'D' ( Down = towards negative Y ), 'R' ( Right = towards positive X ), 'L' ( Left = towards negative X ). Given the initial position and the direction of movement of the earth and each of the N asteroids, find the earliest time at which the earth collides with one of the asteroids. If there can not be any collisions with the earth, print "SAFE" ( without quotes ). You can ignore the collisions between asteroids ( i.e., they continue to move in same direction even after collisions between them ).

-----Input-----

First line contains T, number of test cases. T cases follow. In each test case, first line contains XE YE DIRE, where (XE,YE) is the initial position of the Earth, DIRE is the direction in which it moves. Second line contains N, the number of
asteroids. N lines follow, each containing XA YA DIRA, the initial position and the direction of movement of each asteroid. No asteroid is initially located at (XE,YE)

-----Output-----

For each test case, output the earliest time at which the earth can collide with an asteroid (rounded to 1 position after decimal). If there can not be any collisions with the earth, print "SAFE" (without quotes).

-----Constraints-----

1 ≤ T ≤ 10

1 ≤ N ≤ 2012

-100 ≤ XE, YE, XA, YA ≤ 100

(XE,YE) != any of (XA,YA)

DIRE, DIRA is one of 'U', 'R', 'D', 'L'

-----Example-----
Input:
3
0 0 R
2
1 -2 U
2 2 D
1 1 U
1
1 0 U
0 0 R
1
3 0 L

Output:
2.0
SAFE
1.5

Explanation:

Case 1 :

Time 0 - Earth (0,0) Asteroids {...

#-*- coding:utf-8 -*-

import sys

# class Point:
#     def __init__(self, x, y):
#         self.x = x
#         self.y = y

#     def mul(self, k):
#         return Point(k * self.x, k * self.y)

#     def __add__(self, other):
#         return Point(self.x + other.x, self.y + other.y)

#     def __sub__(self, other):
#         return self + (-other)

#     def __neg__(self):
#         return Point(-self.x, -self.y)

#     def __eq__(self, other):
#         return self.x == other.x and self.y == other.y

#     def __getitem__(self, index):
#         return (self.x, self.y)[index]

#     def __str__(self):
#         return "(%d;%d)" % (self.x, self.y)

DIRS = dict(
 U=(0, 1),
 D=(0, -1),
 R=(1, 0),
 L=(-1, 0)
)
KOEF = 0.2

def div(a, b):
 return round(float(a) / b, 1)

# class Moving:
#     def __init__(self, x, y, dir):
#         self.p = Point(x, y)
#         self.dir = Point(*DIRS[dir.upper()])

#     def collide(self, other):
#         times = []
#         for coord in range(2):
#             d = abs(self.p[coord] - other.p[coord])
#             d2 = abs((self.p + self.dir.mul(KOEF) - other.p)[coord])
#             d3 = abs((other.p + other.dir.mul(KOEF) - self.p)[coord])
#             d_next = abs((self.p + self.dir.mul(KOEF) - (other.p + other.dir    .mul(KOEF)))[coord])
#             if d2 > d or d3 > d:
#                 return None

#             speed = abs(d_next - d)
#             if speed == 0:
#                 if self.p[coord] != other.p[coord]:
#                     return None
#                 continue
#             times.append( div(d, speed / KOEF) )

#         if len(times) == 2 and times[0] != times[1]:
#             return
#         return times[0]

def collide_coord(ex, edx, x, dx):
 d = abs(ex - x)
 d2 = abs(ex + edx - x)
 d3 = abs(ex - x - dx)
 if d2 > d or d3 > d:
  return False

 d_next = abs(ex + edx * KOEF - x - dx * KOEF)
 speed = abs(d_next - d)
 if speed == 0:
  if ex != x:
   return
  return "all" # all
 else:
  return div(d, speed / KOEF)

def main():
 t =...


Solve in Python:
Did you know that the people of America eat around 100 acres of pizza per day ? Having read this fact on internet, two chefs from the Elephant city, Arjuna and Bhima are set to make pizza popular in India. They organized a social awareness camp, where N people ( other than these two ) sit around a large pizza. To make it more interesting, they make some pairs among these N people and the two persons in a pair, feed each other.

Each person should be a part of at most one pair and most importantly, to make feeding easy, any two pairs should not cross each other ( see figure for more clarity ). Arjuna and Bhima decided to play a game on making the pairs. In his turn, a player makes a pair ( selects two persons, as long as its valid ) and this pair start feeding each other. Arjuna and Bhima take turns alternately, by making a pair in each turn, and they  play optimally ( see Notes for more clarity ). The one who can not make a pair in his turn, loses. Given N, find who wins the game, if Arjuna starts first.

-----Notes-----
- 'Optimally' means, if there is a possible move a person can take in his turn that can make him win finally, he will always take that. You can assume both are very intelligent.

-----Input-----
First line contains an integer T ( number of test cases, around 1000 ). Each of the next T lines contains an integer N ( 2 <= N <= 10000 )

-----Output-----
For each test case, output the name of the winner ( either "Arjuna" or "Bhima" ( without quotes ) ) in a new line.

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

Output:
Arjuna
Arjuna
Bhima
Arjuna

Explanation:

Let the people around the table are numbered 1, 2, ... , N in clock-wise order as shown in the image

Case 1 : N = 2. Only two persons and Arjuna makes the only possible pair (1,2)

Case 2 : N = 4. Arjuna can make the pair (1,3). Bhima can not make any more pairs ( without crossing the pair (1,3) )

Case 3 : N = 5. No matter which pair Arjuna makes first, Bhima can always make one more pair, and Arjuna can not make any further