Solve in Python:
The odd and even numbers are fighting against each other!

You are given a list of positive integers. The odd numbers from the list will fight using their `1` bits from their binary representation, while the even numbers will fight using their `0` bits. If present in the list, number `0` will be neutral, hence not fight for either side.

You should return:

* `odds win` if number of `1`s from odd numbers is larger than `0`s from even numbers
* `evens win` if number of `1`s from odd numbers is smaller than `0`s from even numbers
* `tie` if equal, including if list is empty

Please note that any prefix that might appear in the binary representation, e.g. `0b`, should not be counted towards the battle.

### Example:
For an input list of `[5, 3, 14]`:

* odds: `5` and `3` => `101` and `11` => four `1`s
* evens: `14` => `1110` => one `0`

Result: `odds win` the battle with 4-1

If you enjoyed this kata, you can find a nice variation of it [here](https://www.codewars.com/kata/world-bits-war).

def bits_battle(numbers):
  res = [0, 0]
  for x in numbers:
      res[x&1] += bin(x)[2:].count("01"[x&1])
  return "odds win" if res[0] < res[1] else "evens win" if res[0] > res[1] else "tie"


Solve in Python:
The only difference between easy and hard versions is constraints.

Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you.

There are $n$ voters, and two ways to convince each of them to vote for you. The first way to convince the $i$-th voter is to pay him $p_i$ coins. The second way is to make $m_i$ other voters vote for you, and the $i$-th voter will vote for free.

Moreover, the process of such voting takes place in several steps. For example, if there are five voters with $m_1 = 1$, $m_2 = 2$, $m_3 = 2$, $m_4 = 4$, $m_5 = 5$, then you can buy the vote of the fifth voter, and eventually everyone will vote for you. Set of people voting for you will change as follows: ${5} \rightarrow {1, 5} \rightarrow {1, 2, 3, 5} \rightarrow {1, 2, 3, 4, 5}$.

Calculate the minimum number of coins you have to spend so that everyone votes for you.

-----Input-----

The first line contains one integer $t$ ($1 \le t \le 2 \cdot 10^5$) — the number of test cases.

The first line of each test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of voters.

The next $n$ lines contains the description of voters. $i$-th line contains two integers $m_i$ and $p_i$ ($1 \le p_i \le 10^9, 0 \le m_i < n$).

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

-----Output-----

For each test case print one integer — the minimum number of coins you have to spend so that everyone votes for you.

-----Example-----
Input
3
3
1 5
2 10
2 8
7
0 1
3 1
1 1
6 1
1 1
4 1
4 1
6
2 6
2 3
2 8
2 7
4 4
5 5

Output
8
0
7

-----Note-----

In the first test case you have to buy vote of the third voter. Then the set of people voting for you will change as follows: ${3} \rightarrow {1, 3} \rightarrow {1, 2, 3}$.

In the second example you don't need to buy votes. The set of people voting for you will change as follows: ${1} \rightarrow {1, 3, 5} \rightarrow {1, 2, 3, 5} \rightarrow {1, 2, 3, 5, 6, 7} \rightarrow {1, 2, 3, 4, 5, 6, 7}$.

In...

import sys
import heapq as hq

readline = sys.stdin.readline
read = sys.stdin.read
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')

def solve():
    n = ni()
    vot = [tuple(nm()) for _ in range(n)]
    vot.sort(key = lambda x: (-x[0], x[1]))
    q = list()
    c = 0
    cost = 0
    for i in range(n):
        hq.heappush(q, vot[i][1])
        while n - i - 1 + c < vot[i][0]:
            cost += hq.heappop(q)
            c += 1
    print(cost)
    return

# solve()

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


Solve in Python:
The only difference between easy and hard versions is constraints.

Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you.

There are $n$ voters, and two ways to convince each of them to vote for you. The first way to convince the $i$-th voter is to pay him $p_i$ coins. The second way is to make $m_i$ other voters vote for you, and the $i$-th voter will vote for free.

Moreover, the process of such voting takes place in several steps. For example, if there are five voters with $m_1 = 1$, $m_2 = 2$, $m_3 = 2$, $m_4 = 4$, $m_5 = 5$, then you can buy the vote of the fifth voter, and eventually everyone will vote for you. Set of people voting for you will change as follows: ${5} \rightarrow {1, 5} \rightarrow {1, 2, 3, 5} \rightarrow {1, 2, 3, 4, 5}$.

Calculate the minimum number of coins you have to spend so that everyone votes for you.

-----Input-----

The first line contains one integer $t$ ($1 \le t \le 5000$) — the number of test cases.

The first line of each test case contains one integer $n$ ($1 \le n \le 5000$) — the number of voters.

The next $n$ lines contains the description of voters. $i$-th line contains two integers $m_i$ and $p_i$ ($1 \le p_i \le 10^9, 0 \le m_i < n$).

It is guaranteed that the sum of all $n$ over all test cases does not exceed $5000$.

-----Output-----

For each test case print one integer — the minimum number of coins you have to spend so that everyone votes for you.

-----Example-----
Input
3
3
1 5
2 10
2 8
7
0 1
3 1
1 1
6 1
1 1
4 1
4 1
6
2 6
2 3
2 8
2 7
4 4
5 5

Output
8
0
7

-----Note-----

In the first test case you have to buy vote of the third voter. Then the set of people voting for you will change as follows: ${3} \rightarrow {1, 3} \rightarrow {1, 2, 3}$.

In the second example you don't need to buy votes. The set of people voting for you will change as follows: ${1} \rightarrow {1, 3, 5} \rightarrow {1, 2, 3, 5} \rightarrow {1, 2, 3, 5, 6, 7} \rightarrow {1, 2, 3, 4, 5, 6, 7}$.

In the third test case you...

import sys
from heapq import *
#sys.stdin = open('in', 'r')
t = int(input())
for ti in range(t):
    n = int(input())
    a = []
    for i in range(n):
        mi, pi = list(map(int, input().split()))
        a.append((mi, -pi))
    a.sort()
    c = 0
    h = []
    res = 0
    for i in reversed(list(range(n))):
        heappush(h, -a[i][1])
        while c + i < a[i][0]:
            res += heappop(h)
            c += 1
    print(res)

#sys.stdout.write('YES\n')
#sys.stdout.write(f'{res}\n')
#sys.stdout.write(f'{y1} {x1} {y2} {x2}\n')


Solve in Python:
The only difference between easy and hard versions is constraints.

The BerTV channel every day broadcasts one episode of one of the $k$ TV shows. You know the schedule for the next $n$ days: a sequence of integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le k$), where $a_i$ is the show, the episode of which will be shown in $i$-th day.

The subscription to the show is bought for the entire show (i.e. for all its episodes), for each show the subscription is bought separately.

How many minimum subscriptions do you need to buy in order to have the opportunity to watch episodes of purchased shows $d$ ($1 \le d \le n$) days in a row? In other words, you want to buy the minimum number of TV shows so that there is some segment of $d$ consecutive days in which all episodes belong to the purchased shows.

-----Input-----

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

The first line of each test case contains three integers $n, k$ and $d$ ($1 \le n \le 2\cdot10^5$, $1 \le k \le 10^6$, $1 \le d \le n$). The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le k$), where $a_i$ is the show that is broadcasted on the $i$-th day.

It is guaranteed that the sum of the values of $n$ for all test cases in the input does not exceed $2\cdot10^5$.

-----Output-----

Print $t$ integers — the answers to the test cases in the input in the order they follow. The answer to a test case is the minimum number of TV shows for which you need to purchase a subscription so that you can watch episodes of the purchased TV shows on BerTV for $d$ consecutive days. Please note that it is permissible that you will be able to watch more than $d$ days in a row.

-----Example-----
Input
4
5 2 2
1 2 1 2 1
9 3 3
3 3 3 2 2 2 1 1 1
4 10 4
10 8 6 4
16 9 8
3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3

Output
2
1
4
5

-----Note-----

In the first test case to have an opportunity to watch shows for two consecutive days, you need to buy a subscription...

import math
import collections
arrK = [0] * 1000050

def cleanK(q):
    while len(q):
        arrK[q.pop()] = 0

def test():
    n, k, d = list(map(int, input().split()))
    a = list(map(int, input().split()))
    ans = math.inf
    q = collections.deque()
    sumK = 0
    for i in range(len(a)):
        q.append(a[i])
        if arrK[a[i]] == 0:
            sumK += 1
        arrK[a[i]] += 1

        if len(q) > d:
            var = q.popleft()
            arrK[var] -= 1
            if arrK[var] == 0:
                sumK -= 1
        if len(q) == d and sumK < ans:
            ans = sumK
    cleanK(q)
    print(ans)
#
# def print2d(a):
#     for i in a:
#       print(' '.join(list(map(str, i))))

t = int(input())

for i in range(t):
    test()


Solve in Python:
The only difference between easy and hard versions is constraints.

You are given a sequence $a$ consisting of $n$ positive integers.

Let's define a three blocks palindrome as the sequence, consisting of at most two distinct elements (let these elements are $a$ and $b$, $a$ can be equal $b$) and is as follows: $[\underbrace{a, a, \dots, a}_{x}, \underbrace{b, b, \dots, b}_{y}, \underbrace{a, a, \dots, a}_{x}]$. There $x, y$ are integers greater than or equal to $0$. For example, sequences $[]$, $[2]$, $[1, 1]$, $[1, 2, 1]$, $[1, 2, 2, 1]$ and $[1, 1, 2, 1, 1]$ are three block palindromes but $[1, 2, 3, 2, 1]$, $[1, 2, 1, 2, 1]$ and $[1, 2]$ are not.

Your task is to choose the maximum by length subsequence of $a$ that is a three blocks palindrome.

You have to answer $t$ independent test cases.

Recall that the sequence $t$ is a a subsequence of the sequence $s$ if $t$ can be derived from $s$ by removing zero or more elements without changing the order of the remaining elements. For example, if $s=[1, 2, 1, 3, 1, 2, 1]$, then possible subsequences are: $[1, 1, 1, 1]$, $[3]$ and $[1, 2, 1, 3, 1, 2, 1]$, but not $[3, 2, 3]$ and $[1, 1, 1, 1, 2]$.

-----Input-----

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

The first line of the test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of $a$. The second line of the test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 200$), where $a_i$ is the $i$-th element of $a$. Note that the maximum value of $a_i$ can be up to $200$.

It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$).

-----Output-----

For each test case, print the answer — the maximum possible length of some subsequence of $a$ that is a three blocks palindrome.

-----Example-----
Input
6
8
1 1 2 2 3 2 1 1
3
1 3 3
4
1 10 10 1
1
26
2
2 1
3
1 1 1

Output
7
2
4
1
1
3

from operator import itemgetter
import sys
input = sys.stdin.readline

MAX_A = 200
t = int(input())

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

    ruiseki = [[0] * MAX_A for i in range(n + 1)]
    for i in range(n):
        for j in range(MAX_A):
            ruiseki[i + 1][j] = ruiseki[i][j]
            if a[i] - 1 == j:
                ruiseki[i + 1][j] += 1

    ans = 0
    for num in set(a):
        l = 0
        r = n - 1
        cnt = 0
        while True:
            while True:
                if a[l] != num:
                    l += 1
                else:
                    break
            while True:
                if a[r] != num:
                    r -= 1
                else:
                    break
            if l == r:
                ans = max(ans, cnt + 1)
                break
            elif l > r:
                break
            cnt += 1
            tmp_max = 0
            for j in range(MAX_A):
                tmp_max = max(tmp_max, ruiseki[r][j] - ruiseki[l + 1][j])
            ans = max(ans, cnt * 2 + tmp_max)
            l += 1
            r -= 1
    print(ans)


Solve in Python:
The only difference between easy and hard versions is constraints.

You are given a sequence $a$ consisting of $n$ positive integers.

Let's define a three blocks palindrome as the sequence, consisting of at most two distinct elements (let these elements are $a$ and $b$, $a$ can be equal $b$) and is as follows: $[\underbrace{a, a, \dots, a}_{x}, \underbrace{b, b, \dots, b}_{y}, \underbrace{a, a, \dots, a}_{x}]$. There $x, y$ are integers greater than or equal to $0$. For example, sequences $[]$, $[2]$, $[1, 1]$, $[1, 2, 1]$, $[1, 2, 2, 1]$ and $[1, 1, 2, 1, 1]$ are three block palindromes but $[1, 2, 3, 2, 1]$, $[1, 2, 1, 2, 1]$ and $[1, 2]$ are not.

Your task is to choose the maximum by length subsequence of $a$ that is a three blocks palindrome.

You have to answer $t$ independent test cases.

Recall that the sequence $t$ is a a subsequence of the sequence $s$ if $t$ can be derived from $s$ by removing zero or more elements without changing the order of the remaining elements. For example, if $s=[1, 2, 1, 3, 1, 2, 1]$, then possible subsequences are: $[1, 1, 1, 1]$, $[3]$ and $[1, 2, 1, 3, 1, 2, 1]$, but not $[3, 2, 3]$ and $[1, 1, 1, 1, 2]$.

-----Input-----

The first line of the input contains one integer $t$ ($1 \le t \le 2000$) — the number of test cases. Then $t$ test cases follow.

The first line of the test case contains one integer $n$ ($1 \le n \le 2000$) — the length of $a$. The second line of the test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 26$), where $a_i$ is the $i$-th element of $a$. Note that the maximum value of $a_i$ can be up to $26$.

It is guaranteed that the sum of $n$ over all test cases does not exceed $2000$ ($\sum n \le 2000$).

-----Output-----

For each test case, print the answer — the maximum possible length of some subsequence of $a$ that is a three blocks palindrome.

-----Example-----
Input
6
8
1 1 2 2 3 2 1 1
3
1 3 3
4
1 10 10 1
1
26
2
2 1
3
1 1 1

Output
7
2
4
1
1
3

for _ in range(int(input())):
	n = int(input())
	r = list(map(int, input().split()))
	d = {i: [] for i in range(1, 27)}
	for i in range(n):
		d[r[i]].append(i)
	ans = 1
	for end in range(1, 27):
		c = 1
		while c * 2 <= len(d[end]):
			ll, rr = d[end][c - 1] + 1, d[end][-c] - 1
			dd = [0] * 27
			for p in range(ll, rr + 1):
				dd[r[p]] += 1
			ans = max(ans, max(dd) + 2 * c)
			c += 1
	print (ans)


Solve in Python:
The only difference between easy and hard versions is the size of the input.

You are given a string $s$ consisting of $n$ characters, each character is 'R', 'G' or 'B'.

You are also given an integer $k$. Your task is to change the minimum number of characters in the initial string $s$ so that after the changes there will be a string of length $k$ that is a substring of $s$, and is also a substring of the infinite string "RGBRGBRGB ...".

A string $a$ is a substring of string $b$ if there exists a positive integer $i$ such that $a_1 = b_i$, $a_2 = b_{i + 1}$, $a_3 = b_{i + 2}$, ..., $a_{|a|} = b_{i + |a| - 1}$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.

You have to answer $q$ independent queries.

-----Input-----

The first line of the input contains one integer $q$ ($1 \le q \le 2 \cdot 10^5$) — the number of queries. Then $q$ queries follow.

The first line of the query contains two integers $n$ and $k$ ($1 \le k \le n \le 2 \cdot 10^5$) — the length of the string $s$ and the length of the substring.

The second line of the query contains a string $s$ consisting of $n$ characters 'R', 'G' and 'B'.

It is guaranteed that the sum of $n$ over all queries does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$).

-----Output-----

For each query print one integer — the minimum number of characters you need to change in the initial string $s$ so that after changing there will be a substring of length $k$ in $s$ that is also a substring of the infinite string "RGBRGBRGB ...".

-----Example-----
Input
3
5 2
BGGGG
5 3
RBRGR
5 5
BBBRR

Output
1
0
3

-----Note-----

In the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".

In the second example, the substring is "BRG".

# TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!!
# TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!!
# TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!!
from sys import stdin, stdout
import collections

Q = int(input())
ans = [0]*Q
#s = input()
#N = len(s)
#arr = [int(x) for x in stdin.readline().split()]
for q in range(Q):

    N,K = [int(x) for x in stdin.readline().split()]
    s = input()
    res = N+1

    if N==1 or K==1:
        #print(0)
        ans[q] = 0
        continue

    prefix = [0]*(N+1)

    for k in range(3):
        if k==0:
            RGB = 'RGB'
        if k==1:
            RGB = 'GBR'
        if k==2:
            RGB = 'BRG'

        ssum = 0
        for i in range(N):
            letter = RGB[i%3]
            if s[i]!=letter:
                ssum += 1
            prefix[i+1] = ssum
            if i>=K-1:
                res = min(res,prefix[i+1] - prefix[i+1-K])

    ans[q] = res

print(*ans,sep='\n')


Solve in Python:
The pair of integer numbers `(m, n)`, such that `10 > m > n > 0`,  (below 10), that its sum, `(m + n)`, and rest, `(m - n)`, are perfect squares, is (5, 4).

Let's see what we have explained with numbers.
```
5 + 4 = 9 = 3²
5 - 4 = 1 = 1²
(10 > 5 > 4 > 0)
```

The pair of numbers `(m, n)`, closest to and below 50, having the property described above is `(45, 36)`.
```
45 + 36 = 81 = 9²
45 - 36 = 9 = 3²
(50 > 45 > 36 > 0)
```

With the function `closest_pair_tonum()`, that receives a number `upper_limit`, as an upper limit, we should be able to obtain the closest pair to `upper_limit`, that fulfills the property described above.

The function should return the largest pair of numbers `(m, n)`, satisfying `upper_limit > m > n > 0`. Note that we say pair A `(a0, a1)` is larger than pair B `(b0, b1)` when `a0 > b0` or `a0 == b0 and
a1 > b1`.

Let's see some cases:

```python
closest_pair_tonum(10) == (5, 4) # (m = 5, n = 4)

closest_pair_tonum(30) == (29, 20)

closest_pair_tonum(50) == (45, 36)
```

Happy coding and enjoy it!!
(We will be having a second part of a similar exercise (in some days) that will need a faster algorithm for values of `upper_limit` < 1000)

def closest_pair_tonum(upper_lim):
    sq = lambda x: int(x ** 0.5) == x ** 0.5
    for i in range(upper_lim - 1, 1, -1):
        for j in range(i - 1, 1, -1):
            if sq(i + j) * sq(i - j):
                return (i, j)


Solve in Python:
The palindromic number `595` is interesting because it can be written as the sum of consecutive squares: `6^2 + 7^2 + 8^2 + 9^2 + 10^2 + 11^2 + 12^2 = 595`.

There are exactly eleven palindromes below one-thousand that can be written as consecutive square sums. Note that `1 = 0^2 + 1^2` has not been included as this problem is concerned with the squares of positive integers.

Given an input `n`, find the count of all the numbers less than `n` that are both palindromic and can be written as the sum of consecutive squares.

For instance: `values(1000) = 11`. See test examples for more cases.

Good luck!

This Kata is borrowed from [Project Euler #125](https://projecteuler.net/problem=125)

If you like this Kata, please try:

[Fixed length palindromes](https://www.codewars.com/kata/59f0ee47a5e12962cb0000bf)

[Divisor harmony](https://www.codewars.com/kata/59bf97cd4f98a8b1cd00007e)

def values(limit):
    def is_palindrome(n):
        n = str(n)
        if len(n) in [0, 1]:
            return True
        return n[0] == n[-1] and is_palindrome(n[1:-1])

    print("Limit: {}".format(limit))
    current = 2
    totals = [1]
    list_pal = []
    while True:
        number = current ** 2 + totals[-1]
        totals = [i for i in totals if number - i < limit]
        if len(totals) == 1 and totals != [1]:
            break
        for i in totals[:-1]:
            if is_palindrome(number - i) and not (number - i) in list_pal and limit > (number - i):
                list_pal.append(number - i)
        if is_palindrome(number) and not number in list_pal and limit > number:
            list_pal.append(number)
        totals.append(number)
        current += 1
    print("Number of Palindrome in list: {}".format(len(list_pal)))
    print("List of Palindrome: {}".format(list_pal))
    return len(list_pal)


Solve in Python:
The pizza store wants to know how long each order will take. They know:

- Prepping a pizza takes 3 mins
- Cook a pizza takes 10 mins
- Every salad takes 3 mins to make
- Every appetizer takes 5 mins to make
- There are 2 pizza ovens
- 5 pizzas can fit in a oven
- Prepping for a pizza must be done before it can be put in the oven
- There are two pizza chefs and one chef for appitizers and salads combined
- The two pizza chefs can work on the same pizza

Write a function, order, which will tell the company how much time the order will take.

See example tests for details.

from math import ceil

def order(pizzas, salads, appetizers):
    tp = 3 * pizzas / 2 + 10 * math.ceil(pizzas / 10)
    ts = 3 * salads + 5 * appetizers
    return max(tp, ts)


Solve in Python:
The power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps:

if x is even then x = x / 2
if x is odd then x = 3 * x + 1

For example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 (3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1).
Given three integers lo, hi and k. The task is to sort all integers in the interval [lo, hi] by the power value in ascending order, if two or more integers have the same power value sort them by ascending order.
Return the k-th integer in the range [lo, hi] sorted by the power value.
Notice that for any integer x (lo <= x <= hi) it is guaranteed that x will transform into 1 using these steps and that the power of x is will fit in 32 bit signed integer.

Example 1:
Input: lo = 12, hi = 15, k = 2
Output: 13
Explanation: The power of 12 is 9 (12 --> 6 --> 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1)
The power of 13 is 9
The power of 14 is 17
The power of 15 is 17
The interval sorted by the power value [12,13,14,15]. For k = 2 answer is the second element which is 13.
Notice that 12 and 13 have the same power value and we sorted them in ascending order. Same for 14 and 15.

Example 2:
Input: lo = 1, hi = 1, k = 1
Output: 1

Example 3:
Input: lo = 7, hi = 11, k = 4
Output: 7
Explanation: The power array corresponding to the interval [7, 8, 9, 10, 11] is [16, 3, 19, 6, 14].
The interval sorted by power is [8, 10, 11, 7, 9].
The fourth number in the sorted array is 7.

Example 4:
Input: lo = 10, hi = 20, k = 5
Output: 13

Example 5:
Input: lo = 1, hi = 1000, k = 777
Output: 570

Constraints:

1 <= lo <= hi <= 1000
1 <= k <= hi - lo + 1

class Solution:
    def getKth(self, lo: int, hi: int, k: int) -> int:
        powers = []
        for i in range(lo, hi+1):
            index = i
            steps = 0
            while i != 1:
                if i % 2 == 0:
                    i = i / 2
                    steps += 1
                else:
                    i = 3 * i + 1
                    steps += 1
            powers.append([steps, index])
        sortPowers = sorted(powers)
        return sortPowers[k-1][1]


Solve in Python:
The prime `149` has 3 permutations which are also primes: `419`, `491` and `941`.

There are 3 primes below `1000` with three prime permutations:
```python
149 ==> 419 ==> 491 ==> 941
179 ==> 197 ==> 719 ==> 971
379 ==> 397 ==> 739 ==> 937
```

But there are 9 primes below `1000` with two prime permutations:
```python
113 ==> 131 ==> 311
137 ==> 173 ==> 317
157 ==> 571 ==> 751
163 ==> 613 ==> 631
167 ==> 617 ==> 761
199 ==> 919 ==> 991
337 ==> 373 ==> 733
359 ==> 593 ==> 953
389 ==> 839 ==> 983
```

Finally, we can find 34 primes below `1000` with only one prime permutation:
```python
[13, 17, 37, 79, 107, 127, 139, 181, 191, 239, 241, 251, 277, 281, 283, 313, 347, 349, 367, 457, 461, 463, 467, 479, 563, 569, 577, 587, 619, 683, 709, 769, 787, 797]
```

Each set of permuted primes are represented by its smallest value, for example the set `149, 419, 491, 941` is represented by `149`, and the set has 3 permutations.

**Notes**
* the original number (`149` in the above example) is **not** counted as a permutation;
* permutations with leading zeros are **not valid**

## Your Task

Your task is to create a function that takes two arguments:
* an upper limit (`n_max`) and
* the number of prime permutations (`k_perms`) that the primes should generate **below** `n_max`

The function should return the following three values as a list:
* the number of permutational primes below the given limit,
* the smallest prime such prime,
* and the largest such prime

If no eligible primes were found below the limit, the output should be `[0, 0, 0]`

## Examples

Let's see how it would be with the previous cases:
```python
permutational_primes(1000, 3) ==> [3, 149, 379]
''' 3 primes with 3 permutations below 1000, smallest: 149, largest: 379 '''

permutational_primes(1000, 2) ==> [9, 113, 389]
''' 9 primes with 2 permutations below 1000, smallest: 113, largest: 389 '''

permutational_primes(1000, 1) ==> [34, 13, 797]
''' 34 primes with 1 permutation below 1000, smallest: 13, largest: 797 '''
```

Happy coding!!

from itertools import islice, count

#Python cookbook
def eratosthenes():
    D = {}
    yield 2
    for q in islice(count(3), 0, None, 2):
        p = D.pop(q, None)
        if p is None:
            D[q*q] = q
            yield q
        else:
            x = p + q
            while x in D or not (x&1):
                x += p
            D[x] = p

def find_prime_kPerm(n, kPerm):
    d = {}
    for p in eratosthenes():
        if p > n: break
        k = ''.join(sorted(c for c in str(p)))
        d[k] = d.get(k, []) + [p]

    r = [min(v) for v in d.values() if len(v) == kPerm+1]
    return [len(r), min(r) if r else 0, max(r) if r else 0]


Solve in Python:
The prime number sequence starts with: `2,3,5,7,11,13,17,19...`. Notice that `2` is in position `one`.

`3` occupies position `two`, which is a prime-numbered position. Similarly, `5`, `11` and `17` also occupy prime-numbered positions. We shall call primes such as `3,5,11,17` dominant primes because they occupy prime-numbered positions in the prime number sequence. Let's call this `listA`.

As you can see from listA, for the prime range `range(0,10)`, there are `only two` dominant primes (`3` and `5`) and the sum of these primes is: `3 + 5 = 8`.

Similarly, as shown in listA, in the `range (6,20)`, the dominant primes in this range are `11` and `17`, with a sum of `28`.

Given a `range (a,b)`, what is the sum of dominant primes within that range? Note that  `a <= range <= b` and `b` will not exceed `500000`.

Good luck!

If you like this Kata, you will enjoy:

[Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3)

[Sum of prime-indexed elements](https://www.codewars.com/kata/59f38b033640ce9fc700015b)

[Divisor harmony](https://www.codewars.com/kata/59bf97cd4f98a8b1cd00007e)

from itertools import compress, takewhile
import numpy as np

s = np.ones(500000)
s[:2] = s[4::2] = 0
for i in range(3, int(len(s)**0.5)+1, 2):
    if s[i]:
        s[i*i::i] = 0
primes = list(compress(range(len(s)), s))
xs = [primes[i-1] for i in takewhile(lambda x: x < len(primes), primes)]

def solve(a,b):
    return sum(xs[np.searchsorted(xs, a):np.searchsorted(xs, b, side='right')])


Solve in Python:
The prime numbers are not regularly spaced. For example from `2` to `3` the gap is `1`.
From `3` to `5` the gap is `2`. From `7` to `11` it is `4`.
Between 2 and 50 we have the following pairs of 2-gaps primes:
`3-5, 5-7, 11-13, 17-19, 29-31, 41-43`

A prime gap of length n is a run of n-1 consecutive composite numbers between two **successive** primes (see: http://mathworld.wolfram.com/PrimeGaps.html).

We will write a function gap with parameters:

`g` (integer >= 2) which indicates the gap we are looking for

`m` (integer > 2) which gives the start of the search (m inclusive)

`n` (integer >= m) which gives the end of the search (n inclusive)

In the example above `gap(2, 3, 50)` will return `[3, 5] or (3, 5) or {3, 5}` which is the first pair between 3 and 50 with a 2-gap.

So this function should return the **first** pair of two prime numbers spaced with a gap of `g`
between the limits `m`, `n` if these numbers exist otherwise `nil or null or None or Nothing` (depending on the language).

In C++ return in such a case `{0, 0}`. In F# return `[||]`. In Kotlin return `[]`

#Examples:
`gap(2, 5, 7) --> [5, 7] or (5, 7) or {5, 7}`

`gap(2, 5, 5) --> nil. In C++ {0, 0}. In F# [||]. In Kotlin return `[]`

`gap(4, 130, 200) --> [163, 167] or (163, 167) or {163, 167}`

([193, 197] is also such a 4-gap primes between 130 and 200 but it's not the first pair)

`gap(6,100,110) --> nil or {0, 0}` : between 100 and 110 we have `101, 103, 107, 109` but `101-107`is not a
6-gap because there is `103`in between and `103-109`is not a 6-gap because there is `107`in between.

# Note for Go
For Go: nil slice is expected when there are no gap between m and n.
Example: gap(11,30000,100000) --> nil

#Ref
https://en.wikipedia.org/wiki/Prime_gap

from math import floor

def gap(g, m, n):
    for number in range(m, n+1):
        is_prime = True
        for divisor in range(2, floor(number**0.5)+1):
            if number % divisor == 0:
                is_prime = False
                break

        if is_prime:
            if 'prev_prime' not in locals():
                prev_prime = number
            else:
                if number - prev_prime == g:
                    return [prev_prime, number]
                else:
                    prev_prime = number


Solve in Python:
The prime numbers are not regularly spaced. For example from `2` to `3` the step is `1`.
From `3` to `5` the step is `2`. From `7` to `11` it is `4`.
Between 2 and 50 we have the following pairs of 2-steps primes:

`3, 5 - 5, 7, - 11, 13, - 17, 19, - 29, 31, - 41, 43`

We will write a function `step` with parameters:

- `g` (integer >= 2) which indicates the step we are looking for,

- `m` (integer >= 2) which gives the start of the search (m inclusive),

- `n` (integer >= m) which gives the end of the search (n inclusive)

In the example above `step(2, 2, 50)` will return `[3, 5]` which is the first pair between 2 and 50 with a 2-steps.

So this function should return the **first** pair of the two prime numbers spaced with a step of `g`
between the limits `m`, `n` if these g-steps prime numbers exist otherwise `nil` or `null` or `None` or `Nothing` or `[]` or `"0, 0"` or `{0, 0}` or `0 0`(depending on the language).

#Examples:

-

`step(2, 5, 7) --> [5, 7] or (5, 7) or {5, 7} or "5 7"`

`step(2, 5, 5) --> nil or ... or [] in Ocaml or {0, 0} in C++`

`step(4, 130, 200) --> [163, 167] or (163, 167) or {163, 167}`

- **See more examples for your language in "RUN"**

- Remarks:

([193, 197] is also such a 4-steps primes between 130 and 200 but it's not the first pair).

`step(6, 100, 110) --> [101, 107]` though there is a prime between 101 and 107 which is 103; the pair 101-103 is a 2-step.

#Notes:
The idea of "step" is close to that of "gap" but it is not exactly the same. For those interested they can have a look
at .

A "gap" is more restrictive: there must be no primes in between
(101-107 is a "step" but not a "gap". Next kata will be about "gaps":-).

For Go: nil slice is expected when there are no `step` between m and n.
Example: step(2,4900,4919) --> nil

def is_prime(n):
    for i in range(2,int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

def step(g, m, n):
    for i in range(m, n - g):
        if is_prime(i) and is_prime(i + g):
            return [i,i+g]
    return None


Solve in Python:
The principal of a school likes to put challenges to the students related with finding words of certain features.
One day she said: "Dear students, the challenge for today is to find a word that has only one vowel and seven consonants but cannot have the letters "y" and "m". I'll give a special award for the first student that finds it." One of the students used his dictionary and spent all the night without sleeping, trying in vain to find the word. The next day, the word had not been found yet.
This student observed that the principal has a pattern in the features for the wanted words:

- The word should have **n** vowels, may be repeated, for example: in "engineering", n = 5.

- The word should have **m** consonants, may be repeated also: in "engineering", m = 6.

- The word should not have some forbidden letters (in an array), forbid_letters

You will be provided with a list of words, WORD_LIST(python/crystal), wordList(javascript), wordList (haskell), $word_list(ruby), and you have to create the function, ```wanted_words()```, that receives the three arguments in the order given above, ```wanted_words(n, m, forbid_list)```and output an array with the word or an array, having the words in the order given in the pre-loaded list, in the case of two or more words were found.

Let's see some cases:

```python
wanted_words(1, 7, ["m", "y"]) == ["strength"]
wanted_words(3, 7, ["m", "y"]) == ['afterwards', 'background', 'photograph', 'successful', 'understand']
```

For cases where no words are found the function will output an empty array.

```python
wanted_words(3, 7, ["a", "s" , "m", "y"]) == []
```

Help our student to win this and the next challenges of the school. He needs to sure about a suspect that he has. That many times there are no solutions for what the principal is asking for.
All words have its letters in lowercase format.
Enjoy it!

def wanted_words(n, m, forbid_let):
    result = []
    for word in WORD_LIST:
        if set(forbid_let) & set(word):
            continue
        vowels = sum(1 for c in word if c in "aeiou")
        if vowels == n and len(word) == m + n:
            result.append(word)
    return result


Solve in Python:
The professional Russian, Dmitri, from the popular youtube channel FPSRussia has hired you to help him move his arms cache between locations without detection by the authorities.  Your job is to write a Shortest Path First (SPF) algorithm that will provide a route with the shortest possible travel time between waypoints, which will minimize the chances of detection.  One exception is that you can't travel through the same waypoint twice.  Once you've been seen there is a higher chance of detection if you travel through that waypoint a second time.

Your function shortestPath will take three inputs, a topology/map of the environment, along with a starting point, and an ending point.  The topology will be a dictionary with the keys being the different waypoints.  The values of each entry will be another dictionary with the keys being the adjacent waypoints, and the values being the time it takes to travel to that waypoint.

Take the following topology as an example:

     topology = {'a' : {'b': 10, 'c': 20},
                 'b' : {'a': 10, 'c': 20},
                 'c' : {'a': 10, 'b': 20} }

In this example, waypoint 'a' has two adjacent waypoints, 'b' and 'c'.  And the time it takes to travel from 'a' to 'b' is 10 minutes, and from 'a' to 'c' is 20 minutes.  It's important to note that the time between these waypoints is one way travel time and can be different in opposite directions.  This is highlighted in the example above where a->c takes 20 minutes, but c->a takes 10 minutes.

The starting and ending points will passed to your function as single character strings such as 'a' or 'b', which will match a key in your topology.

The return value should be in the form of a list of lists of waypoints that make up the shortest travel time.  If there multiple paths that have equal travel time, then you should choose the path with the least number of waypoints.  If there are still multiple paths with equal travel time and number of waypoints, then you should return a list of lists with the multiple options. For...

from heapq import heappush as push, heappop as pop

def shortestPath(topology, startPoint, endPoint):
    current, res = [], (float('inf'), None, [])
    push(current, (0, 1, [startPoint]))
    while current:
        time, size, path = pop(current)
        if time > res[0] or time == res[0] and size > res[1]:
            return res[2]
        if path[-1] == endPoint:
            if time < res[0] or size < res[1]:
                res = (time, size, [path])
            else:
                res[2].append(path)
        else:
            for k,v in topology[path[-1]].items():
                if k not in path:
                    push(current, (time+v, size+1, path+[k]))
    return "No path"


Solve in Python:
The purpose of this kata is to work out just how many bottles of duty free whiskey you would have to buy such that the saving over the normal high street price would effectively cover the cost of your holiday.

You will be given the high street price (normPrice), the duty free discount (discount) and the cost of the holiday.

For example, if a bottle cost £10 normally and the discount in duty free was 10%, you would save £1 per bottle. If your holiday cost £500, the answer you should return would be 500.

All inputs will be integers. Please return an integer. Round down.

def duty_free(price, discount, holiday_cost):
    disc_price = (discount/100) * price
    return holiday_cost // disc_price


Solve in Python:
The purpose of this problem is to verify whether the method you are using to read input data is sufficiently fast to handle problems branded with the enormous Input/Output warning. You are expected to be able to process at least 2.5MB of input data per second at runtime.

-----Input-----
The input begins with two positive integers n k (n, k<=107). The next n lines of input contain one positive integer ti, not greater than 109, each.

-----Output-----
Write a single integer to output, denoting how many integers ti are divisible by k.

-----Example-----
Input:
7 3
1
51
966369
7
9
999996
11

Output:
4

n,k=map(int,input().split())
ans=0
for i in range(n):
    t=int(input())
    if t%k==0:
        ans+=1
print(ans)


Solve in Python:
The purpose of this series is developing understanding of stastical problems in AS and A level maths. Let's get started with a simple concept in statistics: Mutually exclusive events.

The probability of an OR event is calculated by the following rule:

`P(A || B) = P(A) + P(B) - P(A && B)`

The probability of event A or event B happening is equal to the probability of event A plus the probability of event B minus the probability of event A and event B happening simultaneously.

Mutually exclusive events are events that cannot happen at the same time. For example, the head and tail results of a toin coss are mutually exclusive because they can't both happen at once. Thus, the above example for a coin toss would look like this:

`P(H || T) = P(H) + P(T) - P(H && T)`

Note that the probaility of tossing a coin and the result being both head and tails is 0.

`P(H || T) = (0.5) + (0.5) - (0)`
`P(H || T) = 1`

Thus the probability of a coin toss result being a heads or a tails is 1, in other words: certain.

Your task:

You are going to have to work out the probability of one roll of a die returning two given outcomes, or rolls. Given that dice rolls are mutually exclusive, you will have to implement the above forumala. To make this interesting (this is a coding challenge after all), these dice are not fair and thus the probabilites of receiving each roll is different.

You will be given a two-dimensional array containing the number each of the results (1-6) of the die and the probability of that roll for example `[1 , 0.23]` as well as the two rolls for example `1` and `5`.

Given the two roll probabilities to calculate, return the probability of a single roll of the die returning either. If the total probability of the six rolls doesn't add up to one, there is a problem with the die; in this case, return null.
Return your result as a string to two decimal places.

Example below:

`1 : 1/6`

`2 : 1/6`

`3 : 1/6`

`4 : 1/6`

`5 : 1/6`

`6 : 1/6`

If asked for the rolls `1` and `2` then you would need to sum the...

def mutually_exclusive(dice, call1, call2):
    prob_of_each_roll = []
    for roll in dice:
        prob_of_each_roll.append(roll[1])
        if roll[0] == call1:
            p1 = roll[1]
        if roll[0] == call2:
            p2 = roll[1]
    if sum(prob_of_each_roll) != 1:
        return
    else:
        total_prob = round((p1 + p2),2)
        return ("{:.2f}".format(total_prob))


Solve in Python:
The queen can be moved any number of unoccupied squares in a straight line vertically, horizontally, or diagonally, thus combining the moves of the rook and bishop. The queen captures by occupying the square on which an enemy piece sits. (wikipedia: https://en.wikipedia.org/wiki/Queen_(chess)).

## Task:
Write a function ```availableMoves(position)``` which returns possibly moves of chess queen. Returned value should be an ```array``` with possible moves sorted alphabetically, exluded starting position.

For example when input position is ```A1``` return value should be:

```["A2", "A3", "A4", "A5", "A6", "A7", "A8", "B1", "B2", "C1", "C3", "D1", "D4", "E1", "E5", "F1", "F6", "G1", "G7", "H1", "H8"]```

```
     A   B   C   D   E   F   G   H
   + - + - + - + - + - + - + - + - +
1  | Q | x | x | x | x | x | x | x |
   + - + - + - + - + - + - + - + - +
2  | x | x |   |   |   |   |   |   |
   + - + - + - + - + - + - + - + - +
3  | x |   | x |   |   |   |   |   |
   + - + - + - + - + - + - + - + - +
4  | x |   |   | x |   |   |   |   |
   + - + - + - + - + - + - + - + - +
5  | x |   |   |   | x |   |   |   |
   + - + - + - + - + - + - + - + - +
6  | x |   |   |   |   | x |   |   |
   + - + - + - + - + - + - + - + - +
7  | x |   |   |   |   |   | x |   |
   + - + - + - + - + - + - + - + - +
8  | x |   |   |   |   |   |   | x |
   + - + - + - + - + - + - + - + - +

Q = queen
x = available move
```

## Input:
- input position can be any type (array, number, string and so on). If input position is not a string then return empty array.
- valid input position is one letter from ```A``` to ```H``` with number from ```1``` to ```8```, for example ```A1```, ```C8```, ```B3```. If input is invalid (for example ```A10``` or ```H0```) then return empty array.

from_pos = lambda s: (ord(s[0])-65, int(s[1])-1)
to_pos = lambda i,j: f"{chr(i+65)}{j+1}"

def available_moves(position):
    # That part is always just annoying
    if not (isinstance(position, str)
            and len(position) == 2
            and position[0] in "ABCDEFGH"
            and position[1] in "12345678"): return []

    (x, y), res = from_pos(position), []
    for k,l in ((0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)):
        i, j = y+k, x+l
        while 0 <= i < 8 and 0 <= j < 8:
            res.append(to_pos(j, i))
            i, j = i+k, j+l
    return sorted(res)


Solve in Python:
The rgb function is incomplete. Complete it so that passing in RGB decimal values will result in a hexadecimal representation being returned. Valid decimal values for RGB are 0 - 255. Any values that fall out of that range must be rounded to the closest valid value.

Note: Your answer should always be 6 characters long, the shorthand with 3 will not work here.

The following are examples of  expected output values:
```python
rgb(255, 255, 255) # returns FFFFFF
rgb(255, 255, 300) # returns FFFFFF
rgb(0,0,0) # returns 000000
rgb(148, 0, 211) # returns 9400D3
```
```if:nasm

char \*rgb(int r, int g, int b, char \*outp)

```

def rgb(*args):
    return ''.join(map(lambda x: '{:02X}'.format(min(max(0, x), 255)), args));


Solve in Python:
The round carousel consists of $n$ figures of animals. Figures are numbered from $1$ to $n$ in order of the carousel moving. Thus, after the $n$-th figure the figure with the number $1$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $i$-th figure equals $t_i$. [Image] The example of the carousel for $n=9$ and $t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$.

You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.

Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $k$ distinct colors, then the colors of figures should be denoted with integers from $1$ to $k$.

-----Input-----

The input contains one or more test cases.

The first line contains one integer $q$ ($1 \le q \le 10^4$) — the number of test cases in the test. Then $q$ test cases follow. One test case is given on two lines.

The first line of the test case contains one integer $n$ ($3 \le n \le 2 \cdot 10^5$) — the number of figures in the carousel. Figures are numbered from $1$ to $n$ in order of carousel moving. Assume that after the $n$-th figure the figure $1$ goes.

The second line of the test case contains $n$ integers $t_1, t_2, \dots, t_n$ ($1 \le t_i \le 2 \cdot 10^5$), where $t_i$ is the type of the animal of the $i$-th figure.

The sum of $n$ over all test cases does not exceed $2\cdot10^5$.

-----Output-----

Print $q$ answers, for each test case print two lines.

In the first line print one integer $k$ — the minimum possible number of distinct colors of figures.

In the second line print $n$ integers $c_1, c_2, \dots, c_n$ ($1 \le c_i \le k$), where $c_i$ is the color of the $i$-th figure. If...

for _ in range(int(input())):
    n=int(input())
    a=list(map(int,input().split()))
    ans=[1]*(n)
    f=1
    ind=0
    if a[0]==a[1]:
        ind=1
    for i in range(1,n):
        if a[i]==a[i-1]:
            ans[i]=ans[i-1]
        else:
            ans[i]=3-ans[i-1]
            f=2
        if a[i]==a[(i+1)%n]:
            ind=(i+1)%n

    if a[0]!=a[-1] and ans[-1]==ans[0]:
        ans[-1]=3
        f=3

    # print(ind)

    if f==3 and ind:
        for i in range(ind,n):
            ans[i]=3-ans[i]
        ans[-1]=3-ans[0]

    print(len(set(ans)))

    # if f:
    #     print(3)

    # else:
    #     print(2)
    print(*ans)


Solve in Python:
The sequence of $m$ integers is called the permutation if it contains all integers from $1$ to $m$ exactly once. The number $m$ is called the length of the permutation.

Dreamoon has two permutations $p_1$ and $p_2$ of non-zero lengths $l_1$ and $l_2$.

Now Dreamoon concatenates these two permutations into another sequence $a$ of length $l_1 + l_2$. First $l_1$ elements of $a$ is the permutation $p_1$ and next $l_2$ elements of $a$ is the permutation $p_2$.

You are given the sequence $a$, and you need to find two permutations $p_1$ and $p_2$. If there are several possible ways to restore them, you should find all of them. (Note that it is also possible that there will be no ways.)

-----Input-----

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

Each test case contains two lines. The first line contains one integer $n$ ($2 \leq n \leq 200\,000$): the length of $a$. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq n-1$).

The total sum of $n$ is less than $200\,000$.

-----Output-----

For each test case, the first line of output should contain one integer $k$: the number of ways to divide $a$ into permutations $p_1$ and $p_2$.

Each of the next $k$ lines should contain two integers $l_1$ and $l_2$ ($1 \leq l_1, l_2 \leq n, l_1 + l_2 = n$), denoting, that it is possible to divide $a$ into two permutations of length $l_1$ and $l_2$ ($p_1$ is the first $l_1$ elements of $a$, and $p_2$ is the last $l_2$ elements of $a$). You can print solutions in any order.

-----Example-----
Input
6
5
1 4 3 2 1
6
2 4 1 3 2 1
4
2 1 1 3
4
1 3 3 1
12
2 1 3 4 5 6 7 8 9 1 10 2
3
1 1 1

Output
2
1 4
4 1
1
4 2
0
0
1
2 10
0

-----Note-----

In the first example, two possible ways to divide $a$ into permutations are $\{1\} + \{4, 3, 2, 1\}$ and $\{1,4,3,2\} + \{1\}$.

In the second example, the only way to divide $a$ into permutations is $\{2,4,1,3\} + \{2,1\}$.

In the third example, there are no possible ways.

def per(X):
    S=set(X)
    if not len(X)==len(S):
        return False
    for i in range(1,len(X)+1):
        if i not in S: return False
    return True
for y in range(int(input())):
    n=int(input())
    L=list(map(int,input().split()))
    m=max(L)
    r=[]
    if n!=m:
        if per(L[:m]) and per(L[m:]):
            r.append((m,n-m))
        if per(L[-m:]) and per(L[:-m]):
            r.append((n-m,m))
    r=list(set(r))
    print(len(r))
    for a,b in r:
        print(a,b)


Solve in Python:
The set [1,2,3,...,n] contains a total of n! unique permutations.

By listing and labeling all of the permutations in order, we get the following sequence for n = 3:

       "123"
       "132"
       "213"
       "231"
       "312"
       "321"

Given n and k, return the kth permutation sequence.

Note:

       Given n will be between 1 and 9 inclusive.
       Given k will be between 1 and n! inclusive.

Example 1:

Input: n = 3, k = 3
Output: "213"

Example 2:

Input: n = 4, k = 9
Output: "2314"

class Solution:
     def getPermutation(self, n, k):
         """
         :type n: int
         :type k: int
         :rtype: str
         """
         import math
         nums = list(range(1, n+1))
         ans = ''

         k = k - 1 #make sure the divmod result fail in [0, n-1] instead of [1, n]
         while n > 0:
             n = n - 1
             index, k = divmod(k, math.factorial(n))
             ans = ans + str(nums[index])
             nums.remove(nums[index])

         return ans


Solve in Python:
The snail crawls up the column. During the day it crawls up some distance. During the night she sleeps, so she slides down for some distance (less than crawls up during the day).

Your function takes three arguments:
1. The height of the column (meters)
2. The distance that the snail crawls during the day (meters)
3. The distance that the snail slides down during the night (meters)

Calculate number of day when the snail will reach the top of the column.

from numpy import ceil
def snail(column, day, night):
    return max(ceil((column-day)/(day-night)), 0) + 1


Solve in Python:
The snakes want to build a temple for Lord Cobra. There are multiple strips of land that they are looking at, but not all of them are suitable. They need the strip of land to resemble a coiled Cobra. You need to find out which strips do so.
Formally, every strip of land, has a length. Suppose the length of the i-th strip is is Ni, then there will be Ni integers, Hi1, Hi2, .. HiNi, which represent the heights of the ground at various parts of the strip, in sequential order. That is, the strip has been divided into Ni parts and the height of each part is given. This strip is valid, if and only if all these conditions are satisfied:
- There should be an unique 'centre' part. This is where the actual temple will be built. By centre, we mean that there should be an equal number of parts to the left of this part, and to the right of this part.
- Hi1 = 1
- The heights keep increasing by exactly 1, as you move from the leftmost part, to the centre part.
- The heights should keep decreasing by exactly 1, as you move from the centre part to the rightmost part. Note that this means that HiNi should also be 1.
Your job is to look at every strip and find if it's valid or not.

-----Input-----
- The first line contains a single integer, S, which is the number of strips you need to look at. The description of each of the S strips follows
- The first line of the i-th strip's description will contain a single integer: Ni, which is the length and number of parts into which it has been divided.
- The next line contains Ni integers: Hi1, Hi2, .., HiNi. These represent the heights of the various parts in the i-th strip.

-----Output-----
- For each strip, in a new line, output "yes" if is a valid strip, and "no", if it isn't.

-----Constraints-----
- 1 ≤ S ≤ 100
- 3 ≤ Ni ≤ 100
- 1 ≤ Hij ≤ 100

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

Output:
yes
no
no
no
yes
no
no

-----Explanation-----
In the first strip, all the conditions are satisfied, hence it is...

t = int(input())
for i in range(t):
 n = int(input())
 a = list(map(int, input().split()))
 valid= False
 if n%2==1 and a[0]==1:
  for j in range(int((n-1)/2)):
   if a[j]==a[n-1-j]:
    valid=True
   if a[j] +1 != a[j+1]:
    valid=False
   if a[n-1-j] != a[n-2-j] - 1:
    valid = False
 if(valid):
  print('yes')
 else:
  print('no')


Solve in Python:
The special score(ssc) of an array of integers will be the sum of each integer multiplied by its corresponding index plus one in the array.

E.g.: with the array  ```[6, 12, -1]```
```
arr =   [6,      12,       -1 ]
ssc =   1*6  +  2* 12 +  3.(*1) = 6 + 24 - 3 = 27
```
The array given in the example has six(6) permutations and are with the corresponding ssc:
```
Permutations      Special Score (ssc)
[6, 12, -1]      1*6 + 2*12 + 3*(-1) = 27
[6, -1, 12]       1*6 + 2*(-1) + 3*12 = 40
[-1, 6, 12]       1*(-1) + 2*6 + 3*12 = 47
[-1, 12, 6]       1*(-1) + 2*12 + 3*6 = 41
[12, -1, 6]       1*12 + 2*(-1) + 3*6 = 28
[12, 6, -1]       1*12 + 2*6 + 3*(-1) = 21
```
The total sum of the ```ssc's``` of all the possible permutations is: ```27 + 40 + 47 + 41 + 28 + 21 = 204```

The maximum value for the ```ssc``` is ```47```.

The minimum value for the ```ssc``` is ```21```.

We need a special function ```ssc_forperm()``` that receives an array of uncertain number of elements (the elements may occur more than once) and may output a list of dictionaries with the following data:
```
[{"total perm":__}, {"total ssc": ___}, {"max ssc": __}, {"min ssc": __}]
```
For the example we have above will be:
```python
ssc_forperm([6, 12, -1]) = [{"total perm":6}, {"total ssc:204}, {"max ssc":47}, {"min ssc":21}]
```
You may assume that you will never receive an empty array.

Also you will never receive an array with the same element in all the positions like [1, 1, 1, 1 ,1], but you may have elements occuring twice or more like [1, 1, 1, 2, 3]

Enjoy it!!

from itertools import permutations

def ssc_forperm(lst):
    scores = [sum(i*n for i, n in enumerate(p, 1)) for p in set(permutations(lst))]
    return [{"total perm": len(scores)}, {"total ssc": sum(scores)}, {"max ssc": max(scores)}, {"min ssc": min(scores)}]


Solve in Python:
The sports centre needs repair. Vandals have been kicking balls so hard into the roof that some of the tiles have started sticking up. The roof is represented by r.

As a quick fix, the committee have decided to place another old roof over the top, if they can find one that fits. This is your job.

A 'new' roof (f) will fit if it currently has a hole in it at the location where the old roof has a tile sticking up.

Sticking up tiles are represented by either '\\' or '/'. Holes in the 'new' roof are represented by spaces (' '). Any other character can not go over a sticking up tile.

Return true if the new roof fits, false if it does not.

def roof_fix(f,r):
    for u,y in zip(f,r):
        if u.isalpha() and y in '/\\': return False
    return True


Solve in Python:
The squarefree part of a positive integer is the largest divisor of that integer which itself has no square factors (other than 1). For example, the squareefree part of 12 is 6, since the only larger divisor is 12, and 12 has a square factor (namely, 4).

Your challenge, should you choose to accept it, is to implement a `squareFreePart` function which accepts a number `n` and returns the squarefree part of `n`.

In the case that `n = 1`, your function should return 1. Also, if the input doesn't make sense (e.g. if it is not a positive integer), the function should return `null/None`.

Here are some examples:

```python
square_free_part(2) # returns 2
square_free_part(4) # returns 2
square_free_part(24) # returns 6, since any larger divisor is divisible by 4, which is a square
square_free_part("hi") # returns None
square_free_part(0) # returns None
```

Good luck!

def square_free_part(n):
    import math
    lst = []
    squares = []
    x = []
    if isinstance(n, int):
        if n > 1:
            for i in range(2, n // 2 + 1):
                if n % i == 0:
                    lst.append(i)
            lst.append(n)
            lst.reverse()
            for elem in lst:
                if math.sqrt(elem).is_integer():
                    squares.append(elem)
            for i in lst:
                for j in squares:
                    if i % j == 0:
                        break
                else:
                    x.append(i)
            if len(x) > 0:
                return x[0]
            else:
                return lst[0]
        elif n is 1:
            return 1
        else:
            return None
    else:
        return None


Solve in Python:
The statement of this problem is the same as the statement of problem C1. The only difference is that, in problem C1, $n$ is always even, and in C2, $n$ is always odd.

You are given a regular polygon with $2 \cdot n$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $1$. Let's name it as $2n$-gon.

Your task is to find the square of the minimum size such that you can embed $2n$-gon in the square. Embedding $2n$-gon in the square means that you need to place $2n$-gon in the square in such way that each point which lies inside or on a border of $2n$-gon should also lie inside or on a border of the square.

You can rotate $2n$-gon and/or the square.

-----Input-----

The first line contains a single integer $T$ ($1 \le T \le 200$) — the number of test cases.

Next $T$ lines contain descriptions of test cases — one per line. Each line contains single odd integer $n$ ($3 \le n \le 199$). Don't forget you need to embed $2n$-gon, not an $n$-gon.

-----Output-----

Print $T$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $2n$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $10^{-6}$.

-----Example-----
Input
3
3
5
199

Output
1.931851653
3.196226611
126.687663595

import math
T = int(input())

while T !=0:
    n = int(input())

    side = math.sin(math.pi/(4*n)) * 2
    print(1/side)

    T -= 1


Solve in Python:
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $n$ is always even, and in C2, $n$ is always odd.

You are given a regular polygon with $2 \cdot n$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $1$. Let's name it as $2n$-gon.

Your task is to find the square of the minimum size such that you can embed $2n$-gon in the square. Embedding $2n$-gon in the square means that you need to place $2n$-gon in the square in such way that each point which lies inside or on a border of $2n$-gon should also lie inside or on a border of the square.

You can rotate $2n$-gon and/or the square.

-----Input-----

The first line contains a single integer $T$ ($1 \le T \le 200$) — the number of test cases.

Next $T$ lines contain descriptions of test cases — one per line. Each line contains single even integer $n$ ($2 \le n \le 200$). Don't forget you need to embed $2n$-gon, not an $n$-gon.

-----Output-----

Print $T$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $2n$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $10^{-6}$.

-----Example-----
Input
3
2
4
200

Output
1.000000000
2.414213562
127.321336469

import math

def sqare_size(n):
    return 1/math.tan(math.pi/(2*n))

t = int(input())
for _ in range(t):
    print(sqare_size(int(input())))


Solve in Python:
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P   A   H   N
A P L S I I G
Y   I   R

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

string convert(string s, int numRows);

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"

Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

P     I    N
A   L S  I G
Y A   H R
P     I

class Solution:
     def convert(self, s, numRows):
         """
         :type s: str
         :type numRows: int
         :rtype: str
         """
         if numRows == 1:
             return s
         count = len(s)
         if count <= 1:
             return s

         result = []
         deltSmall = numRows - 1
         deltBig = 2 * deltSmall
         for i in range(0, numRows):
             k = i
             if i == 0 or i == deltSmall:
                 while k < count:
                     result.append(s[k])
                     k += deltBig
             else:
                 while k < count:
                     top = k - k % deltSmall
                     bottom = top + deltSmall
                     result.append(s[k])
                     nextk = 2 * bottom - k
                     if nextk < count:
                         result.append(s[nextk])
                     k += deltBig

         return "".join(result)


Solve in Python:
The students of Codechef Middle School are visiting an amusement park. The children want to go on a ride, however, there is a minimum height requirement of $X$ cm. Determine if the children are eligible to go on the ride.
Print "Yes" if they are eligible, "No" otherwise.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, two integers $H$ which is a child's height in cm and $X$ which is the minimum permissible height.

-----Output:-----
For each testcase, output in a single line $"Yes"$ or $"No"$. You cannot give your answer as "YeS", "YES", "yes" or any other variation.

-----Constraints-----
- $1 \leq T \leq 10^4$
- $50 \leq H \leq 200$
- $50 \leq X \leq 200$

-----Sample Input:-----
2
120 100
90 100

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

-----EXPLANATION:-----
The first child has height more than minimum permissible height, so he can go on the ride while the other person cannot!

for _ in range(int(input())):
    l=list(map(int,input().split()))
    if(l[0]>=l[1]):
        print("Yes")
    else:
        print("No")


Solve in Python:
The sum of divisors of `6` is `12` and the sum of divisors of `28` is `56`. You will notice that `12/6 = 2` and `56/28 = 2`. We shall say that `(6,28)` is a pair with a ratio of `2`.  Similarly, `(30,140)` is also a pair but with a ratio of `2.4`. These ratios are simply decimal representations of fractions.

`(6,28)` and `(30,140)` are the only pairs in which `every member of a pair is 0 <= n < 200`. The sum of the lowest members of each pair is `6 + 30 = 36`.

You will be given a `range(a,b)`, and your task is to group the numbers into pairs with the same ratios. You will return the sum of the lowest member of each pair in the range. If there are no pairs. return `nil` in Ruby, `0` in python. Upper limit is `2000`.

```Haskell
solve(0,200) = 36
```

Good luck!

if you like this Kata, please try:

[Simple division](https://www.codewars.com/kata/59ec2d112332430ce9000005)

[Sub-array division](https://www.codewars.com/kata/59eb64cba954273cd4000099)

def solve(a,b):
    H = {}
    for n in range(a, b):
        r = {1, n}
        for i in range(2, int(n**0.5) + 1):
            if n % i == 0: r.update([i, n//i])
        d = sum(r) / n
        H[d] = H.get(d, []) + [n]
    return sum(H[k][0] for k in H if len(H[k]) > 1)


Solve in Python:
The task is simply stated. Given an integer n (3 < n < 10^(9)), find the length of the smallest list of [*perfect squares*](https://en.wikipedia.org/wiki/Square_number) which add up to n. Come up with the best algorithm you can; you'll need it!

Examples:

sum_of_squares(17) = 2  17 = 16 + 1 (4 and 1 are perfect squares).
sum_of_squares(15) = 4  15 = 9 + 4 + 1 + 1. There is no way to represent 15 as the sum of three perfect squares.
sum_of_squares(16) = 1  16 itself is a perfect square.

Time constraints:

5 easy (sample) test cases: n < 20

5 harder test cases: 1000 < n < 15000

5 maximally hard test cases: 5 * 1e8 < n < 1e9

```if:java
300 random maximally hard test cases: 1e8 < n < 1e9
```
```if:c#
350 random maximally hard test cases: 1e8 < n < 1e9
```
```if:python
15 random maximally hard test cases: 1e8 < n < 1e9
```
```if:ruby
25  random maximally hard test cases: 1e8 < n < 1e9
```
```if:javascript
100 random maximally hard test cases: 1e8 < n < 1e9
```
```if:crystal
250 random maximally hard test cases: 1e8 < n < 1e9
```
```if:cpp
Random maximally hard test cases: 1e8 < n < 1e9
```

def sum_of_squares(n):
        import math
        while n % 4 == 0: n = n // 4
        if n % 8 == 7: return 4
        if int(math.sqrt(n)) ** 2 == n: return 1
        i = 1
        while i*i <= n:
            j = math.sqrt(n - i*i)
            if int(j) == j: return 2
            i += 1
        return 3


Solve in Python:
The task is very simple.

You must to return pyramids. Given a number ```n```  you print a pyramid with ```n``` floors

For example , given a ```n=4``` you must to print this pyramid:

```
   /\
  /  \
 /    \
/______\

```

Other example, given a ```n=6``` you must to print this pyramid:

```
     /\
    /  \
   /    \
  /      \
 /        \
/__________\

```

Another example, given a ```n=10```, you must to print this pyramid:

```
         /\
        /  \
       /    \
      /      \
     /        \
    /          \
   /            \
  /              \
 /                \
/__________________\

```

Note: an extra line feed character is needed at the end of the string. Case `n=0` should so return `"\n"`.

def pyramid(n):
    return "".join(
        f"{' ' * (n - i - 1)}/{(' ' if i < (n - 1) else '_') * i * 2}\\\n" for i in range(n)
    )


Solve in Python:
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night.

Determine the maximum amount of money the thief can rob tonight without alerting the police.

Example 1:

     3
    / \
   2   3
    \   \
     3   1

Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

Example 2:

     3
    / \
   4   5
  / \   \
 1   3   1

Maximum amount of money the thief can rob = 4 + 5 = 9.

Credits:Special thanks to @dietpepsi for adding this problem and creating all test cases.

# Definition for a binary tree node.
 # class TreeNode:
 #     def __init__(self, x):
 #         self.val = x
 #         self.left = None
 #         self.right = None

 class Solution:
     def rob(self, root):
         self.dict = {}
         return self.recurse(root)

     def recurse(self, root):
         if root is None:
             return 0
         if root in self.dict:
             return self.dict[root]
         else:
             x = self.recurse(root.left)
             y = self.recurse(root.right)
             a = 0 if root.left is None else self.recurse(root.left.left)
             b = 0 if root.left is None else self.recurse(root.left.right)
             c = 0 if root.right is None else self.recurse(root.right.left)
             d = 0 if root.right is None else self.recurse(root.right.right)
             ans = max(root.val+a+b+c+d , x+y)
             self.dict[root] = ans
             return ans


Solve in Python:
The town sheriff dislikes odd numbers and wants all odd numbered families out of town! In town crowds can form and individuals are often mixed with other people and families. However you can distinguish the family they belong to by the number on the shirts they wear. As the sheriff's assistant it's your job to find all the odd numbered families and remove them from the town!
~~~if-not:cpp
Challenge: You are given a list of numbers. The numbers each repeat a certain number of times. Remove all numbers that repeat an odd number of times while keeping everything else the same.
~~~
~~~if:cpp
Challenge: You are given a vector of numbers. The numbers each repeat a certain number of times. Remove all numbers that repeat an odd number of times while keeping everything else the same.
~~~
```python
odd_ones_out([1, 2, 3, 1, 3, 3]) = [1, 1]
```
In the above example:
- the number 1 appears twice
- the number 2 appears once
- the number 3 appears three times

`2` and `3` both appear an odd number of times, so they are removed from the list. The final result is: `[1,1]`

Here are more examples:
```python
odd_ones_out([1, 1, 2, 2, 3, 3, 3]) = [1, 1, 2, 2]
odd_ones_out([26, 23, 24, 17, 23, 24, 23, 26]) = [26, 24, 24, 26]
odd_ones_out([1, 2, 3]) = []
odd_ones_out([1]) = []
```

Are you up to the challenge?

def odd_ones_out(numbers):
    return [i for i in numbers if numbers.count(i) % 2 == 0]


Solve in Python:
The vowel substrings in the word `codewarriors` are `o,e,a,io`. The longest of these has a length of 2. Given a lowercase string that has alphabetic characters only (both vowels and consonants) and no spaces, return the length of the longest vowel substring.
Vowels are any of `aeiou`.

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

Returns the length of the greatest continuous vowel substring in a string.

Syntax

public
static
int Solve(
string str
    )

Parameters

str

Type: System.String
The string to be processed.

Return Value

Type: System.Int32
  The length of the greatest continuous vowel substring in str, or 0 if str contains no vowels.

Exceptions

Exception
Condition

ArgumentNullException
str is null.

```

Good luck!

If you like substring Katas, please try:

[Non-even substrings](https://www.codewars.com/kata/59da47fa27ee00a8b90000b4)

[Vowel-consonant lexicon](https://www.codewars.com/kata/59cf8bed1a68b75ffb000026)

import re
def solve(s):
    return max(map(len, re.findall('[uoiae]+', s)))


Solve in Python:
The wide mouth frog is particularly interested in the eating habits of other creatures.

He just can't stop asking the creatures he encounters what they like to eat. But then he meet the alligator who just LOVES to eat wide-mouthed frogs!

When he meets the alligator, it then makes a tiny mouth.

Your goal in this kata is to create complete the `mouth_size` method this method take one argument `animal` which corresponds to the animal encountered by frog. If this one is an `alligator` (case insensitive) return `small` otherwise return `wide`.

def mouth_size(animal):
    return 'small' if (animal.lower()=='alligator' or animal.lower()=='alligator!') else 'wide'


Solve in Python:
The written representation of a number (with 4 or more digits) can be split into three parts in various different ways. For example, the written number 1234 can be split as [1 | 2 | 34] or [1 | 23 | 4] or [12 | 3 | 4].

Given a written number, find the highest possible product from splitting it into three parts and multiplying those parts together. For example:

- product of [1 | 2 | 34] = 1 \* 2 \* 34 = 68
- product of [1 | 23 | 4] = 1 \* 23 \* 4 = 92
- product of [12 | 3 | 4] = 12 \* 3 \* 4 = 144

So maximumProductOfParts(1234) = 144

For a longer string there will be many possible different ways to split it into parts. For example, 8675309 could be split as:

- [8 | 6 | 75309]
- [867 | 530 | 9]
- [8 | 67 | 5309]
- [86 | 75 | 309]

or any other option that splits the string into three parts each containing at least one digit.

def maximum_product_of_parts(n):
    products = []

    n = str(n)
    l = len(n)
    for i in range(1, l - 1) :
        for j in range(i + 1, l) :
            k = int(n[:i]) * int(n[i : j]) * int(n[j : l])
            products.append(k)
    return max(products)


Solve in Python:
The year is 2088 and the Radical Marxist Socialist People's Party (RMSPP) has just seized power in Brazil.

Their first act in power is absolute wealth equality through coercive redistribution.

Create a function that redistributes all wealth equally among all citizens.

Wealth is represented as an array/list where every index is the wealth of a single citizen. The function should mutate the input such that every index has the same amount of wealth. **MUTATE the input array/list, don't return anything.**

See example:

```python
wealth = [5, 10, 6]  # This represents:
                     # citizen 1 has wealth 5
                     # citizen 2 has wealth 10
                     # citizen 3 has wealth 6

redistribute_wealth(wealth) # mutates wealth list
wealth => [7, 7, 7] # wealth has now been equally redistributed

```

Info:

- **MUTATE the input array/list, don't return anything**

- Input is garantueed to hold at least 1 or more citizens

- Wealth of citizen will an integer with minimum 0 (negative wealth not possible)

- Handling of floating point error will not be tested

def redistribute_wealth(wealth):
    wealth[:] = len(wealth)*[sum(wealth)/float(len(wealth))]


Solve in Python:
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a.
What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
Input
The input contains three positive integer numbers in the first line: n,  m and a (1 ≤  n, m, a ≤ 10^9).
Output
Print the needed number of flagstones in new line.
Examples
input
6 6 4
output
4

try:
    n,m,a=map(int,input().split())
    if n%a!=0:
        number1=(n//a)+1
    else:
        number1=(n//a)
    if m%a!=0:
        number2=(m//a)+1
    else:
        number2=(m//a)
    print(number1*number2)
except:
    pass


Solve in Python:
Theory
 This section does not need to be read and can be skipped, but it does provide some clarity into the inspiration behind the problem.
In music theory, a major scale consists of seven notes, or scale degrees, in order (with tonic listed twice for demonstrative purposes):

Tonic, the base of the scale and the note the scale is named after (for example, C is the tonic note of the C major scale)
Supertonic, 2 semitones (or one tone) above the tonic
Mediant, 2 semitones above the supertonic and 4 above the tonic
Subdominant, 1 semitone above the median and 5 above the tonic
Dominant, 2 semitones above the subdominant and 7 above the tonic
Submediant, 2 semitones above the dominant and 9 above the tonic
Leading tone, 2 semitones above the mediant and 11 above the tonic
Tonic (again!), 1 semitone above the leading tone and 12 semitones (or one octave) above the tonic

An octave is an interval of 12 semitones, and the pitch class of a note consists of any note that is some integer
number of octaves apart from that note. Notes in the same pitch class sound different but share similar properties. If a note is in a major scale, then any note in that note's pitch class is also in that major scale.

 Problem
Using integers to represent notes, the major scale of an integer note will be an array (or list) of integers that follows the major scale pattern note, note + 2, note + 4, note + 5, note + 7, note + 9, note + 11. For example, the array of integers [1, 3, 5, 6, 8, 10, 12] is the major scale of  1.
Secondly, the pitch class of a note will be the set of all integers some multiple of 12 above or below the note. For example, 1, 13, and 25 are all in the same pitch class.
Thirdly, an integer note1 is considered to be in the key of an integer note2 if note1, or some integer in note1's pitch class, is in the major scale of note2.  More mathematically, an integer note1 is in the key of an integer note2 if there exists an integer i such that note1 + i × 12 is in the major scale of note2. For example, 22 is in the key of...

def is_tune(notes):
    return any(all((j+i)%12 in [0,2,4,5,7,9,11] for j in notes) for i in range(12)) if notes else False


Solve in Python:
There are $5$ cities in the country.
The map of the country is given below.
The tour starts from the red city.

Each road is associated with a character.
Initially, there is an empty string.
Every time a road has been travelled the character associated gets appended to the string.
At the green city either the string can be printed or the tour can be continued.
In the problem, you are given a string tell whether it is possible to print the string while following the rules of the country?

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains a single line of input, a string $ s  $. The string consists only of $0's$ and $1's$.

-----Output:-----
For each testcase, output "YES" or "NO" depending on the input.

-----Constraints-----
-
$1 \leq T \leq 10000$
-
$1 \leq length of each string \leq 10000$
-
$ 1 \leq Summation length \leq 10^5$

-----Sample Input:-----
1
100

-----Sample Output:-----
NO

-----EXPLANATION:-----

# cook your dish here
t=int(input())
for i in range(t):
 s=input()
 if len(s)>3:
  if s[-1]=='0' and s[-2]=='0' and s[-3]=='0' and s[-4]=='1':
   print("YES")
  else:
   print("NO")
 else:
  print("NO")


Solve in Python:
There are $M$ levels for a building numbered from $1$ to $M$ from top to bottom, each level having $N$ parking spots numbered from $1$ to $N$ from left to right. Some spots might have a car while other may be empty, the information of which is given in form of two dimensional character array $C$ ($C_{i, j}$ denote parking spot at $j$-th position on $i$-th level).
There is a thief who wants to unlock all the cars. Now, he is skilled such that for the first time, he can directly reach in any parking spot in no time. Basically he can reach the first car to be stolen in 0 time.
Now, he can move within the parking lot only in following manner, each taking 1 unit of time:
- Move down a level. That is, if current position is $(i, j)$, then he reaches $(i+1, j)$
- If current position is $(i, j)$ and if
- $i$ is odd, then he can move from $(i, j)$ to $(i, j+1)$
- $i$ is even, then he can move from $(i, j)$ to $(i, j-1)$
Note that he wants to unlock the cars in minimum time and the car is unlocked as soon as the thief reaches that parking spot.If the parking lot is empty, then the time taken is considered to be 0.
Find the minimum time when all the cars would be unlocked. Note that once all cars are unlocked, the thief can escape instantly, so this time does not count.

-----Input :-----
- The first line of input contains a single integer $T$ (number of test cases).
- First liine of each test case contains $M$ and $N$(number of levels and spots per each level)
- Next $M$ line contains $N$ space separated characters $C_{i, 1}, C_{i, 2} \ldots C_{i, N}$  where $(1\leq i\leq M)$ and $C_{i, j}$ is either $'P'$ or $'N'$ (without quotes).
If the spot contains $'P'$, then a car is parked there. else, it’s not parked.

-----Output :-----
For each test case print a single integer, the minimum time in which thief can unlock all cars.

-----Constraints :-----
- $1\leq T \leq100.$
- $1\leq M,N \leq300$

-----Subtasks :-----
-
Subtask 1 (20 points): $1\leq M \leq2.$
-
Subtask 2 (80 points): Original...

try:
# if(True):
 for _ in range(int(input())):
  m,n=map(int,input().split())
  c=[]
  last=0
  flag=True
  rowstart=0
  rowend=0
  for i in range(m):
   k=list(input().split())
   co=0
   k.append(-1)
   k.append(-1)
   for j in range(len(k)):
    if(k[j]=="P"):
     co+=1
     if(co==1):
      k[-2]=j
     k[-1]=j
     rowend=i

   if(k[-1]!=-1 and flag):
    flag=False
    rowstart=i
    if(i%2==0):
     last=k[-2]
    else:
     last=k[-1]
   c.append(k)
  count=0
#         print(c)

  for i in range(rowstart,rowend+1):

   if(i%2==0 and c[i][-1]!=-1):
    count+=abs(last-c[i][-2])
    count+=c[i][-1]-c[i][-2]
    last=c[i][-1]
   elif(i%2!=0 and c[i][-1]!=-1):
    count+=abs(last-c[i][-1])
    count+=c[i][-1]-c[i][-2]
    last=c[i][-2]
   count+=1
  print(count-1)

except:
 pass


Solve in Python:
There are $N$ buckets numbered $1$ through $N$. The buckets contain balls; each ball has a color between $1$ and $K$. Let's denote the number of balls with color $j$ that are initially in bucket $i$ by $a_{i, j}$.
For each $i$ from $1$ to $N-1$ (in this order), someone draws a ball uniformly at random from bucket $i$ and puts it into bucket $i+1$, then continues to draw the next ball. After putting a ball in bucket $N$, this person draws a ball, again uniformly at random, from bucket $N$.
For each color from $1$ to $K$, find the probability that the ball drawn from bucket $N$ has this color.

-----Input-----
- The first line of the input contains two space-separated integers $N$ and $K$.
- $N$ lines follow. For each $i$ ($1 \le i \le N$), the $i$-th of these lines contains $K$ space-separated integers $a_{i, 1}, a_{i, 2}, \ldots, a_{i, K}$.

-----Output-----
Print a single line containing $K$ space-separated real numbers. For each valid $i$, the $i$-th of these numbers should denote the probability that the last drawn ball has color $i$. your answer will be considered correct if absolute or relative error does not exceed $10^{-6}$

-----Constraints-----
- $1 \le N, K \le 1,000$
- $0 \le a_{i, j} \le 10$ for each valid $i, j$
- initially, there is at least one ball in bucket $1$

-----Subtasks-----
Subtask #1 (30 points): $1 \le N, K \le 100$
Subtask #2 (70 points): original constraints

-----Example Input-----
2 2
0 1
1 1

-----Example Output-----
0.333333 0.666667

-----Explanation-----

"""
  Url: https://www.codechef.com/problems/BUCKETS
"""

__author__ = "Ronald Kaiser"
__email__ = "raios dot catodicos at gmail dot com"

def solve(px, y, K):
 s = []
 sy = sum(y)
 for i in range(K):
  s.append((px[i]*((y[i] + 1)/(sy + 1)) + (1 - px[i])*(y[i]/(sy + 1))))
 return s

N, K = list(map(int, input().split()))
a = list(map(int, input().split()))
s = sum(a)
p = list([v/s for v in a])
for _ in range(N-1):
 a = list(map(int, input().split()))
 p = solve(p, a, K)
print(*p)


Solve in Python:
There are $N$ cars (numbered $1$ through $N$) on a circular track with length $N$. For each $i$ ($2 \le i \le N$), the $i$-th of them is at a distance $i-1$ clockwise from car $1$, i.e. car $1$ needs to travel a distance $i-1$ clockwise to reach car $i$. Also, for each valid $i$, the $i$-th car has $f_i$ litres of gasoline in it initially.
You are driving car $1$ in the clockwise direction. To move one unit of distance in this direction, you need to spend $1$ litre of gasoline. When you pass another car (even if you'd run out of gasoline exactly at that point), you steal all its gasoline. Once you do not have any gasoline left, you stop.
What is the total clockwise distance travelled by your car?

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- The second line contains $N$ space-separated integers $f_1, f_2, \ldots, f_N$.

-----Output-----
For each test case, print a single line containing one integer ― the total clockwise distance travelled.

-----Constraints-----
- $1 \le T \le 100$
- $1 \le N \le 100$
- $0 \le f_i \le 100$ for each valid $i$

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

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

-----Example Output-----
3
5
15

t = int(input())

for _ in range(t):
 n = int(input())
 flag = 0

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

 for i in range(1, n):
  f[i] += f[i-1]

 for i in range(0, n):
  if f[i] <= i:
   flag = 1
   break

 if(flag == 1):
  print(i)
 else:
  print(f[-1])


Solve in Python:
There are $N$ cells numbered 1,2,….., N, and every cell has some positive value. you will be given an array $A_1$,$A_2$,…,$A_N$ where $A_i$ is the value of $ith$ cell and an integer $K$.
There is a monkey who wants to reach the $right$ side of the last ($Nth$) cell, initially, the monkey was left side of the first ($1st$) cell.
In the first step, he can jump into any cell numbered 1,2,….., K.Once he jumped into any cell $i$ next he can only jump to the cell $j$ such that-
- j>i
- j-i <= K
- A[i]%2 == A[j]%2
You have to find out what is the minimum number of steps required to reach the right side of the cell or In case it's not possible to reach the right side of the cell your answer should be $-1$.NOTE: As soon as monkey reach any cell whose distance from the last cell is less than K, then in the last step, he will jump out to the right side of the ($Nth$) cell.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- The first line of each test case contains two space-separated integers $N$ and $K$.
- The second line contains $N$ space-separated integers $A_1$,$A_2$,…,$A_N$

-----Output:-----
For each test case, output in a single line minimum steps or $-1$.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq N \leq 2*10^5$
- $1 \leq K \leq N$
- $0 \leq A_i \leq 10^6$
- $\text{the sum of N over all test cases does not exceed $5*10^{5}$}$

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

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

-----EXPLANATION:-----
in the first step, you can jump into any cell 1 or 2 and then in the second step you will jump
out to the right side of 2nd cell
remember we don't want to reach $Nth$ cell we want to reach the right side of the nth cell.

# cook your dish here
#2

for t in range(int(input())):
    n, k = list(map(int, input().split()))
    A = list(map(int, input().split()))

    if k > n:
        print(1)
        continue
    #even
    curr = -1
    i = 0
    temp_even_place = -1
    ans_of_even = 0
    while curr + k < n: #need to find a stop
        while i-curr <= k:
            if A[i]%2 == 0:
                temp_even_place = i
            i+=1
        if temp_even_place == curr: #no new stop found
            ans_of_even = -1
            break
        else:
            ans_of_even += 1
            curr = temp_even_place
    if ans_of_even != -1:
        ans_of_even += 1

    #odd
    curr = -1
    i = 0
    temp_odd_place = -1
    ans_of_odd = 0
    while curr + k < n: #need to find a stop
        while i-curr <= k:
            if A[i]%2 == 1:
                temp_odd_place = i
            i+=1
        if temp_odd_place == curr: #no new stop found
            ans_of_odd = -1
            break
        else:
            ans_of_odd += 1
            curr = temp_odd_place
    if ans_of_odd != -1:
        ans_of_odd += 1

    if ans_of_even == -1 and ans_of_odd == -1:
        print(-1)
    elif ans_of_odd == -1 and ans_of_even != -1:
        print(ans_of_even)
    elif ans_of_odd != -1 and ans_of_even == -1:
        print(ans_of_odd)
    elif ans_of_odd != -1 and ans_of_even != -1:
        print(min(ans_of_even,ans_of_odd) )


Solve in Python:
There are $N$ cities on a circle, numbered $1$ through $N$. For each $i$ ($1 \le i \le N-1$), cities $i$ and $i+1$ are directly connected by a bidirectional road with length $A_i$, and cities $N$ and $1$ are also directly connected by a bidirectional road with length $A_N$. However, we do not know the lengths of some roads.
For each city $i$, we do know that it has an opposite city — formally, there is a city $j \neq i$ such that the clockwise distance between cities $i$ and $j$ is equal to the counterclockwise distance between these cities.
Please find the lengths of all roads in such a way that the above condition is satisfied and the sum of lengths of all roads is minimised.

-----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 the input contains a single integer $N$.
- The second line contains $N$ space-separated integers $A_1, A_2, \dots, A_N$. For each valid $i$, $A_i = -1$ denotes that the length of road $i$ is unknown.

-----Output-----
For each test case, print a line containing the string "NO" if there is no solution or "YES" otherwise. If a solution exists, print a second line containing $N$ space-separated positive integers — the lengths of all roads in your solution. Each of these integers should be $\le 10^9$. If there are multiple solutions, you may print any one.

-----Constraints-----
- $1 \le T \le 100$
- $3 \le N \le 10^5$
- $1 \le A_i \le 10^9$ or $A_i = -1$ for each valid $i$
- the sum of $N$ for all test cases does not exceed $3\cdot 10^5$

-----Subtasks-----
Subtask #1 (10 points): $N \le 4$
Subtask #2 (20 points): $A_i = \pm 1$ for each valid $i$
Subtask #3 (70 points): original constraints

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

-----Example Output-----
YES
1 1 1 1
NO
YES
1 4 1 4
NO

# cook your dish here
try:
 for i in range(int(input())):
  n=int(input())
  l=list(map(int,input().split()))
  if(n&1):
   print("NO")
   continue
  b=n//2
  c=0
  for j in range(b):
   if(l[j]>-1 and l[j+b]>-1 and l[j]!=l[j+b]):
    c=1
    break
   elif(l[j]==l[j+b] and l[j]==-1):
    l[j]=1
    l[j+b]=1
   else:
    if(l[j]==-1):
     l[j]=l[j+b]
    elif(l[j+b]==-1):
     l[j+b]=l[j]
  if(c==1):
   print("NO")
  else:
   print("YES")
   for j in range(n-1):
    print(l[j],end=" ")
   print(l[n-1])
except:
 pass


Solve in Python:
There are $N$ friends in a group. Each of them have $A_{i}$ candies.
Can they share all of these candies among themselves such that each one of them have equal no. of candies.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- First line of each testcase contains of a single line of input, an integer $N$ denoting no. of friends in the group.
- Next line contains $N$ space separated integers $A_{i}$  denoting the no. candies  $i^{th}$ friend has.

-----Output:-----
For each testcase, output $"Yes"$ if it is possible to share equally else $"No"$ (without " ").

-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq N \leq 100$
- $0 \leq A_{i} \leq 1000$

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

3

1 2 3

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

-----EXPLANATION:-----
Each of them have $2$ candies after sharing.

T=int(input())
while T<1 or T>10:
 T=int(input())
for i in range(T):
 n = int(input())
 a =list(map(int, input().strip().split(" ")))
 sum = 0
 k = 0
 for j in a:
  sum = sum + j
  k = k + 1
 avg = sum / k
 if avg % 1 == 0:
  print('Yes')
 else:
  print('No')


Solve in Python:
There are $N$ robots who work for $Y$ days and on each day they
produce some toys .on some days a few robots are given rest.
So depending on the availability of robots owner has
made a time table which decides which robots will work on
the particular day.
Only contiguous robots must be selected as they can form
a link of communication among themselves.
Initially, all robots have the capacity of one toy.
On each day capacity for the chosen robot is updated i.e
capacity = capacity $+$$ ($minimum capacity of given range % $1000000007)$ .
After calculating the minimum capacity of a given range, compute
it as modulo 1000000007 ($10^9 + 7$).
After $Y$ days find the minimum capacity of the $N$ robots and compute it as modulo 1000000007 ($10^9 + 7$).

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Next Line contains a single integer N.
- Next Line contains a single integer Y.
- Next $Y$ lines contains l and r range of chosen robots .

-----Output:-----
For each testcase, output in a single line answer , the minimum capacity of the $N$ robots after $Y$ days and compute it as modulo 1000000007 ($10^9 + 7$) .

-----Constraints-----
- $1 \leq T \leq 100$
- $100 \leq N \leq 10^4$
- $200 \leq Y \leq 1000$
- $0<=l , r<=N-1$  , $l<=r$

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

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

-----EXPLANATION:-----
Initial capacity of the $5$ robots
1 1 1 1 1
Minimum in range [0,3] = 1
Update the capacity in the range [0,3]
Now capacity becomes,
Day 1 - 2 2 2 2 1
Similarly capacities changes for each day
Day 2 - 2 4 4 2 1
Day 3 - 2 4 4 2 2
Day 4 - 4 6 6 4 4
so after 4 days minimum capacity is $4$.

MAX = 100005
tree = [0] * MAX;
lazy = [0] * MAX;

def updateRangeUtil(si, ss, se, us, ue, diff) :
    if (lazy[si] != 0) :
        tree[si] += lazy[si];
        if (ss != se) :
            lazy[si * 2 + 1] += lazy[si];
            lazy[si * 2 + 2] += lazy[si];
        lazy[si] = 0;

    if (ss > se or ss > ue or se < us) :
        return;

    if (ss >= us and se <= ue) :
        tree[si] += diff;
        if (ss != se) :
            lazy[si * 2 + 1] += diff;
            lazy[si * 2 + 2] += diff;
        return;

    mid = (ss + se) // 2;
    updateRangeUtil(si * 2 + 1, ss,mid, us, ue, diff);
    updateRangeUtil(si * 2 + 2, mid + 1,se, us, ue, diff);
    tree[si] = min(tree[si * 2 + 1],tree[si * 2 + 2]);

def updateRange(n, us, ue, diff) :
    updateRangeUtil(0, 0, n - 1, us, ue, diff);

def getSumUtil(ss, se, qs, qe, si) :
    if (lazy[si] != 0) :
        tree[si] += lazy[si];
        if (ss != se) :
            lazy[si * 2 + 1] += lazy[si];
            lazy[si * 2 + 2] += lazy[si];
        lazy[si] = 0;

    if (ss > se or ss > qe or se < qs) :
        return 10e9;

    if (ss >= qs and se <= qe) :
        return tree[si];

    mid = (ss + se) // 2;
    return min(getSumUtil(ss, mid, qs, qe, 2 * si + 1),getSumUtil(mid + 1, se, qs, qe, 2 * si + 2));

def getSum(n, qs, qe) :
    if (qs < 0 or qe > n - 1 or qs > qe) :
        #print("Invalid Input", end = "");
        return -1;

    return getSumUtil(0, n - 1, qs, qe, 0);

def constructSTUtil(arr, ss, se, si) :
    if (ss > se) :
        return;
    if (ss == se) :
        tree[si] = arr[ss];
        return;
    mid = (ss + se) // 2;
    constructSTUtil(arr, ss, mid, si * 2 + 1);
    constructSTUtil(arr, mid + 1, se, si * 2 + 2);
    tree[si] = min(tree[si * 2 + 1], tree[si * 2 + 2]);

def constructST(arr, n) :
    constructSTUtil(arr, 0, n - 1, 0);

# Driver code
for _ in range(int(input())):
    tree = [0] * MAX;
    lazy = [0] * MAX;
    n=int(input());
    y=int(input());
    arr=[1]*n;
    constructST(arr, n);
    for xyz...


Solve in Python:
There are $N$ sabotages available in the game Among Us, initially all at level $0$.
$N$ imposters are allotted the task to upgrade the level of the sabotages.
The $i^{th}$ imposter $(1 \leq i \leq N)$ increases the level of $x^{th}$ sabotage $(1 \leq x \leq N)$ by one level  if $gcd(i,x)=i$.
You need to find the number of sabotages at LEVEL 5 after all the imposters have completed their tasks.

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

-----Output:-----
For each testcase, output in a single line the number of sabotages at LEVEL 5.

-----Constraints-----
- $1 \leq T \leq 10^5$
- $1 \leq N \leq 10^{18}$

-----Sample Input:-----
1
6

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

-----EXPLANATION:-----
The $1^{st}$ sabotage is at level $1$, the $2^{nd}$, $3^{rd}$ and $5^{th}$ sabotages are at level $2$, the $4^{th}$ sabotage is at level $3$ and the $6^{th}$ sabotage is at level $4$.
None of them reach level $5$. Hence the output is $0$.

from sys import stdin, stdout
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf
from bisect import bisect_left as bl, bisect_right as br, bisect
mod = pow(10, 9) + 7
mod2 = 998244353
def inp(): return stdin.readline().strip()
def out(var, end="\n"): stdout.write(str(var)+"\n")
def outa(*var, end="\n"): stdout.write(' '.join(map(str, var)) + end)
def lmp(): return list(mp())
def mp(): return list(map(int, inp().split()))
def smp(): return list(map(str, inp().split()))
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]
def remadd(x, y): return 1 if x%y else 0

def chkprime(x):
    if x<=1: return False
    if x in (2, 3): return True
    if x%2 == 0: return False
    for i in range(3, int(sqrt(x))+1, 2):
        if x%i == 0: return False
    return True

l = []
i = 2
while True:
    if i**4 > 10**18: break
    if chkprime(i):
        l.append(i**4)
    i += 1

for _ in range(int(inp())):
    n = int(inp())
    k = br(l, n)
    print(k)