Solve in Python:
Every day, Mike goes to his job by a bus, where he buys a ticket. On the ticket, there is a letter-code that can be represented as a string of upper-case Latin letters.
Mike believes that the day will be successful in case exactly two different letters in the code alternate.  Otherwise, he believes that the day will be unlucky. Please see note section for formal definition of alternating code.
You are given a ticket code. Please determine, whether the day will be successful for Mike or not. Print "YES" or "NO" (without quotes) corresponding to the situation.

-----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 and only line of each test case contains a single string S denoting the letter code on the ticket.

-----Output-----
For each test case, output a single line containing "YES" (without quotes) in case the day will be successful and "NO" otherwise.

-----Note-----
Two letters x, y where x != y are said to be alternating in a code, if code is of form "xyxyxy...".

-----Constraints-----

- 1 ≤ T ≤ 100
- S consists only of upper-case Latin letters

Subtask 1 (50 points):

- |S| = 2

Subtask 2 (50 points):

- 2 ≤ |S| ≤ 100

-----Example-----
Input:
2
ABABAB
ABC

Output:
YES
NO

t=int(input())
for i in range(t):
 s=input()
 l=set(s)
 if(len(l)==2):
  print("YES")
 else:
  print("NO")


Solve in Python:
Every email consists of a local name and a domain name, separated by the @ sign.
For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name.
Besides lowercase letters, these emails may contain '.'s or '+'s.
If you add periods ('.') between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name.  For example, "alice.z@leetcode.com" and "alicez@leetcode.com" forward to the same email address.  (Note that this rule does not apply for domain names.)
If you add a plus ('+') in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered, for example m.y+name@email.com will be forwarded to my@email.com.  (Again, this rule does not apply for domain names.)
It is possible to use both of these rules at the same time.
Given a list of emails, we send one email to each address in the list.  How many different addresses actually receive mails?

Example 1:
Input: ["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"]
Output: 2
Explanation: "testemail@leetcode.com" and "testemail@lee.tcode.com" actually receive mails

Note:

1 <= emails[i].length <= 100
1 <= emails.length <= 100
Each emails[i] contains exactly one '@' character.
All local and domain names are non-empty.
Local names do not start with a '+' character.

class Solution:
    def numUniqueEmails(self, emails: List[str]) -> int:
        tmp = set()
        for email in emails:
            local_name, domain_name = email.split('@')
            before_first_plus = local_name.split('+')[0]
            without_dot_list = before_first_plus.split('.')
            final_local_name = ''.join(without_dot_list)
            tmp.add(final_local_name + '@' + domain_name)
        return len(tmp)


Solve in Python:
Every great chef knows that lucky numbers are positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.

Our chef has recently returned from the Lucky country. He observed that every restaurant in the Lucky country had a lucky number as its name.
He believes that having a lucky number as a restaurant name can indeed turn out to be very lucky.

Our chef believes that it is possible to make a lucky number having N digits even luckier. Any number following the rules below is called Lucky lucky number -

1. The number contains only digits 4 and 7.

2. Count of digit 4 in the number should be divisible by 7.

3. Count of digit 7 in the number should be divisible by 4.

Help our chef to compute the count of digit 4 in the smallest Lucky lucky number having N digits.

-----Input-----

First line contains T, number of test cases. Each of the next T lines contains a number N, the number of digits in the Lucky lucky number to be formed.

1<=T<=1000

1<=N<=1000000000 (10^9)

-----Output-----

If it is not possible to form a Lucky lucky number having N digits, output -1.
Otherwise, output the count of digit 4 in the smallest Lucky lucky number having N digits.

-----Example-----
Input:
5
7
4
11
1
15

Output:
7
0
7
-1
7

Explanation
For the last test case, N = 15, the smallest lucky lucky number is
444444477777777. The count of digit 4 is 7.

#!/usr/bin/env python2
#-*- coding: utf-8 -*-

try:
    import psyco
    psyco.full()
except ImportError:
    pass

def main(n):
    sol = -1

    while (n >= 7 and sol < 0):
        if not (n % 7):
            sol = n
        n -= 4

    return sol

def __starting_point():
    T = int(input())

    for test in range(T):
        N = list(map(int, input().split()))[0]
        print(main(N))

__starting_point()


Solve in Python:
Every natural number, ```n```, may have a prime factorization like:

We define the **geometric derivative of n**, as a number with the following value:

For example: calculate the value of ```n*``` for ```n = 24500```.
```
24500 = 2²5³7²
n* = (2*2) * (3*5²) * (2*7) = 4200
```
Make a function, ```f``` that can perform this calculation
```
f(n) ----> n*
```
Every prime number will have ```n* = 1```.

Every number that does not have an exponent ```ki```, higher than 1, will give a ```n* = 1```, too

```python
f(24500) == 4200

f(997) == 1
```
Do your best!

from functools import reduce
def f(n):
    facts = factorization(n)
    return mul(power * prime ** (power - 1) for prime, power in facts)

def mul(ar):
    return reduce(lambda x,y:x*y, ar)

def factorization(n):
    result = []
    i = 2
    while i * i <= n:
        if n % i == 0:
            power = 0
            while n % i == 0:
                power += 1
                n /= i
            result.append((i, power))
        i += 1
    if n > 1: result.append((n, 1))
    return result


Solve in Python:
Every natural number, ```n```, may have a prime factorization like:

We define the arithmetic derivative of ```n```, ```n'``` the value of the expression:

Let's do the calculation for ```n = 231525```.
```
231525 = 3³5²7³
n' = (3*3²)*5²7³ + 3³*(2*5)*7³ + 3³*5²*(3*7²) = 231525 + 92610 + 99225 = 423360
```
We may make a chain of arithmetic derivatives, starting from a number we apply to the result the transformation and so on until we get the result ```1```.
```
n ---> n'  ---> (n')' ---> ((n')')' ---> ..... ---> ((...(n')...)')'
```
Let's do it starting with our number, ```n = 231525``` and making a chain of 5 terms:
```
231525 ---> 423360 ---> 1899072 ---> 7879680 ---> 51895296
```
We need a function ```chain_arith_deriv()``` that receives two arguments: ```start``` and ```k```, amount of terms of the chain.

The function should output the chain in an array format:
```
chain_arith_deriv(start, k) ---> [start, term1, term2, .....term(k-1)] # a total of k-terms
```
For the case presented above:
```python
chain_arith_deriv(231525, 5) == [231525, 423360, 1899072, 7879680, 51895296]
```
The function has to reject prime numbers giving an alerting message
```python
chain_arith_deriv(997, 5) == "997 is a prime number"
```
Features of the tests:
```
Number of Random Tests: 50
1000 ≤ start ≤ 99000000
3 ≤ k ≤ 15
```
Enjoy it and do your best!

def chain_arith_deriv(n, k):
    if len(prime_factors(n)) < 2:
        return "{} is a prime number".format(n)
    chain = [n]
    while k > 1:
        k, n = k-1, arith_deriv(n)
        chain.append(n)
    return chain

def arith_deriv(n):
    factors = prime_factors(n)
    return sum(n * factors.count(factor) // factor for factor in set(factors)) or 1

def prime_factors(n):
    if n < 2:
        return []
    factors = []
    for k in (2, 3):
        while n % k == 0:
            n //= k
            factors.append(k)
    k = 5
    step = 2
    while k * k <= n:
        if n % k:
            k += step
            step = 6 - step
        else:
            n //= k
            factors.append(k)
    if n > 1:
        factors.append(n)
    return factors


Solve in Python:
Every non-negative integer N has a binary representation.  For example, 5 can be represented as "101" in binary, 11 as "1011" in binary, and so on.  Note that except for N = 0, there are no leading zeroes in any binary representation.
The complement of a binary representation is the number in binary you get when changing every 1 to a 0 and 0 to a 1.  For example, the complement of "101" in binary is "010" in binary.
For a given number N in base-10, return the complement of it's binary representation as a base-10 integer.

Example 1:
Input: 5
Output: 2
Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.

Example 2:
Input: 7
Output: 0
Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10.

Example 3:
Input: 10
Output: 5
Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10.

Note:

0 <= N < 10^9
This question is the same as 476: https://leetcode.com/problems/number-complement/

class Solution:
    def bitwiseComplement(self, N: int) -> int:

        if N==0:
            return 1

        dummy_num=N

        n=0
        while(dummy_num):
            n+=1
            dummy_num>>=1

        ans=0

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

            if (N>>i)&1==0:
                ans|=(1<<i)

        return ans


Solve in Python:
Every now and then people in the office moves teams or departments. Depending what people are doing with their time they can become more or less boring. Time to assess the current team.

```if-not:java
You will be provided with an object(staff) containing the staff names as keys, and the department they work in as values.
```

```if:java
You will be provided with an array of `Person` objects with each instance containing the name and department for a staff member.
~~~java
public class Person {
  public final String name;        // name of the staff member
  public final String department;  // department they work in
}
~~~
```

Each department has a different boredom assessment score, as follows:

accounts = 1
finance = 2
canteen = 10
regulation = 3
trading = 6
change = 6
IS = 8
retail = 5
cleaning = 4
pissing about = 25

Depending on the cumulative score of the team, return the appropriate sentiment:

<=80: 'kill me now'
< 100 & > 80: 'i can handle this'
100 or over: 'party time!!'

The Office I - Outed
The Office III - Broken Photocopier
The Office IV - Find a Meeting Room
The Office V - Find a Chair

def boredom(staff):
    scores = {"accounts" : 1, "finance" : 2, "canteen" : 10,
              "regulation" : 3, "trading" : 6, "change" : 6,
              "IS" : 8, "retail" : 5, "cleaning" : 4, "pissing about" : 25}
    score = sum(scores[team] for team in staff.values())
    return "kill me now" if score <= 80 else "party time!!" if score >= 100 else "i can handle this"


Solve in Python:
Every number may be factored in prime factors.

For example, the number 18 may be factored by its prime factors ``` 2 ``` and ```3```
```
18 = 2 . 3 . 3 = 2 . 3²
```
The sum of the prime factors of 18 is  ```2 + 3 + 3 = 8```

But some numbers like 70 are divisible by the sum of its prime factors:
```
70 = 2 . 5 . 7 # sum of prime factors = 2 + 5 + 7 = 14
and 70 is a multiple of 14
```
Of course that primes would fulfill this property, but is obvious, because the prime decomposition of a number, is the number itself and every number is divisible by iself. That is why we will discard every prime number in the results

We are interested in collect the integer positive numbers (non primes) that have this property in a certain range ```[a, b]``` (inclusive).

Make the function ```mult_primefactor_sum()```, that receives the values ```a```, ```b``` as limits of the range ```[a, b]``` and ```a < b``` and outputs the sorted list of these numbers.

Let's see some cases:
```python
mult_primefactor_sum(10, 100) == [16, 27, 30, 60, 70, 72, 84]

mult_primefactor_sum(1, 60) == [1, 4, 16, 27, 30, 60]
```

def primes(n):
    primfac = []
    d = 2
    while d*d <= n:
        while (n % d) == 0:
            primfac.append(d)
            n //= d
        d += 1
    if n > 1:
       primfac.append(n)
    return primfac
def mult_primefactor_sum(a, b):
    l = []
    for i in range(a, b+1):
        factors = primes(i)
        if i>sum(factors) and not i%sum(factors):
            l.append(i)
    return l


Solve in Python:
Everybody is worried about Rakesh as the boy does not have much knowledge about the real world. He can not go from one place to another on his own. It's high time he learned to explore the city. He is going to a relative's house situated on the other side of the city on his own. As this is his first time, he is carrying a GPS tracker of a special kind. The tracker continuously sends information to the family of Rakesh about his movement. The information is sent using the following four letters: U, D, R, and L. Those letters indicate the moves taken by Rakesh.

The city can be considered as a grid. Rakesh starts his journey from (0, 0) position of the grid. His relative's house is situated at (Rx, Ry). Rakesh can move in four directions: up, down, right, or left indicated by U, D, R, and L respectively.

Any position of the city with x ordinate negative or greater than M is considered as dangerous. Also, any position of the city with y ordinate negative or greater than N is considered as dangerous. You will be given the total sequence of Rakesh's movement. You need to determine if Rakesh ended up being at his relative's house, at a dangerous place, or at a random place in the city.

To make things clear,

-  U indicates a move that increases position along y-axis by 1
-  D indicates a move that decreases position along y-axis by 1
-  R indicates a move that increases position along x-axis by 1
-  L indicates a move that decreases position along x-axis by 1

Note that we are interested in the position of Rakesh at the end of his journey only. He may visit some dangerous place or his relative's house at some intermediate point but that won't affect the answer.

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

- The first line of each test case contains two integers M and N.
- The second line contains two integers Rx and Ry.
- The third line contains the length of Rakesh's move sequence.
- The next line...

for i in range(int(input())):
 m, n = map(int, input().split())
 rx, ry = map(int, input().split())
 num = int(input())
 s = input()
 x = 0
 y = 0
 for j in s:
  if(j=='U'):
   y=y+1
  elif(j=='D'):
   y=y-1
  elif(j=='R'):
   x=x+1
  elif(j=='L'):
   x=x-1
 if x == rx and y == ry:
  print("Case "+str(i+1)+": REACHED")
 elif x != rx and y != ry and x > 0 and x <= m and y > 0 and y <= n:
  print("Case "+str(i+1)+": SOMEWHERE")
 elif x < 0 or x > m or y < 0 or y > n:
  print("Case "+str(i+1)+": DANGER")


Solve in Python:
Everybody know that you passed to much time awake during night time...

Your task here is to define how much coffee you need to stay awake after your night.
You will have to complete a function that take an array of events in arguments, according to this list you will return the number of coffee you need to stay awake during day time. **Note**: If the count exceed 3 please return 'You need extra sleep'.

The list of events can contain the following:

- You come here, to solve some kata ('cw').

- You have a dog or a cat that just decide to wake up too early ('dog' | 'cat').

- You just watch a movie ('movie').

- Other events can be present and it will be represent by arbitrary string, just ignore this one.

Each event can be downcase/lowercase, or uppercase. If it is downcase/lowercase you need 1 coffee by events and if it is uppercase you need 2 coffees.

def how_much_coffee(events):
    res=0
    for m in events:
        if m in ['cw','cat','dog','movie']:
            res+=1
        elif m in ['CW','DOG','MOVIE','CAT']:
            res+=2
    return (res if res <4 else 'You need extra sleep')


Solve in Python:
Everybody knows the classic ["half your age plus seven"](https://en.wikipedia.org/wiki/Age_disparity_in_sexual_relationships#The_.22half-your-age-plus-seven.22_rule) dating rule that a lot of people follow (including myself). It's the 'recommended' age range in which to date someone.

```minimum age <= your age <= maximum age```
#Task

Given an integer (1 <= n <= 100) representing a person's age, return their minimum and maximum age range.

This equation doesn't work when the age <= 14, so use this equation instead:
```
min = age - 0.10 * age
max = age + 0.10 * age
```
You should floor all your answers so that an integer is given instead of a float (which doesn't represent age). ```Return your answer in the form [min]-[max]```

##Examples:

```
age = 27   =>   20-40
age = 5    =>   4-5
age = 17   =>   15-20
```

def dating_range(age):
    if age <= 14:
        return f'{int(age - 0.1 * age)}-{int(age + 0.1 * age)}'
    return f'{age//2 + 7}-{(age-7)*2}'


Solve in Python:
Everybody loves **pi**, but what if **pi** were a square? Given a number of digits ```digits```, find the smallest integer whose square is greater or equal to the sum of the squares of the first ```digits``` digits of pi, including the ```3``` before the decimal point.

**Note:** Test cases will not extend beyond 100 digits; the first 100 digits of pi are pasted here for your convenience:
```
31415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679
```

## Examples

```
digits   = 1   #  [3]
expected = 3   #  sqrt(3^2) = 3

digits   = 3   #  [3, 1, 4]
expected = 6   #  sqrt(3^2 + 1^2 + 4^2) = 5.099 --> 6
```


Solve in Python:
Everybody seems to think that the Martians are green, but it turns out they are metallic pink and fat. Ajs has two bags of distinct nonnegative integers. The bags are disjoint, and the union of the sets of numbers in the bags is $\{0,1,…,M-1\}$, for some positive integer $M$. Ajs draws a number from the first bag and a number from the second bag, and then sums them modulo $M$.

What are the residues modulo $M$ that Ajs cannot obtain with this action?

-----Input-----

The first line contains two positive integer $N$ ($1 \leq N \leq 200\,000$) and $M$ ($N+1 \leq M \leq 10^{9}$), denoting the number of the elements in the first bag and the modulus, respectively.

The second line contains $N$ nonnegative integers $a_1,a_2,\ldots,a_N$ ($0 \leq a_1<a_2< \ldots< a_N<M$), the contents of the first bag.

-----Output-----

In the first line, output the cardinality $K$ of the set of residues modulo $M$ which Ajs cannot obtain.

In the second line of the output, print $K$ space-separated integers greater or equal than zero and less than $M$, which represent the residues Ajs cannot obtain. The outputs should be sorted in increasing order of magnitude. If $K$=0, do not output the second line.

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

Output
1
2

Input
4 1000000000
5 25 125 625

Output
0

Input
2 4
1 3

Output
2
0 2

-----Note-----

In the first sample, the first bag and the second bag contain $\{3,4\}$ and $\{0,1,2\}$, respectively. Ajs can obtain every residue modulo $5$ except the residue $2$: $ 4+1 \equiv 0, \, 4+2 \equiv 1, \, 3+0 \equiv 3, \, 3+1 \equiv 4 $ modulo $5$. One can check that there is no choice of elements from the first and the second bag which sum to $2$ modulo $5$.

In the second sample, the contents of the first bag are $\{5,25,125,625\}$, while the second bag contains all other nonnegative integers with at most $9$ decimal digits. Every residue modulo $1\,000\,000\,000$ can be obtained as a sum of an element in the first bag and an element in the second bag.

import sys
input = sys.stdin.readline

def main():
    n, m = map(int, input().split())
    a = list(map(int, input().split())) + [0]*500000
    ans_S = 0
    a[n] = a[0] + m
    s = [0]*600600
    for i in range(n):
        s[i] = a[i + 1] - a[i]
    s[n] = -1
    for i in range(n):
        s[2*n - i] = s[i]
    for i in range(2*n + 1, 3*n + 1):
        s[i] = s[i - n]
    l, r = 0, 0
    z = [0]*600600
    for i in range(1, 3*n + 1):
        if i < r:
            z[i] = z[i - l]
        while i + z[i] <= 3*n and (s[i + z[i]] == s[z[i]]):
            z[i] += 1
        if i + z[i] > r:
            l = i
            r = i + z[i]
    ans = []
    for i in range(n + 1, 2*n + 1):
        if z[i] < n:
            continue
        ans_S += 1
        ans.append((a[0] + a[2*n - i + 1]) % m)
    ans.sort()
    print(ans_S)
    print(*ans)
    return

def __starting_point():
    main()
__starting_point()


Solve in Python:
Everyday we go to different places to get our things done. Those places can be represented by specific location points `[ [, ], ... ]` on a map. I will be giving you an array of arrays that contain coordinates of the different places I had been on a particular day. Your task will be to find `peripheries (outermost edges)` of the bounding box that contains all the points. The response should only contain `Northwest and Southeast` points as follows: `{ "nw": [, ], "se": [ , ] }`. You are adviced to draw the points on a 2D plan to visualize:

```
                         N
                         ^
    p(nw)  ______________|________________
          |              |                |
          |              | all other      |
          |              |  points        |
          |              |                |
     ----------------------------------------> E
          |              |                |
          |  all other   |                |
          |  points      |                |
          |______________|________________|
                         |                  p(se)
```

def box(coords):
    a=min(i[0] for i in coords)
    b=max(i[0] for i in coords)
    c=min(i[1] for i in coords)
    d=max(i[1] for i in coords)
    return {'nw':[b,c], 'se':[a,d]}


Solve in Python:
Everyone Knows AdFly and their Sister Sites.

If we see the Page Source of an ad.fly site we can see this perticular line:
Believe it or not This is actually the Encoded url which you would skip to.

The Algorithm is as Follows:
```
1) The ysmm value is broken like this

ysmm   = 0 1 2 3 4 5 6 7 8 9  = "0123456789"
code1  = 0   2   4   6   8    = "02468"
code2  =   9   7   5   3   1  = "97531"

2) code1+code2 is base64 Decoded

3) The result will be of this form :
https://adf.ly/go.php?u=

4)  has to be further decoded and the result is to be returned
```

Your Task:

```
Make a function to Encode text to ysmm value.

and a function to Decode ysmm value.
```

Note: Take random values for The first 2 int values.
I personally hate trivial error checking like giving integer input in place of string.

```
Input For Decoder & Encoder: Strings
Return "Invalid" for invalid Strings
```

from base64 import b64decode, b64encode
from random import randint

def adFly_decoder(sc):
    return b64decode(b64decode(sc[::2] + sc[::-2])[26:]).decode('utf-8') or 'Invalid'

def adFly_encoder(url):
    url = f'{randint(0, 99):02d}https://adf.ly/go.php?u={url}'.encode('utf-8')
    encoded = b64encode(url[:26] + b64encode(url[26:])).decode('utf-8')
    length = len(encoded) // 2
    return ''.join(x + y for x, y in zip(encoded[:length], encoded[:length - 1:-1]))


Solve in Python:
Everyone knows passphrases. One can choose passphrases from poems, songs, movies names and so on but frequently
they can be guessed due to common cultural references.
You  can get your passphrases stronger by different means. One is the following:

choose a text in capital letters including or not digits and non alphabetic characters,

1. shift each letter by a given number but the transformed letter must be a letter (circular shift),
2. replace each digit by its complement to 9,
3. keep such as non alphabetic and non digit characters,
4. downcase each letter in odd position, upcase each letter in even position (the first character is in position 0),
5. reverse the whole result.

#Example:

your text: "BORN IN 2015!", shift 1

1 + 2 + 3 -> "CPSO JO 7984!"

4 "CpSo jO 7984!"

5 "!4897 Oj oSpC"

With longer passphrases it's better to have a small and easy program.
Would you write it?

https://en.wikipedia.org/wiki/Passphrase

from string import ascii_uppercase as letters, digits

def play_pass(s, n):
    return "".join(c.lower() if i & 1 else c
        for i, c in enumerate(s.upper().translate(
            str.maketrans(letters + digits, letters[n:] + letters[:n] + digits[::-1])
        )))[::-1]


Solve in Python:
Everyone loves short problem statements.
Given a function $ f(x) $ find its minimum value over the range $ 0 < x < π/2$
$
f(x) = ( x^2 + b*x + c ) / sin( x )
$

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, two real numbers $b, c$.

-----Output:-----
For each test case, output the minimum value of $ f(x) $ over the given range. Absolute error of $10^{-6}$ is allowed.

-----Constraints-----
- $1 \leq T \leq 100000$
- $1 \leq b,c \leq 20$

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

-----Sample Output:-----
5.8831725615

import math

def func(x,b,c):
 ans=x*x+b*x+c
 ans/=math.sin(x)
 return ans

for asd in range(int(input())):
 b,c=map(float,input().split())

 st=0
 en=math.pi/2
 iterations=0
 ans=func(en,b,c)
 while en-st>0.000001:
  if iterations>100:
   break

  x1=st+(en-st)/3
  x2=en-(en-st)/3
  fx1=func(x1,b,c)
  fx2=func(x2,b,c)
  if abs(fx2-fx1)<0.00000001:
   break
  ans=min(ans,min(fx1,fx2))
  if fx2<fx1:
   st=x1
  else:
   en=x2

  iterations+=1
 print("%.12f"%ans)


Solve in Python:
Evlampiy has found one more cool application to process photos. However the application has certain limitations.

Each photo i has a contrast v_{i}. In order for the processing to be truly of high quality, the application must receive at least k photos with contrasts which differ as little as possible.

Evlampiy already knows the contrast v_{i} for each of his n photos. Now he wants to split the photos into groups, so that each group contains at least k photos. As a result, each photo must belong to exactly one group.

He considers a processing time of the j-th group to be the difference between the maximum and minimum values of v_{i} in the group. Because of multithreading the processing time of a division into groups is the maximum processing time among all groups.

Split n photos into groups in a such way that the processing time of the division is the minimum possible, i.e. that the the maximum processing time over all groups as least as possible.

-----Input-----

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 3·10^5) — number of photos and minimum size of a group.

The second line contains n integers v_1, v_2, ..., v_{n} (1 ≤ v_{i} ≤ 10^9), where v_{i} is the contrast of the i-th photo.

-----Output-----

Print the minimal processing time of the division into groups.

-----Examples-----
Input
5 2
50 110 130 40 120

Output
20

Input
4 1
2 3 4 1

Output
0

-----Note-----

In the first example the photos should be split into 2 groups: [40, 50] and [110, 120, 130]. The processing time of the first group is 10, and the processing time of the second group is 20. Maximum among 10 and 20 is 20. It is impossible to split the photos into groups in a such way that the processing time of division is less than 20.

In the second example the photos should be split into four groups, each containing one photo. So the minimal possible processing time of a division is 0.

def f(m):
    nonlocal dp, sdp
    l = 0
    for i in range(n):
        while l < n and v[l] < v[i] - m:
            l += 1
        if l - 1 > i - k:
            dp[i] = False
        else:
            dp[i] = (sdp[i - k + 1] != sdp[l - 1])
        sdp[i + 1] = sdp[i] + (1 if dp[i] else 0)
    return dp[n - 1]

n, k = map(int, input().split())
dp = [False for i in range(n + 2)]
sdp = [0 for i in range(n + 2)]
dp[-1] = True
sdp[0] = 1
v = list(map(int, input().split()))
v.sort()
le = -1
r = v[-1] - v[0]
while r - le > 1:
    m = (r + le) // 2
    if f(m):
        r = m
    else:
        le = m
print(r)


Solve in Python:
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from $1$ to $n$. Each of its vertices also has an integer $a_i$ written on it. For each vertex $i$, Evlampiy calculated $c_i$ — the number of vertices $j$ in the subtree of vertex $i$, such that $a_j < a_i$. [Image]Illustration for the second example, the first integer is $a_i$ and the integer in parentheses is $c_i$

After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of $c_i$, but he completely forgot which integers $a_i$ were written on the vertices.

Help him to restore initial integers!

-----Input-----

The first line contains an integer $n$ $(1 \leq n \leq 2000)$ — the number of vertices in the tree.

The next $n$ lines contain descriptions of vertices: the $i$-th line contains two integers $p_i$ and $c_i$ ($0 \leq p_i \leq n$; $0 \leq c_i \leq n-1$), where $p_i$ is the parent of vertex $i$ or $0$ if vertex $i$ is root, and $c_i$ is the number of vertices $j$ in the subtree of vertex $i$, such that $a_j < a_i$.

It is guaranteed that the values of $p_i$ describe a rooted tree with $n$ vertices.

-----Output-----

If a solution exists, in the first line print "YES", and in the second line output $n$ integers $a_i$ $(1 \leq a_i \leq {10}^{9})$. If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all $a_i$ are between $1$ and $10^9$.

If there are no solutions, print "NO".

-----Examples-----
Input
3
2 0
0 2
2 0

Output
YES
1 2 1
Input
5
0 1
1 3
2 1
3 0
2 0

Output
YES
2 3 2 1 2

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

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

N = int(readline())
root = None
Edge = [[] for _ in range(N)]
Cr = [None]*N
for a in range(N):
    b, c = list(map(int, readline().split()))
    b -= 1
    if b == -1:
        root = a
    else:
        Edge[a].append(b)
        Edge[b].append(a)
    Cr[a] = c

P, L = parorder(Edge, root)

dp = [0]*N

for l in L[:0:-1]:
    p = P[l]
    dp[p] += 1+dp[l]

if any(d < c for d, c in zip(dp, Cr)):
    print('NO')
else:
    print('YES')
    A = [None]*N
    dp2 = [[] for _ in range(N)]
    for l in L[:0:-1]:
        p = P[l]
        dp2[l] = dp2[l][:Cr[l]] + [l] + dp2[l][Cr[l]:]
        dp2[p].extend(dp2[l])
    dp2[root] = dp2[root][:Cr[root]] + [root] + dp2[root][Cr[root]:]
    Ans = [None]*N
    for i in range(N):
        Ans[dp2[root][i]] = i+1
    print(' '.join(map(str, Ans)))


Solve in Python:
Failed Filter - Bug Fixing #3
Oh no, Timmy's filter doesn't seem to be working? Your task is to fix the FilterNumber function to remove all the numbers from the string.

def filter_numbers(st):
    return "".join(x for x in st if x not in '1234567890')


Solve in Python:
Failed Sort - Bug Fixing #4
Oh no, Timmy's Sort doesn't seem to be working? Your task is to fix the sortArray function to sort all numbers in ascending order

def sort_array(value):
    return "".join(sorted(value,key=lambda a: a))


Solve in Python:
Fans of The Wire will appreciate this one.
For those that haven't seen the show, the Barksdale Organization has a simple method for encoding telephone numbers exchanged via pagers: "Jump to the other side of the 5 on the keypad, and swap 5's and 0's."

Here's a keypad for visualization.
```
┌───┬───┬───┐
│ 1 │ 2 │ 3 │
├───┼───┼───┤
│ 4 │ 5 │ 6 │
├───┼───┼───┤
│ 7 │ 8 │ 9 │
└───┼───┼───┘
    │ 0 │
    └───┘
```

Detective, we're hot on their trail! We have a big pile of encoded messages here to use as evidence, but it would take way too long to decode by hand. Could you write a program to do this for us?

Write a funciton called decode(). Given an encoded string, return the actual phone number in string form. Don't worry about input validation, parenthesies, or hyphens.

def decode(string):
   return string.translate(string.maketrans("1234567890", "9876043215"))


Solve in Python:
Farmer Bob have a big farm, where he growths chickens, rabbits and cows. It is very difficult to count the number of animals for each type manually, so he diceded to buy a system to do it. But he bought a cheap system that can count only total number of heads, total number of legs and total number of horns of animals on the farm.
Help Bob to figure out how many chickens, rabbits and cows does he have?

All chickens have 2 legs, 1 head and no horns; all rabbits have 4 legs, 1 head and no horns; all cows have 4 legs, 1 head and 2 horns.

Your task is to write a function
```Python
get_animals_count(legs_number, heads_number, horns_number)
```
```Csharp
Dictionary get_animals_count(int legs_number, int heads_number, int horns_number)
```
, which returns a dictionary
```python
{"rabbits" : rabbits_count, "chickens" : chickens_count, "cows" : cows_count}
```
```Csharp
new Dictionary(){{"rabbits", rabbits_count},{"chickens", chickens_count},{"cows", cows_count}}
```

Parameters `legs_number, heads_number, horns_number` are integer, all tests have valid input.

Example:

```python
get_animals_count(34, 11, 6); # Should return {"rabbits" : 3, "chickens" : 5, "cows" : 3}
get_animals_count(154, 42, 10); # Should return {"rabbits" : 30, "chickens" : 7, "cows" : 5}
```

```Csharp
get_animals_count(34, 11, 6); //Should return  Dictionary(){{"rabbits", 3},{"chickens", 5},{"cows", 3}}
get_animals_count(154, 42, 10); //Should return Dictionary(){{"rabbits", 30},{"chickens", 7},{"cows", 5}}
```

def get_animals_count(legs, heads, horns):
    cows = horns // 2
    rabbits = (legs - 4 * cows) // 2 - (heads - cows)
    chickens = heads - cows - rabbits
    return {"rabbits": rabbits, "chickens": chickens, "cows": cows}


Solve in Python:
Farmer Feb has three fields with potatoes planted in them. He harvested x potatoes from the first field, y potatoes from the second field and is yet to harvest potatoes from the third field. Feb is very superstitious and believes that if the sum of potatoes he harvests from the three fields is a prime number (http://en.wikipedia.org/wiki/Prime_number), he'll make a huge profit. Please help him by calculating for him the minimum number of potatoes that if harvested from the third field will make the sum of potatoes prime. At least one potato should be harvested from the third field.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. Each of the next T lines contain 2 integers separated by single space: x and y.

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

-----Constraints-----
- 1 ≤ T ≤ 1000
- 1 ≤ x ≤ 1000
- 1 ≤ y ≤ 1000

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

Output:
1
4

-----Explanation-----

In example case 1: the farmer harvested a potato from the first field and 3 potatoes from the second field. The sum is 4. If he is able to harvest a potato from the third field, that will make the sum 5, which is prime. Hence the answer is 1(he needs one more potato to make the sum of harvested potatoes prime.)

# cook your dish here
def prime(n):
 for i in range(2,(n//2)+1):
  if(n%i ==0):
   return("no")
   break
 else:
  return("yes")
for i in range(int(input())):
 a,b=map(int,input().split())
 x=a+b+1
 while(1):
  if(prime(x)=="yes"):
   ans=x
   break
  else:
   x+=1
 print(x-(a+b))


Solve in Python:
Farmer John has just given the cows a program to play with! The program contains two integer variables, x and y, and performs the following operations on a sequence a_1, a_2, ..., a_{n} of positive integers:  Initially, x = 1 and y = 0. If, after any step, x ≤ 0 or x > n, the program immediately terminates.  The program increases both x and y by a value equal to a_{x} simultaneously.  The program now increases y by a_{x} while decreasing x by a_{x}.  The program executes steps 2 and 3 (first step 2, then step 3) repeatedly until it terminates (it may never terminate). So, the sequence of executed steps may start with: step 2, step 3, step 2, step 3, step 2 and so on.

The cows are not very good at arithmetic though, and they want to see how the program works. Please help them!

You are given the sequence a_2, a_3, ..., a_{n}. Suppose for each i (1 ≤ i ≤ n - 1) we run the program on the sequence i, a_2, a_3, ..., a_{n}. For each such run output the final value of y if the program terminates or -1 if it does not terminate.

-----Input-----

The first line contains a single integer, n (2 ≤ n ≤ 2·10^5). The next line contains n - 1 space separated integers, a_2, a_3, ..., a_{n} (1 ≤ a_{i} ≤ 10^9).

-----Output-----

Output n - 1 lines. On the i-th line, print the requested value when the program is run on the sequence i, a_2, a_3, ...a_{n}.

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

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

Output
3
6
8

Input
3
1 2

Output
-1
-1

-----Note-----

In the first sample   For i = 1,  x becomes $1 \rightarrow 2 \rightarrow 0$ and y becomes 1 + 2 = 3.  For i = 2,  x becomes $1 \rightarrow 3 \rightarrow - 1$ and y becomes 2 + 4 = 6.  For i = 3,  x becomes $1 \rightarrow 4 \rightarrow 3 \rightarrow 7$ and y becomes 3 + 1 + 4 = 8.

n = int(input())
t = [0, 0]
t += list(map(int, input().split()))
n += 1
a = [0] * n
b = [0] * n
n -= 1
a[1] = b[1] = -1

#print(t, a, b)

def calc(s, a, b, l):
	nonlocal t
	l.reverse()
	j = 0
	n = len(l)

	while True:
		s += t[l[j]]
		a[l[j]] = s
		j += 1
		if j == n:
			return

		s += t[l[j]]
		b[l[j]] = s
		j += 1
		if j == n:
			return

def calc2(i, k):
	nonlocal a, b
	l = []
	if k:
		a[i] = -1
		l.append(i)
		i += t[i]

	while True:
		if i > n:
			return calc(0, a, b, l)
		if b[i] > 0:
			return calc(b[i], a, b, l)
		if b[i] == -1:
			return
		b[i] = -1
		l.append(i)
		i -= t[i]
		if i < 1:
			return calc(0, b, a, l)
		if a[i] > 0:
			return calc(a[i], b, a, l)
		if a[i] == -1:
			return
		a[i] -= 1
		l.append(i)
		i += t[i]

for i in range(2, n + 1):
	if a[i] == 0:
		calc2(i, True)
	if b[i] == 0:
		calc2(i, False)

for i in range(1, n):
	if b[i + 1] > 0:
		t[i] = i + b[i + 1]
	else:
		t[i] = -1

#print(t, a, b)

print('\n'.join(map(str, t[1:n])))


Solve in Python:
Fast & Furious Driving School's (F&F) charges for lessons are as below:

Time
Cost

Up to 1st hour
$30

Every subsequent half hour**
$10

** Subsequent charges are calculated by rounding up to nearest half hour.

For example, if student X has a lesson for 1hr 20 minutes, he will be charged $40 (30+10) for 1 hr 30 mins and if he has a lesson for 5 minutes, he will be charged $30 for the full hour.

Out of the kindness of its heart, F&F also provides a 5 minutes grace period. So, if student X were to have a lesson for 65 minutes or 1 hr 35 mins, he will only have to pay for an hour or 1hr 30 minutes respectively.

For a given lesson time in minutes (min) , write a function price to calculate how much the lesson costs.

import math
def cost(mins):

    if mins <= 60:
        return 30

    if mins > 60:
        if (mins % 30) <= 5:
            leftover = mins - 60
            multiple = round(leftover / 30)
            return 30 + (10 * (multiple))

        if (mins % 30) > 5:
            leftover = mins - 60
            multiple = math.ceil(leftover/30)
            return 30 + (10 * multiple)


Solve in Python:
Fennec and Snuke are playing a board game.
On the board, there are N cells numbered 1 through N, and N-1 roads, each connecting two cells. Cell a_i is adjacent to Cell b_i through the i-th road. Every cell can be reached from every other cell by repeatedly traveling to an adjacent cell. In terms of graph theory, the graph formed by the cells and the roads is a tree.
Initially, Cell 1 is painted black, and Cell N is painted white. The other cells are not yet colored.
Fennec (who goes first) and Snuke (who goes second) alternately paint an uncolored cell.
More specifically, each player performs the following action in her/his turn:
 - Fennec: selects an uncolored cell that is adjacent to a black cell, and paints it black.
 - Snuke: selects an uncolored cell that is adjacent to a white cell, and paints it white.
A player loses when she/he cannot paint a cell. Determine the winner of the game when Fennec and Snuke play optimally.

-----Constraints-----
 - 2 \leq N \leq 10^5
 - 1 \leq a_i, b_i \leq N
 - The given graph is a tree.

-----Input-----
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}

-----Output-----
If Fennec wins, print Fennec; if Snuke wins, print Snuke.

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

-----Sample Output-----
Fennec

For example, if Fennec first paints Cell 2 black, she will win regardless of Snuke's moves.

from networkx import*
(N,),*t=map(str.split,open(0))
s=shortest_path_length
x=s(G:=Graph(t),'1')
y=s(G,N)
print('FSennunkeec'[sum(x[k]>y[k]for k in x)*2>=int(N)::2])


Solve in Python:
Fibonacci numbers are generated by setting F0 = 0, F1 = 1, and then using the formula:

# Fn = Fn-1 + Fn-2

Your task is to efficiently calculate the **n**th element in the Fibonacci sequence and then count the occurrence of each digit in the number. Return a list of integer pairs sorted in **descending** order.

10 ≤ n ≤ 100000

## Examples
```
f(10) = 55  # returns [(2, 5)], as there are two occurances of digit 5

f(10000)    # returns:
  [(254, 3),
   (228, 2),
   (217, 6),
   (217, 0),
   (202, 5),
   (199, 1),
   (198, 7),
   (197, 8),
   (194, 4),
   (184, 9)]
```
If two integers have the same count, sort them in descending order.

Your algorithm must be efficient.

~~~if:javascript
Solving this Kata in Javascript requires the use of the bignumber.js library. I have included starter code to assist you with using the library. Thanks to `kazk` for assisting with the translation.
~~~

def fib(n1):
    fn_1=1
    fn_2=0
    f=0
    for i in range(1,n1):
        f=fn_1+fn_2
        fn_2=fn_1
        fn_1=f
    return f

def fib_digits(n):
    check=0
    num=''
    l=[]
    count=0
    x=str(fib(int(n)))
    while len(x)>1:
        for j in range(len(x)):
            if x[0]==x[j]:
                count+=1
        num+=x[0]
        l.append((count,int(x[0])))
        count=0
        x=x.replace(x[0],"")
    l.sort()
    return(l[::-1])


Solve in Python:
Final kata of the series (highly recommended to compute [layers](https://www.codewars.com/kata/progressive-spiral-number-position/) and [branch](https://www.codewars.com/kata/progressive-spiral-number-branch/) first to get a good idea), this is a blatant ripoff of [the one offered on AoC](http://adventofcode.com/2017/day/3).

Given a number, return the Manhattan distance considering the core of the spiral (the `1` cell) as 0 and counting each step up, right, down or left to reach a given cell.

For example, using our beloved 5x5 square:

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

And thus your code should behave like this:

```python
distance(1) == 0
distance(5) == 2
distance(25) == 4
distance(30) == 5
distance(50) == 7
```

Just be ready for larger numbers, as usual always positive.

*[Dedicated to [swiftest learner I met in a long while](https://www.codewars.com/users/irbekrm/)]*

from math import *

def distance(n):
    k=ceil((sqrt(n)-1)/2)
    t=2*k+1
    m=t**2
    t=t-1
    if n>=m-t:
        x = k-(m-n),-k
        return sum(map(abs,x))
    m -= t
    if n>=m-t:
        x = -k,-k+(m-n)
        return sum(map(abs,x))
    m -= t
    if n>=m-t:
        x =  -k+(m-n),k
        return sum(map(abs,x))
    x = k,k-(m-n-t)
    return sum(map(abs,x))


Solve in Python:
Finally the clowns of Synapse have decided to take their site online. The convener of the clowns has heard from somewhere that knowing URI's is very important for their website, so kindly help him with this task.

Uniform Resource Identifiers (or URIs) are strings like
http://synapse.daiict.ac.in/codemutants/, mailto:clown_convener@synapse.daiict.ac.in,
ftp://10.100.93.93/night_halters, or even just output.txt that are
used to identify a resource, usually on the Internet or a local computer.
Certain characters are reserved within URIs, and if a reserved character is
part of an identifier then it must be percent-encoded by
replacing it with a percent sign followed by two hexadecimal digits
representing the ASCII code of the character. A table of seven reserved
characters and their encodings is shown below. Your job is to write a
program that can percent-encode a string of characters.CharacterEncoding" " (space)%20"!" (exclamation point)%21"$" (dollar sign)%24"%" (percent sign)%25"(" (left parenthesis)%28")" (right parenthesis)%29"*" (asterisk)%2a
Input: The input consists of one or more strings, each
1–79 characters long and on a line by itself, followed by a line
containing only "#" that signals the end of the input. The character "#" is
used only as an end-of-input marker and will not appear anywhere else in the
input. A string may contain spaces, but not at the beginning or end of the
string, and there will never be two or more consecutive spaces.
Output: For each input string, replace every occurrence of a
reserved character in the table above by its percent-encoding, exactly as
shown, and output the resulting string on a line by itself. Note that the
percent-encoding for an asterisk is %2a (with a lowercase "a") rather than
%2A (with an uppercase "A").

-----Example-----
Input:
Happy Joy Joy!
http://synapse.daiict.ac.in/
plain_vanilla
(**)
?
the 7% solution
#

Output:
Happy%20Joy%20Joy%21
http://synapse.daiict.ac.in/
plain_vanilla
%28%2a%2a%29
?
the%207%25%20solution

import sys
def main():
    s = sys.stdin.readline
    save = {' ': '%20', '!': '%21', '$': '%24', '%': '%25', '(': '%28', ')': '%29', '*': '%2a'}
    string = s().strip()
    while True:
        output = []
        if '#' in string:
            return
        for i in string:
            if i in save:
                output.append(save[i])
            else:
                output.append(i)
        print(''.join(output))
        string = s().strip()

def __starting_point():
    main()
__starting_point()


Solve in Python:
Finally, a COVID vaccine is out on the market and the Chefland government has asked you to form a plan to distribute it to the public as soon as possible. There are a total of $N$ people with ages $a_1, a_2, \ldots, a_N$.
There is only one hospital where vaccination is done and it is only possible to vaccinate up to $D$ people per day. Anyone whose age is $\ge 80$ or $\le 9$ is considered to be at risk. On each day, you may not vaccinate both a person who is at risk and a person who is not at risk. Find the smallest number of days needed to vaccinate everyone.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains two space-separated integers $N$ and $D$.
- The second line contains $N$ space-separated integers $a_1, a_2, \ldots, a_N$.

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

-----Constraints-----
- $1 \le T \le 10$
- $1 \le N \le 10^4$
- $1 \le D \le 10^5$
- $1 \le a_i \le 100$ for each valid $i$

-----Subtasks-----
Subtask #1 (100 points): original constraints

-----Example Input-----
2
10 1
10 20 30 40 50 60 90 80 100 1
5 2
9 80 27 72 79

-----Example Output-----
10
3

-----Explanation-----
Example case 1: We do not need to worry about how the people are grouped, since only one person can be vaccinated in a single day. We require as many days as there are people.
Example case 2: There are two people at risk and three people who are not at risk. One optimal strategy is to vaccinate the two people at risk on day $1$ and the remaining three on the next $2$ days.

# cook your dish here
import math

for _ in range(int(input())):
 n,d=list(map(int,input().split(' ')))
 l= list(map(int, input().split(' ')))
 l1=[]
 l2=[]

 for i in l:
  if i>=80 or i<=9:
   l1.append(i)
  else:
   l2.append(i)

 x=math.ceil(len(l1)/d)
 y=math.ceil(len(l2)/d)

 print(x+y)

# 2
# 10 1
# 10 20 30 40 50 60 90 80 100 1
# 5 2
# 9 80 27 72 79
# Example Output
# 10
# 3


Solve in Python:
Finally, the pandemic is over in ChefLand, and the chef is visiting the school again. Chef likes to climb the stairs of his school's floor by skipping one step, sometimes chef climbs the stairs one by one. Simply, the chef can take one or 2 steps in one upward movement. There are N stairs between ground and next floor. The chef is on the ground floor and he wants to go to the next floor with Cheffina but, Cheffina asks chef in how many ways, the chef can reach the next floor normally or any combination of skipping one step, where order doesn't matter.

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

-----Output:-----
For each test case, output in a single line answer as the number of ways.

-----Constraints-----
- $1 \leq T \leq 1000$
- $1 \leq N \leq 10^5$

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

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

-----EXPLANATION:-----
ways: [1,1,1], here chef climb to the next floor, one by one stair.
[1,2], here chef climb to the next floor, one step first and after that 2 stairs at once.
Note, [2,1] consider the same as that of [1,2] hence ignored.

# cook your dish here
for _ in range(int(input())):
    n=int(input())
    print((n//2)+1)


Solve in Python:
Find out the maximum sub-array of non negative numbers from an array.

The sub-array should be continuous. That is, a sub-array created by choosing the second and fourth element and skipping the third element is invalid.

Maximum sub-array is defined in terms of the sum of the elements in the sub-array. Sub-array A is greater than sub-array B if sum(A) > sum(B).

NOTE 1 :If there is a tie, then compare with segment's length and return segment which has maximum length

NOTE 2: If there is still a tie, then return the segment with minimum starting index.

-----Input-----

The first line contains the number of test cases. Each test cases contains an integer N. next line consists of N integers, the elements of the array.

-----Output-----

Print out the maximum sub-array as stated above.

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

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

1
6
1 2 5 -7 2 3

Output:

1 2 5

for t in range(int(input())):
 n=int(input())
 a=list(map(int,input().split()))
 s=0
 l=[]
 for i in range(n):
  if (a[i]<0):
   e=i
   ss=sum(a[s:e])
   l.append((ss,e-s,n-s))
   s=i+1
 e=n
 ss=sum(a[s:e])
 l.append((ss,e-s,n-s))
 x=max(l)
 s=n-x[2]
 e=x[1]+s
 for i in range(s,e):
  print(a[i], end=' ')
 print("")


Solve in Python:
Find sum of all the numbers that are multiples of 10 and are less than or equal to a given number "N". (quotes for clarity and be careful of integer overflow)

-----Input-----
Input will start with an integer T the count of test cases, each case will have an integer N.

-----Output-----
Output each values, on a newline.

-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ N ≤1000000000

-----Example-----
Input:
1
10

Output:
10

-----Explanation-----
Example case 1. Only integer that is multiple 10 that is less than or equal to 10 is 10

t = int(input())
l = list()

for i in range(t):
 n = int(input()) / 10
 l.append(n)

for n in l:
 print(int(n * (n + 1) / 2.0 * 10))


Solve in Python:
Find the 2nd largest integer in array
If the array has no 2nd largest integer then return nil.
Reject all non integers elements and then find the 2nd largest integer in array

find_2nd_largest([1,2,3]) => 2

find_2nd_largest([1,1,1,1,1]) => nil
because all elements are same. Largest no. is 1. and there is no 2nd largest no.

find_2nd_largest([1,'a','2',3,3,4,5,'b']) => 4
as after rejecting non integers array will be [1,3,3,4,5]
Largest no. is 5. and 2nd largest is 4.

Return nil if there is no 2nd largest integer.
Take care of big numbers as well

def find_2nd_largest(arr):
    return next(iter(sorted(n for n in set(arr) if type(n) == int)[-2:-1]), None)


Solve in Python:
Find the area of a rectangle when provided with one diagonal and one side of the rectangle. If the input diagonal is less than or equal to the length of the side, return "Not a rectangle". If the resultant area has decimals round it to two places.

`This kata is meant for beginners. Rank and upvote to bring it out of beta!`

def area(d, l):
    return "Not a rectangle" if d<=l else round( l*(d*d-l*l)**.5, 2)


Solve in Python:
Find the closest prime number under a certain integer ```n``` that has the maximum possible amount of even digits.

For ```n = 1000```, the highest prime under ```1000``` is ```887```, having two even digits (8 twice)

Naming ```f()```, the function that gives that prime, the above case and others will be like the following below.
```
f(1000) ---> 887 (even digits: 8, 8)

f(1210) ---> 1201 (even digits: 2, 0)

f(10000) ---> 8887

f(500) ---> 487

f(487) ---> 467
```
Features of the random tests:
```
Number of tests = 28
1000 <= n <= 5000000
```

Enjoy it!!

from bisect import bisect_left as bisect

n = 5000000
sieve, PED, PED_DATA = [0]*((n>>1)+1), [], []
for i in range(3, n+1, 2):
    if not sieve[i>>1]:
        for j in range(i**2>>1, (n+1)>>1, i): sieve[j] = 1
        s = str(i)
        nEveD = sum(s.count(d) for d in "02468")
        if nEveD:
            PED.append(i)
            PED_DATA.append( (nEveD,len(s)-1) )

def f(n):
    idx = bisect(PED, n)-1
    m, (nEveD, l) = PED[idx], PED_DATA[idx]

    for c in range(idx):
        mc, (nEveDc, lc) = PED[idx-c], PED_DATA[idx-c]
        if nEveDc > nEveD:
            m, nEveD = mc, nEveDc
        if lc < nEveD: break
    return m


Solve in Python:
Find the difference between two collections. The difference means that either the character is present in one collection or it is present in other, but not in both. Return a sorted set with difference.

The collections can contain any character and can contain duplicates.

For instance:

A = [a,a,t,e,f,i,j]

B = [t,g,g,i,k,f]

difference = [a,e,g,j,k]

diff=lambda a,b: sorted(set([e for e in a if e not in b]+[e for e in b if e not in a]))


Solve in Python:
Find the first character that repeats in a String and return that character.

```python
first_dup('tweet') => 't'
first_dup('like') => None
```

*This is not the same as finding the character that repeats first.*
*In that case, an input of 'tweet' would yield 'e'.*

def first_dup(text):
    for t in text:
        if text.count(t) > 1:
            return t


Solve in Python:
Find the greatest common divisor of two positive integers. The integers can be large, so you need to find a clever solution.

The inputs `x` and `y` are always greater or equal to 1, so the greatest common divisor will always be an integer that is also greater or equal to 1.

def mygcd(x,y):
    if x == 0:
        return y
    if y == 0:
        return x
    else:
        return mygcd(y, x%y)


Solve in Python:
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Example 1:

Input: [3,2,1,5,6,4] and k = 2
Output: 5

Example 2:

Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4

Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.

class Solution:
     def findKthLargest(self, nums, k):
         """
         :type nums: List[int]
         :type k: int
         :rtype: int
         """
         return sorted(nums)[len(nums) - k]


Solve in Python:
Find the largest palindrome made from the product of two n-digit numbers.
 Since the result could be very large, you should return the largest palindrome mod 1337.

Example:
Input: 2
Output: 987
Explanation: 99 x 91 = 9009, 9009 % 1337 = 987

Note:
The range of n is [1,8].

class Solution:
     def largestPalindrome(self, n):
         """
         :type n: int
         :rtype: int
         """
         A = [0,9,987,123,597,677,1218,877,475]
         return A[n]


Solve in Python:
Find the last element of the given argument(s).

## Examples

```python
last([1, 2, 3, 4]) ==>  4
last("xyz")        ==> "z"
last(1, 2, 3, 4)   ==>  4
```
In **javascript** and **CoffeeScript** a **list** will be an `array`, a `string` or the list of `arguments`.

(courtesy of [haskell.org](http://www.haskell.org/haskellwiki/99_questions/1_to_10))

def last(*args):
    last = args[-1]
    try:
        return last[-1]
    except TypeError:
        return last


Solve in Python:
Find the length between 2 co-ordinates.  The co-ordinates are made of integers between -20 and 20 and will be given in the form of a 2D array:

(0,0) and (5,-7) would be [ [ 0 , 0 ] , [ 5, -7 ] ]

The function must return the answer rounded to 2 decimal places in the form of a string.

```python
length_of_line([[0, 0], [5, -7]]) => "8.60"
```

If the 2 given co-ordinates are the same, the returned length should be "0.00"

from math import hypot

def length_of_line(array):
    (a, b), (c, d) = array
    return f"{hypot(a-c, b-d):.2f}"


Solve in Python:
Find the length of the longest contiguous segment in an array, in which if a given element $K$ is inserted, $K$ becomes the second largest element of that subarray.

-----Input:-----
- The first line will contain $T$, number of test cases. Then the test cases follow.
- The first line of each test case contains two integers $N$ and $K$.
- The next line contains N space-separated integers Ai denoting the elements of the array.

-----Output:-----
Print a single line corresponding to each test case — the length of the largest segment.

-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq N \leq 10^6$
- $1 \leq Ai, K \leq 10^9$
- Sum of N across all test cases doesn't exceed $10^6$

-----Sample Input:-----
2
5 3
2 4 2 4 2
8 5
9 3 5 7 8 11 17 2

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

-----EXPLANATION:-----
If 3 is inserted at anywhere in the array, it is the second largest element. Hence the maximum length is 5.
If 5 is inserted anywhere between 1st and 4th element, it is the second largest element. The length of such subarray is 3.

# cook your dish here
t=int(input())
while t:
 a=input().split()
 n=int(a[0])
 k=int(a[1])
 lst=input().split()
 for i in range(n):
  lst[i] = int(lst[i])
 greater = 0
 length=0
 pos = -1
 allTimeLong=0
 for i in range(n):
  if lst[i]>k and greater!=0 and lst[i]!=greater:
   greater = lst[i]
   if allTimeLong<length:
    allTimeLong=length
   length = i - pos
   pos=i
   continue
  elif lst[i]>k:
   greater = lst[i]
   pos=i
  length+=1
 if allTimeLong<length:
  allTimeLong=length
 t-=1
 print(allTimeLong)


Solve in Python:
Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every character in T appears no less than k times.

Example 1:

Input:
s = "aaabb", k = 3

Output:
3

The longest substring is "aaa", as 'a' is repeated 3 times.

Example 2:

Input:
s = "ababbc", k = 2

Output:
5

The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.

class Solution:
     def longestSubstring(self, s, k):
         """
         :type s: str
         :type k: int
         :rtype: int
         """
         # str.count is much faster than collections.Counter under certain conditions
         # collections.Counter is intended to be a general tool
         # while str.count is much optimized C code to do just one thing
         # (Counter in Py3 is written in C too)
         # see this SO question:
         # https://stackoverflow.com/questions/41594940/why-is-collections-counter-so-slow
         for c in set(s):
             if s.count(c) < k:
                 return max(self.longestSubstring(sub, k) for sub in s.split(c))
         return len(s)


Solve in Python:
Find the longest substring in alphabetical order.

Example: the longest alphabetical substring in `"asdfaaaabbbbcttavvfffffdf"` is `"aaaabbbbctt"`.

There are tests with strings up to `10 000` characters long so your code will need to be efficient.

The input will only consist of lowercase characters and will be at least one letter long.

If there are multiple solutions, return the one that appears first.

Good luck :)

def longest(s):

    result = []
    ordx = 0

    for i in s:
        if ord(i) >= ordx:
            ordx = ord(i)
            result.append(i)
        else:
            result.append('|')
            result.append(i)

            ordx = ord(i)

    return max(("").join(result).split("|"), key=len)


Solve in Python:
Find the longest substring within a string that contains at most 2 unique characters.

```
substring("a") => "a"
substring("aaa") => "aaa"
substring("abacd") => "aba"
substring("abacddcd") => "cddcd"
substring("cefageaacceaccacca") => "accacca"
```

This function will take alphanumeric characters as input.

In cases where there could be more than one correct answer, the first string occurrence should be used. For example, substring('abc') should return 'ab' instead of 'bc'.

Although there are O(N^2) solutions to this problem, you should try to solve this problem in O(N) time. Tests may pass for O(N^2) solutions but, this is not guaranteed.

This question is much harder than some of the other substring questions. It's easy to think that you have a solution and then get hung up on the implementation.

def substring(stg):
    i, mi, s, ms, l = 0, 0, 3, 2, len(stg)
    while i + s <= l:
        if len(set(stg[i:i+s])) > 2:
            i += 1
        else:
            mi, ms = i, s
            s += 1
    return stg[mi:mi+ms]


Solve in Python:
Find the minimum area of a square land on which you can place two identical rectangular $a \times b$ houses. The sides of the houses should be parallel to the sides of the desired square land.

Formally,   You are given two identical rectangles with side lengths $a$ and $b$ ($1 \le a, b \le 100$) — positive integers (you are given just the sizes, but not their positions).  Find the square of the minimum area that contains both given rectangles. Rectangles can be rotated (both or just one), moved, but the sides of the rectangles should be parallel to the sides of the desired square.

Two rectangles can touch each other (side or corner), but cannot intersect. Rectangles can also touch the sides of the square but must be completely inside it. You can rotate the rectangles. Take a look at the examples for a better understanding.

 [Image] The picture shows a square that contains red and green rectangles.

-----Input-----

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

Each test case is a line containing two integers $a$, $b$ ($1 \le a, b \le 100$) — side lengths of the rectangles.

-----Output-----

Print $t$ answers to the test cases. Each answer must be a single integer — minimal area of square land, that contains two rectangles with dimensions $a \times b$.

-----Example-----
Input
8
3 2
4 2
1 1
3 1
4 7
1 3
7 4
100 100

Output
16
16
4
9
64
9
64
40000

-----Note-----

Below are the answers for the first two test cases:  [Image]   [Image]

t=int(input())
for i in range(t):
    a,b=list(map(int,input().split()))
    c=min(a,b)
    d=max(a,b)
    print(max(2*c,d)**2)


Solve in Python:
Find the minimum length word from a given dictionary words, which has all the letters from the string licensePlate.  Such a word is said to complete the given string licensePlate

Here, for letters we ignore case.  For example, "P" on the licensePlate still matches "p" on the word.

It is guaranteed an answer exists.  If there are multiple answers, return the one that occurs first in the array.

The license plate might have the same letter occurring multiple times.  For example, given a licensePlate of "PP", the word "pair" does not complete the licensePlate, but the word "supper" does.

Example 1:

Input: licensePlate = "1s3 PSt", words = ["step", "steps", "stripe", "stepple"]
Output: "steps"
Explanation: The smallest length word that contains the letters "S", "P", "S", and "T".
Note that the answer is not "step", because the letter "s" must occur in the word twice.
Also note that we ignored case for the purposes of comparing whether a letter exists in the word.

Example 2:

Input: licensePlate = "1s3 456", words = ["looks", "pest", "stew", "show"]
Output: "pest"
Explanation: There are 3 smallest length words that contains the letters "s".
We return the one that occurred first.

Note:

licensePlate will be a string with length in range [1, 7].
licensePlate will contain digits, spaces, or letters (uppercase or lowercase).
words will have a length in the range [10, 1000].
Every words[i] will consist of lowercase letters, and have length in range [1, 15].

class Solution:
     def dominantIndex(self, nums):
         """
         :type nums: List[int]
         :rtype: int
         """
         if len(nums)==1:
             return 0
         Max = max(nums)
         if nums.count(Max)>1:
             return -1
         if any(nums)==False:
             return 0
         if nums.count(0)==len(nums)-1:
             return nums.index(Max)
         for i in nums:
             if i!=Max and i!=0:
                 if Max/i<2:
                     return -1
         return nums.index(Max)


Solve in Python:
Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...

Note:
n is positive and will fit within the range of a 32-bit signed integer (n < 231).

Example 1:

Input:
3

Output:
3

Example 2:

Input:
11

Output:
0

Explanation:
The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.

class Solution:
     def findNthDigit(self, n):
         """
         :type n: int
         :rtype: int
         """
         n -= 1
         for digits in range(1, 11):
             first = 10**(digits - 1)
             if n < 9 * first * digits:
                 return int(str(first + n//digits)[n%digits])
             n -= 9 * first * digits


Solve in Python:
Find the number with the most digits.

If two numbers in the argument array have the same number of digits, return the first one in the array.

def find_longest(arr):
    l = [len(str(a)) for a in arr]
    return arr[l.index(max(l))]


Solve in Python:
Find the second-to-last element of a list.

Example:
```python
penultimate([1,2,3,4])            # => 3
penultimate(["Python is dynamic"]) # => 'i'
(courtesy of [haskell.org](http://www.haskell.org/haskellwiki/99_questions/1_to_10))
```

def penultimate(a):
  return a[len(a)-2]


Solve in Python:
Find the smallest prime palindrome greater than or equal to N.
Recall that a number is prime if it's only divisors are 1 and itself, and it is greater than 1.
For example, 2,3,5,7,11 and 13 are primes.
Recall that a number is a palindrome if it reads the same from left to right as it does from right to left.
For example, 12321 is a palindrome.

Example 1:
Input: 6
Output: 7

Example 2:
Input: 8
Output: 11

Example 3:
Input: 13
Output: 101

Note:

1 <= N <= 10^8
The answer is guaranteed to exist and be less than 2 * 10^8.

class Solution:
    def primePalindrome(self, N: int) -> int:
        def isPrime(N):
            return N > 1 and all(N % d for d in range(2, int(N**0.5)+1))

        # N must be a palindrome with odd number of digits.
        # The return value will have odd number of digits too.
        def nextPalindrome(N):
            if N in [999, 99999, 9999999]:
                return (N + 1) * 10 + 1
            n = str(N // 10 ** (len(str(N))//2) + 1)
            return int(n + n[-2::-1])

        if N <= 11:
            while not isPrime(N):
                N += 1
            return N

        if (digits := len(str(N))) % 2 == 0:
            N = 10 ** digits + 1
        else:
            n = str(N // 10 ** (len(str(N))//2))
            if (p := int(n + n[-2::-1])) >= N:
                N = p
            else:
                N = nextPalindrome(p)

        while not isPrime(N):
            N = nextPalindrome(N)
        return N


Solve in Python:
Find the sum of the odd numbers within an array, after cubing the initial integers. The function should return `undefined`/`None`/`nil`/`NULL` if any of the values aren't numbers.

~~~if:java,csharp
Note: There are ONLY integers in the JAVA and C# versions of this Kata.
~~~

~~~if:python
Note: Booleans should not be considered as numbers.
~~~

def cube_odd(a):
    return sum(e**3 for e in a if e % 2) if all(type(e) == int for e in a) else None


Solve in Python:
Find the total sum of internal angles (in degrees) in an n-sided simple polygon. N will be greater than 2.

def angle(n):
    if n <=2:
        raise ValueError
    else:
        return 180*(int(n)-2)


Solve in Python:
Find the volume of a cone whose radius and height are provided as parameters to the function `volume`. Use the value of PI provided by your language (for example: `Math.PI` in JS, `math.pi` in Python or `Math::PI` in Ruby) and round down the volume to an Interger.

If you complete this kata and there are no issues, please remember to give it a ready vote and a difficulty rating. :)

from math import pi,floor

def volume(r,h):
    return floor(h/3 * pi * r ** 2)


Solve in Python:
Finding your seat on a plane is never fun, particularly for a long haul flight... You arrive, realise again just how little leg room you get, and sort of climb into the seat covered in a pile of your own stuff.

To help confuse matters (although they claim in an effort to do the opposite) many airlines omit the letters 'I' and 'J' from their seat naming system.

the naming system consists of a number (in this case between 1-60) that denotes the section of the plane where the seat is (1-20 = front, 21-40 = middle, 40+ = back). This number is followed by a letter, A-K with the exclusions mentioned above.

Letters A-C denote seats on the left cluster, D-F the middle and G-K the right.

Given a seat number, your task is to return the seat location in the following format:

'2B' would return 'Front-Left'.

If the number is over 60, or the letter is not valid, return 'No Seat!!'.

# import this
# Явное лучше, чем неявное.
# Простое лучше, чем сложное.
# Если реализацию легко объяснить — идея, возможно, хороша.
def plane_seat(a):
    num2 = a[0] + a[1]
    num1 = a[0]
    let = a[-1]
    if let == 'I' or let == 'J':
        return ('No Seat!!')
    elif len(a) == 3:
        if int(num2) > 60:
            return ('No Seat!!')
        elif int(num2) >= 1 and int(num2) <= 20:
            if let == 'A' or let == 'B' or let == 'C':
                return ('Front-Left')
            if let == 'D' or let == 'E' or let == 'F':
                return ('Front-Middle')
            if let == 'G' or let == 'H' or let == 'K':
                return ('Front-Right')
        elif int(num2) >= 21 and int(num2) <= 40:
            if let == 'A' or let == 'B' or let == 'C':
                return ('Middle-Left')
            if let == 'D' or let == 'E' or let == 'F':
                return ('Middle-Middle')
            if let == 'G' or let == 'H' or let == 'K':
                return ('Middle-Right')
        elif int(num2) >= 41 and int(num2) <= 60:
            if let == 'A' or let == 'B' or let == 'C':
                return ('Back-Left')
            if let == 'D' or let == 'E' or let == 'F':
                return ('Back-Middle')
            if let == 'G' or let == 'H' or let == 'K':
                return ('Back-Right')
    elif len(a) == 2:
        if int(num1) >= 1 and int(num1) <= 20:
            if let == 'A' or let == 'B' or let == 'C':
                return ('Front-Left')
            if let == 'D' or let == 'E' or let == 'F':
                return ('Front-Middle')
            if let == 'G' or let == 'H' or let == 'K':
                return ('Front-Right')

'''
1-20 - front
21-40 - middle
41-60 - back

A,B,C - left
D,E,F - middle
G,H,K - right
'''


Solve in Python:
Finish the solution so that it sorts the passed in array of numbers. If the function passes in an empty array or null/nil value then it should return an empty array.

For example:

```python
solution([1,2,3,10,5]) # should return [1,2,3,5,10]
solution(None) # should return []
```

```Hakell
sortNumbers [1, 2, 10, 50, 5] = Just [1, 2, 5, 10, 50]
sortNumbers [] = Nothing
```

def solution(name):
    return sorted(name) if name  else []


Solve in Python:
Finish the solution so that it takes an input `n` (integer) and returns a string that is the decimal representation of the number grouped by commas after every 3 digits.

Assume: `0 <= n < 2147483647`

## Examples

```
       1  ->           "1"
      10  ->          "10"
     100  ->         "100"
    1000  ->       "1,000"
   10000  ->      "10,000"
  100000  ->     "100,000"
 1000000  ->   "1,000,000"
35235235  ->  "35,235,235"
```


Solve in Python:
Firdavs is living on planet F. There are $N$ cities (numbered $1$ through $N$) on this planet; let's denote the value of city $i$ by $v_i$. Firdavs can travel directly from each city to any other city. When he travels directly from city $x$ to city $y$, he needs to pay $f(x, y) = |v_y-v_x|+y-x$ coins (this number can be negative, in which case he receives $-f(x, y)$ coins).
Let's define a simple path from city $x$ to city $y$ with length $k \ge 1$ as a sequence of cities $a_1, a_2, \ldots, a_k$ such that all cities in this sequence are different, $a_1 = x$ and $a_k = y$. The cost of such a path is $\sum_{i=1}^{k-1} f(a_i, a_{i+1})$.
You need to answer some queries for Firdavs. In each query, you are given two cities $x$ and $y$, and you need to find the minimum cost of a simple path from city $x$ to city $y$. Then, you need to find the length of the longest simple path from $x$ to $y$ with this cost.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains two space-separated integers $N$ and $Q$.
- The second line contains $N$ space-separated integers $v_1, v_2, \ldots, v_N$.
- The following $Q$ lines describe queries. Each of these lines contains two space-separated integers $x$ and $y$.

-----Output-----
For each query, print a single line containing two space-separated integers ― the minimum cost and the maximum length.

-----Constraints-----
- $1 \le T \le 100$
- $1 \le N, Q \le 2 \cdot 10^5$
- $0 \le v_i \le 10^9$ for each valid $i$
- $1 \le x, y \le N$
- the sum of $N$ in all test cases does not exceed $5 \cdot 10^5$
- the sum of $Q$ in all test cases does not exceed $5 \cdot 10^5$

-----Subtasks-----
Subtask #1 (30 points):
- $1 \le N, Q \le 1,000$
- $v_1 < v_2 < \ldots < v_N$
- the sum of $N$ in all test cases does not exceed $5,000$
- the sum of $Q$ in all test cases does not exceed $5,000$
Subtask #2 (70 points): original constraints

-----Example...

import bisect

for _ in range(int(input())):
 n, q = list(map(int, input().split()))
 ar = list(map(int, input().split()))

 new = ar.copy()
 new.sort()

 for __ in range(q):
  x, y = list(map(int, input().split()))
  cost = abs(ar[y - 1] - ar[x - 1]) + y - x

  length = bisect.bisect_right(new, max(ar[y - 1], ar[x - 1]))
  length -= bisect.bisect_left(new, min(ar[x - 1], ar[y - 1]))

  print(cost, length)


Solve in Python:
FizzBuzz is often one of the first programming puzzles people learn. Now undo it with reverse FizzBuzz!

Write a function that accepts a string, which will always be a valid section of FizzBuzz. Your function must return an array that contains the numbers in order to generate the given section of FizzBuzz.

Notes:
- If the sequence can appear multiple times within FizzBuzz, return the numbers that generate the first instance of that sequence.
- All numbers in the sequence will be greater than zero.
- You will never receive an empty sequence.

## Examples
```
reverse_fizzbuzz("1 2 Fizz 4 Buzz")        -->  [1, 2, 3, 4, 5]
reverse_fizzbuzz("Fizz 688 689 FizzBuzz")  -->  [687, 688, 689, 690]
reverse_fizzbuzz("Fizz Buzz")              -->  [9, 10]
```

def reverse_fizzbuzz(s):
    if s == 'Fizz': return [3]
    if s == 'Buzz': return [5]
    if s == 'Fizz Buzz': return [9, 10]
    if s == 'Buzz Fizz': return [5, 6]
    if s == 'FizzBuzz': return [15]
    s = s.split()
    for i in range(len(s)):
        if s[i].isdigit():
            start = int(s[i]) - i
            return list(range(start, start + len(s)))


Solve in Python:
Fizza is a cute girl and she wants to be more beautiful.
So she approached a magician to increase her beauty magically. But the magician's
glasses accidently got locked inside the locker and he forgot the password. Without
glasses he can't help her. The password is hidden in N integers i.e. $a[1], a[2], ..... a[N]$
written on his magical stick.The password is the maximum number of moves Fizza can perform, for any position $i$ such that 1 < = $i$ < = $N$ and integer $X$ is present at $i$-th
position. In one move she can perform one of the following operations ->
$(1)$  If ( $i$ + 1 < = $N$ ) she can go to position ($i$ + 1 ) if integer at ( $i$ + 1 )-th
position is equal to $X$.
$(2)$ if ( $i$ + 2 < = $N$ ) she can go to position ($i$ + 2 ) if integer at ($i$ + 2)-th
position is equal to $X$.
Fizza is a bit worried about her beauty so she can't focus on the problem but she asked for
your help to find the password.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase consists of  two lines of input.
- Input $N$.
- Input $N$ integers .

-----Output:-----
For each testcase, output in a single line Maximum number of moves.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq N \leq 10^5$
- $1 \leq a[i] \leq 2*10^5$

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

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

-----EXPLANATION:-----
In the first case, integers at position 1 and 3 are the same and at alternate positions.
In the second case, integers at position 1, 2, 4 follow the conditions.

from copy import copy
def main():
    for _ in range(int(input())):
        n=int(input())
        a=list(map(int,input().split()))
        i=0
        l=[]
        visited=[False for i in range(n)]
        for j in range(n):
            if(not visited[j]):
                i=j
                s=0
                while(i<n):
                    visited[i]=True
                    if(i+1<n and a[i]==a[i+1]):
                        s+=1
                        i+=1
                    elif(i+2<n and a[i]==a[i+2]):
                        s+=1
                        i+=2
                    else:
                        break
                l.append(s)
        print(max(l))
main()


Solve in Python:
Flash has invited his nemesis The Turtle (He actually was a real villain! ) to play his favourite card game, SNAP. In this game a 52 card deck is dealt out so both Flash and the Turtle get 26 random cards.

Each players cards will be represented by an array like below

Flash’s pile:
```[ 'A', '5', 'Q', 'Q', '6', '2', 'A', '9', '10', '6', '4', '3', '10', '9', '3', '8', 'K', 'J', 'J', 'K', '7', '9', '5', 'J', '7', '2' ]```

Turtle’s pile:
```[ '8', 'A', '2', 'Q', 'K', '8', 'J', '6', '4', '8', '7', 'A', '5', 'K', '3', 'Q', '6', '9', '4', '3', '4', '10', '2', '7', '10', '5' ]```

The players take it in turn to take the top card from their deck (the first element in their array) and place it in a face up pile in the middle. Flash goes first.

When a card is placed on the face up pile that matches the card it is placed on top of the first player to shout ‘SNAP!’ wins that round. Due to Flash's speed he wins every round.

Face up pile in the middle:
```[ 'A', '8', '5', 'A', 'Q', '2', 'Q', 'Q',```  =>  SNAP!

The face up pile of cards in the middle are added to the bottom of Flash's pile.

Flash’s pile after one round:
```['6', '2', 'A', '9', '10', '6', '4', '3', '10', '9', '3', '8', 'K', 'J', 'J', 'K', '7', '9', '5', 'J', '7', '2', 'A', '8', '5', 'A', 'Q', '2', 'Q', 'Q' ]```

Flash then starts the next round by putting down the next card.

When Turtle runs out of cards the game is over.

How many times does Flash get to call Snap before Turtle runs out of cards?

If both the player put down all their cards into the middle without any matches then the game ends a draw and Flash calls SNAP 0 times.

def round(flash_pile, turtle_pile):
    faceup_pile = []
    while turtle_pile:
        for pile in flash_pile, turtle_pile:
            faceup_pile.append(pile.pop(0))
            if len(faceup_pile) >= 2 and faceup_pile[-1] == faceup_pile[-2]:
                flash_pile.extend(faceup_pile)
                return True

def snap(flash_pile, turtle_pile):
    for i in range(26):
        if not round(flash_pile, turtle_pile):
            return i


Solve in Python:
Following from the previous kata and taking into account how cool psionic powers are compare to the Vance spell system (really, the idea of slots to dumb down the game sucks, not to mention that D&D became a smash hit among geeks, so...), your task in this kata is to create a function that returns how many power points you get as a psion [because psions are the coolest, they allow for a lot of indepth tactic playing and adjusting for psychic warriors or wilders or other non-core classes would be just an obnoxious core].

Consider both [the psion power points/days table](http://www.dandwiki.com/wiki/SRD:Psion#Making_a_Psion) and [bonus power points](http://www.d20pfsrd.com/psionics-unleashed/classes/#Table_Ability_Modifiers_and_Bonus_Power_Points) to figure out the correct reply, returned as an integer; the usual interpretation is that bonus power points stop increasing after level 20, but for the scope of this kata, we will pretend they keep increasing as they did before.

To compute the total, you will be provided, both as non-negative integers:

* class level (assume they are all psion levels and remember the base power points/day halts after level 20)
* manifesting attribute score (Intelligence, to be more precise) to determine the total, provided the score is high enough for the character to manifest at least one power.

Some examples:

```python
psion_power_points(1,0) == 0
psion_power_points(1,10) == 0
psion_power_points(1,11) == 2
psion_power_points(1,20) == 4
psion_power_points(21,30) == 448
```

*Note: I didn't explain things in detail and just pointed out to the table on purpose, as my goal is also to train the pattern recognition skills of whoever is going to take this challenges, so do not complain about a summary description. Thanks :)*

In the same series:

* [D&D Character generator #1: attribute modifiers and spells](https://www.codewars.com/kata/d-and-d-character-generator-number-1-attribute-modifiers-and-spells/)
* [D&D Character generator #2: psion power...


Solve in Python:
Following on from [Part 1](http://www.codewars.com/kata/filling-an-array-part-1/), part 2 looks at some more complicated array contents.

So let's try filling an array with...

## ...square numbers
The numbers from `1` to `n*n`

## ...a range of numbers
A range of numbers starting from `start` and increasing by `step`

## ...random numbers
A bunch of random integers between `min` and `max`

## ...prime numbers
All primes starting from `2` (obviously)...

HOTE: All the above functions should take as their first parameter a number that determines the length of the returned array.

from random import randint

PRIMES = [2] + [n for n in range(3, 10**3, 2) if all(n%d for d in range(3, int(n**0.5)+1, 2))]

def squares(n):
    return [x*x for x in range(1, n+1)]

def num_range(n, start, step):
    return [start + step * i for i in range(n)]

def rand_range(n, mn, mx):
    return [randint(mn, mx) for _ in range(n)]

def primes(n):
    return PRIMES[:n]


Solve in Python:
For "x", determine how many positive integers less than or equal to "x" are odd but not prime. Assume "x" is an integer between 1 and 10000.

Example: 5 has three odd numbers (1,3,5) and only the number 1 is not prime, so the answer is 1

Example: 10 has five odd numbers (1,3,5,7,9) and only 1 and 9 are not prime, so the answer is 2

def not_prime(x):
    if x == 1: return True
    for y in range(2, int(x ** 0.5) + 1):
        if x % y == 0:
            return True
    return False
def odd_not_prime(n):
    return sum(not_prime(x) for x in range(1, n + 1, 2))


Solve in Python:
For Diwali, Chef arranges all $K$ laddus in a row in his sweet shop. Whenever a customer comes to buy laddus, chef follows a rule that each customer must buy all laddus on odd position. After the selection of the laddu, a new row is formed, and again out of these only laddus on odd position are selected. This continues until the chef left with the last laddu. Find out the position of that last laddu in the original row.

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

-----Output:-----
For each testcase, print the position of that laddu who is left, in the original row.

-----Constraints-----
- $1 \leq T \leq 10^5$
- $1 \leq K \leq 10^5$

-----Sample Input:-----
3
1
5
8

-----Sample Output:-----
1
4
8

-----EXPLANATION:-----
For 1) Only one laddu which is last so print 1.
For 2) Customer 1: [1, 3, 5]
New row = [2, 4]

Customer 2: [2]

Last laddu = 4

from math import  log2,floor
for _ in range(int(input())):
    n=int(input())

    ans=floor(log2(n))
    print(2**ans)


Solve in Python:
For a given 2D vector described by cartesian coordinates of its initial point and terminal point in the following format:

```python
[[x1, y1], [x2, y2]]
```

Your function must return this vector's length represented as a floating point number.

Error must be within 1e-7.

Coordinates can be integers or floating point numbers.

from math import sqrt
def vector_length(v):
    return sqrt((v[1][0]-v[0][0])**2+(v[0][1]-v[1][1])**2)


Solve in Python:
For a given array whose element values are randomly picked from single-digit integers `0` to `9`, return an array with the same digit order but all `0`'s paired. Paring two `0`'s generates one `0` at the location of the first.

Ex:
```python
pair_zeros([0, 1, 0, 2])
# paired: ^-----^ cull second zero
       == [0, 1, 2];
#   kept: ^

pair_zeros([0, 1, 0, 0])
# paired: ^-----^
       == [0, 1,    0];
#   kept: ^

pair_zeros([1, 0, 7, 0, 1])
# paired:    ^-----^
       == [1, 0, 7,    1];
#   kept:    ^

pair_zeros([0, 1, 7, 0, 2, 2, 0, 0, 1, 0])
# paired: ^--------^
#        [0, 1, 7,    2, 2, 0, 0, 1, 0]
#   kept: ^         paired: ^--^
       == [0, 1, 7,    2, 2, 0,    1, 0];
#   kept:                   ^
```

Here are the 2 important rules:

1. Pairing happens from left to right in the array. However, for each pairing, the "second" `0` will always be paired towards the first (right to left)
2. `0`'s generated by pairing can NOT be paired again

def pair_zeros(arr):
    lst = []
    flag = False
    for i in arr:
        if i == 0:
            if not flag:
                lst.append(i)
            flag = not flag
        else:
            lst.append(i)
    return lst


Solve in Python:
For a given two numbers your mission is to derive a function that evaluates whether two given numbers are **abundant**, **deficient** or **perfect** and whether together they are **amicable**.

### Abundant Numbers
An abundant number or excessive number is a number for which the sum of its proper divisors is greater than the number itself.

The integer 12 is the first abundant number. Its proper divisors are 1, 2, 3, 4 and 6 for a total of 16 (> 12).

### Deficient Numbers
A deficient number is a number for which the sum of its proper divisors is less than the number itself.

The first few deficient numbers are: 1, 2, 3, 4, 5, 7, 8, 9.

### Perfect Numbers
A perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself.

The first perfect number is 6, because 1, 2, and 3 are its proper positive divisors, and 1 + 2 + 3 = 6.

### Amicable Numbers
Amicable numbers are two different numbers so related that the sum of the proper divisors of each is equal to the other number. (A proper divisor of a number is a positive factor of that number other than the number itself. For example, the proper divisors of 6 are 1, 2, and 3.)

For example, the smallest pair of amicable numbers is (220, 284); for the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110, of which the sum is 284; and the proper divisors of 284 are 1, 2, 4, 71 and 142, of which the sum is 220.

### The Function

For a given two numbers, derive function `deficientlyAbundantAmicableNumbers(num1, num2)` which returns a string with first and second word either abundant or deficient depending on whether `num1` or `num2` are abundant, deficient or perfect. The string should finish with either amicable or not amicable depending on the relationship between `num1` and `num2`.

e.g. `deficientlyAbundantAmicableNumbers(220, 284)` returns `"abundant deficient amicable"` as 220 is an abundant number, 284 is a deficient number and amicable...

def deficiently_abundant_amicable_numbers(n1, n2):
    d1, d2 = (sum(d for d in range(1, n//2 + 1) if n % d == 0) for n in (n1, n2))
    perf = " ".join("deficient" if d < n else "abundant" if n < d else "perfect" for (n, d) in ((n1, d1), (n2, d2)))
    is_amic = "" if n1 != n2 and (n1, n2) == (d2, d1) else "not "
    return f"{perf} {is_amic}amicable"


Solve in Python:
For a new 3D game that will be released, a team of programmers needs an easy function. (Then it will be processed as a method in a Class, forget this concept for Ruby)

We have an sphere with center O, having in the space the coordinates `[α, β, γ]` and radius `r`  and a list of points, `points_list`, each one with coordinates `[x, y, z]`. Select the biggest triangle (or triangles) that has (have) all its (their) 3 vertice(s) as interior points of the sphere (not even in the sphere contour). You should consider that a point P is interior if its distance to center O, d, is such that:

d < r

and

(d - r) / r| > 10^(-10)

Let's see the situation with the following points in the image posted below:
```python
A = [1,2,-4]; B = [-3, 2, 4]; C = [7, 8, -4]; D = [2, 3, 5]; E = [-2, -1, 1]
```

The sphere has the following features:
```
O = [1, 2, -2] (Center of the sphere)
radius = 8
```

As C is the only exterior point of the sphere, the possible triangles that have their vertices interior to the sphere are:

```
ABD, ABE, ADE, BDE
```

Let's see which is the biggest one:

```python
Triangle    Triangle with its points         Area
ABD        [[1,2,-4],[-3,2,4],[2,3,5]]    22.44994432064
ABE        [[1,2,-4],[-3,2,4],[-2,-1,1]]  13.56465996625
ADE        [[1,2,-4],[2,3,5],[-2,-1,1]]   22.62741699796 <---- biggest triangle
BDE        [[-3,2,4],[2,3,5],[-2,-1,1]]   11.31370849898
```

Our function ```biggest_triang_int()``` (javascript: ```biggestTriangInt()```should output for this case:

```python
points_list = [[1,2,-4], [-3, 2, 4], [7, 8, -4], [2, 3, 5], [-2, -1, 1]]
sphere_center = [1, 2, -2]
radius = 8
biggest_triang_int(points_list, sphere_center, radius) == [4, 22.62741699796,  [[1,2,-4],[2,3,5],[-2,-1,1]]]
```

That means that with the given points list we may generate 4 triangles with all their vertices as interior points of the sphere, the biggest triangle has an area of 22.62741699796 (the units does not matter and the values for the area should not be rounded) and finally, there is only one triangle...

def biggest_triang_int(points, ce, ra):
    max=0; r=[]; le=len(points); count=0
    for i in range(le):
       for j in range (i+1,le):
          for k in range (j+1,le):
             po=[points[i],points[j],points[k]]
             if distance(po[0],ce)<=ra and distance(po[1],ce)<=ra and distance(po[2],ce)<=ra:
                count+=1
                ae=areatriangle(po[0],po[1],po[2])
                if ae>=max:
                   if abs(ae-max)>1e-5: max=ae; r=[po]
                   else: r.append(po)
    if len(r)==1: r=r[0]
    return [count,max,r] if count>0 else []

def areatriangle((x1,y1,z1),(x2,y2,z2),(x3,y3,z3)):
    a=distance((x1,y1,z1),(x2,y2,z2))
    b=distance((x2,y2,z2),(x3,y3,z3))
    c=distance((x3,y3,z3),(x1,y1,z1))
    return heron(a,b,c)

def heron(a,b,c):
    s=(a+b+c)/2
    return (s*(s-a)*(s-b)*(s-c))**0.5

def distance((x1,y1,z1),(x2,y2,z2)):
    return ((x1-x2)**2+(y1-y2)**2+(z1-z2)**2)**.5


Solve in Python:
For a permutation P = (p1, p2, ..., pN) of numbers [1, 2, ..., N], we define the function f(P) = max(p1, p2) + max(p2, p3) + ... + max(pN-1, pN).
You are given N and an integer K. Find and report a permutation P of [1, 2, ..., N] such that f(P) = K, if such a permutation exists.
Note f([1]) = 0.

-----Input-----
- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
- The only line of each test case consists of two space-separated integers N, K respectively.

-----Output-----
For each test case, if a permutation satisfying the condition exists, output a single line containing N space-separated integers which denotes any such permutation. If no such permutation exists, output a single integer -1 instead.
Use fast I/O methods since the size of the output is large.

-----Constraints-----
- 1 ≤ T ≤ 40
- 1 ≤ N ≤ 105
- Sum of N over all test cases in each file ≤ 106
- 0 ≤ K ≤ 2 * 1010

-----Example-----
Input:
3
4 12
2 2
5 14

Output:
-1
1 2
5 4 3 2 1

-----Explanation-----
Example 1. There doesn't exist any permutation of numbers [1, 2, 3, 4] that can have its f value equal to 4. Hence answer is -1.
Example 2. The permutations [1, 2] and [2, 1] both have their f values equal to 2. You can print any of these two permutations.
Example 3. The permutation [5, 4, 3, 2, 1]
has f value = max(5, 4) + max(4, 3) + max(3, 2) + max(2, 1) = 5 + 4 + 3 + 2 = 14.

for i in range(int(input())):
    n,k=[int(i) for i in input().split()]
    if(n%2==0):
     if(k<(n*(n+1))//2 - 1  or  k>3*((n//2)**2) - 1):print(-1)
     elif(k==(n*(n+1))//2 - 1):
      for i in range(1,n+1):print(i,'',end='')
      print()
     else:
      k,count,p,l,x = k-(n*(n+1))//2 + 1,0,0,[0 for i in range(n)],1
      while(k>0):p+=2 ;k,count = k-n+p ,count+1
      for i in range(n,n-count+1,-1):l[x]=i ;x+=2
      k=-k ;l[2*count - 1 +k],p = n-count+1 ,1
      for i in range(n):
       if(l[i]==0):l[i]=p ;   p+=1
      for i in l:print(i,'',end='')
      print()
    else:
     if(n==1):print(1) if(k==0) else print(-1)
     elif(k<(n*(n+1))//2 - 1  or k>3*(n//2)*(n//2 + 1)):print(-1)
     elif(k==(n*(n+1))//2 - 1):
      for i in range(1,n+1):print(i,'',end='')
      print()
     else:
      k,count,p,l,x = k-(n*(n+1))//2 + 1,0,0,[0 for i in range(n)],1
      while(k>0):  p+=2 ;  k,count = k-n+p ,count+1
      for i in range(n,n-count+1,-1): l[x]=i; x+=2


Solve in Python:
For a pole vaulter, it is very important to begin the approach run at the best possible starting mark. This is affected by numerous factors and requires fine-tuning in practice. But there is a guideline that will help a beginning vaulter start at approximately the right location for the so-called "three-step approach," based on the vaulter's body height.

This guideline was taught to me in feet and inches, but due to the international nature of Codewars, I am creating this kata to use metric units instead.

You are given the following two guidelines to begin with:
(1) A vaulter with a height of 1.52 meters should start at 9.45 meters on the runway.
(2) A vaulter with a height of 1.83 meters should start at 10.67 meters on the runway.

You will receive a vaulter's height in meters (which will always lie in a range between a minimum of 1.22 meters and a maximum of 2.13 meters). Your job is to return the best starting mark in meters, rounded to two decimal places.

Hint: Based on the two guidelines given above, you will want to account for the change in starting mark per change in body height. This involves a linear relationship. But there is also a constant offset involved. If you can determine the rate of change described above, you should be able to determine that constant offset.

from decimal import Decimal

def starting_mark(height):

#     if height == 1.22:
#         return 8.27
#     elif height == 2.13:
#         return 11.85

    number = Decimal("0.03935483870967741935483870968")
    start = Decimal("8.27")
    height = Decimal(height)
    min_height = Decimal("1.22")

    form = (height - min_height) * 100 * number + start
    form = form.quantize(Decimal("1.00"))
    form = float(form)
    return form


Solve in Python:
For a string $S$ let the unique set of characters that occur in it one or more times be $C$. Consider a permutation of the elements of $C$ as $(c_1, c_2, c_3 ... )$. Let $f(c)$ be the number of times $c$ occurs in $S$.
If any such permutation of the elements of $C$ satisfies $f(c_i) = f(c_{i-1}) + f(c_{i-2})$ for all $i \ge 3$, the string is said to be a dynamic string.
Mr Bancroft is given the task to check if the string is dynamic, but he is busy playing with sandpaper. Would you help him in such a state?
Note that if the number of distinct characters in the string is less than 3, i.e. if $|C| < 3$, then the string is always dynamic.

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

-----Output:-----
For each testcase, output in a single line "Dynamic" if the given string is dynamic, otherwise print "Not". (Note that the judge is case sensitive)

-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq |S| \leq 10^5$
- $S$ contains only lower case alphabets: $a$, $b$, …, $z$

-----Sample Input:-----
3
aaaabccc
aabbcc
ppppmmnnoooopp

-----Sample Output:-----
Dynamic
Not
Dynamic

-----Explanation:-----
- Testase 1: For the given string, $C = \{a, b, c\}$ and $f(a)=4, f(b)=1, f(c)=3$. $f(a) = f(c) + f(b)$ so the permutation $(b, c, a)$ satisfies the requirement.
- Testcase 2: Here too $C = \{a, b, c\}$ but no permutation satisfies the requirement of a dynamic string.
- Testcase 3: Here $C = \{m, n, o, p\}$ and $(m, n, o, p)$ is a permutation that makes it a dynamic string.

t = int(input())
for i in range(t):
 s = input()
 lst = []
 for i in set(s):
  lst.append(s.count(i))
 lst.sort()

 if len(lst)<3 or lst[-1]==lst[-2]+lst[-3]:
  print("Dynamic")
 else:
  print("Not")