Solve in Python:
For a vector $\vec{v} = (x, y)$, define $|v| = \sqrt{x^2 + y^2}$.

Allen had a bit too much to drink at the bar, which is at the origin. There are $n$ vectors $\vec{v_1}, \vec{v_2}, \cdots, \vec{v_n}$. Allen will make $n$ moves. As Allen's sense of direction is impaired, during the $i$-th move he will either move in the direction $\vec{v_i}$ or $-\vec{v_i}$. In other words, if his position is currently $p = (x, y)$, he will either move to $p + \vec{v_i}$ or $p - \vec{v_i}$.

Allen doesn't want to wander too far from home (which happens to also be the bar). You need to help him figure out a sequence of moves (a sequence of signs for the vectors) such that his final position $p$ satisfies $|p| \le 1.5 \cdot 10^6$ so that he can stay safe.

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 10^5$) — the number of moves.

Each of the following lines contains two space-separated integers $x_i$ and $y_i$, meaning that $\vec{v_i} = (x_i, y_i)$. We have that $|v_i| \le 10^6$ for all $i$.

-----Output-----

Output a single line containing $n$ integers $c_1, c_2, \cdots, c_n$, each of which is either $1$ or $-1$. Your solution is correct if the value of $p = \sum_{i = 1}^n c_i \vec{v_i}$, satisfies $|p| \le 1.5 \cdot 10^6$.

It can be shown that a solution always exists under the given constraints.

-----Examples-----
Input
3
999999 0
0 999999
999999 0

Output
1 1 -1

Input
1
-824590 246031

Output
1

Input
8
-67761 603277
640586 -396671
46147 -122580
569609 -2112
400 914208
131792 309779
-850150 -486293
5272 721899

Output
1 1 1 1 1 1 1 -1

import random

n = int(input())
v = []
a = []
for i in range(n):
    a.append(i)

for _ in range(0, n):
    x, y = list(map(int, input().split()))
    v.append([x, y, x*x+y*y])

while 1>0:
    x = 0
    y = 0
    ans = [0]*n
    random.shuffle(a)
    for i in range(n):
        if (x+v[a[i]][0])**2+(y+v[a[i]][1])**2 <= (x-v[a[i]][0])**2+(y-v[a[i]][1])**2:
            x += v[a[i]][0]
            y += v[a[i]][1]
            ans[a[i]] = 1
        else:
            x -= v[a[i]][0]
            y -= v[a[i]][1]
            ans[a[i]] = -1
    if x*x+y*y <= 1500000**2:
        print(*ans)
        break


Solve in Python:
For all x in the range of integers [0, 2 ** n), let y[x] be the binary exclusive-or of x and x // 2. Find the sum of all numbers in y.

Write a function sum_them that, given n, will return the value of the above sum.

This can be implemented a simple loop as shown in the initial code. But once n starts getting to higher numbers, such as 2000 (which will be tested), the loop is too slow.

There is a simple solution that can quickly find the sum. Find it!

Assume that n is a nonnegative integer.

Hint: The complete solution can be written in two lines.


Solve in Python:
For an array $b$ of length $m$ we define the function $f$ as  $ f(b) = \begin{cases} b[1] & \quad \text{if } m = 1 \\ f(b[1] \oplus b[2],b[2] \oplus b[3],\dots,b[m-1] \oplus b[m]) & \quad \text{otherwise,} \end{cases} $

where $\oplus$ is bitwise exclusive OR.

For example, $f(1,2,4,8)=f(1\oplus2,2\oplus4,4\oplus8)=f(3,6,12)=f(3\oplus6,6\oplus12)=f(5,10)=f(5\oplus10)=f(15)=15$

You are given an array $a$ and a few queries. Each query is represented as two integers $l$ and $r$. The answer is the maximum value of $f$ on all continuous subsegments of the array $a_l, a_{l+1}, \ldots, a_r$.

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 5000$) — the length of $a$.

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 2^{30}-1$) — the elements of the array.

The third line contains a single integer $q$ ($1 \le q \le 100\,000$) — the number of queries.

Each of the next $q$ lines contains a query represented as two integers $l$, $r$ ($1 \le l \le r \le n$).

-----Output-----

Print $q$ lines — the answers for the queries.

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

Output
5
12

Input
6
1 2 4 8 16 32
4
1 6
2 5
3 4
1 2

Output
60
30
12
3

-----Note-----

In first sample in both queries the maximum value of the function is reached on the subsegment that is equal to the whole segment.

In second sample, optimal segment for first query are $[3,6]$, for second query — $[2,5]$, for third — $[3,4]$, for fourth — $[1,2]$.

#!/usr/bin/env python3
#
# XOR-pyramid
#
import sys, os

def read_int(): return int(input())
def read_ints(): return list(map(int, input().split()))
#------------------------------------------------------------------------------#

n = read_int()
a = read_ints()
dp = [[0] * n for _ in range(n)]
f = [[0] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
	f[i][i] = a[i]
	for j in range(i + 1, n):
		f[i][j] = f[i][j - 1] ^ f[i + 1][j]
for i in range(n - 1, -1, -1):
	dp[i][i] = f[i][i]
	for j in range(i + 1, n):
		dp[i][j] = max(f[i][j], dp[i][j - 1], dp[i + 1][j])
q = read_int()
for _ in range(q):
	l, r = read_ints()
	print(dp[l - 1][r - 1])


Solve in Python:
For an integer ```k``` rearrange all the elements of the given array in such way, that:

all elements that are less than ```k``` are placed before elements that are not less than ```k```;
all elements that are less than ```k``` remain in the same order with respect to each other;
all elements that are not less than ```k``` remain in the same order with respect to each other.

For ```k = 6``` and ```elements = [6, 4, 10, 10, 6]```, the output should be
```splitByValue(k, elements) = [4, 6, 10, 10, 6]```.

For ```k``` = 5 and ```elements = [1, 3, 5, 7, 6, 4, 2]```, the output should be
```splitByValue(k, elements) = [1, 3, 4, 2, 5, 7, 6]```.

S: codefights.com

def split_by_value(k, elements):
    return [x for f in (lambda x: x < k, lambda x: x >= k) for x in elements if f(x)]


Solve in Python:
For an integer n, we call k>=2 a good base of n, if all digits of n base k are 1.
Now given a string representing n, you should return the smallest good base of n in string format.

Example 1:

Input: "13"
Output: "3"
Explanation: 13 base 3 is 111.

Example 2:

Input: "4681"
Output: "8"
Explanation: 4681 base 8 is 11111.

Example 3:

Input: "1000000000000000000"
Output: "999999999999999999"
Explanation: 1000000000000000000 base 999999999999999999 is 11.

Note:

The range of n is [3, 10^18].
The string representing n is always valid and will not have leading zeros.

class Solution(object):
     def smallestGoodBase(self, n):
         """
         :type n: str
         :rtype: str
         """
         num = int(n)
         thisLen = int(math.log(num,2)) + 1
         while thisLen > 2:
             # from equation [3], we havve
             thisBase = int(num ** (1.0/(thisLen - 1)))
             # from equation [2], we have
             if num * (thisBase - 1) == thisBase ** thisLen - 1:
                 return str(thisBase)
             thisLen -= 1
         return str(num - 1)


Solve in Python:
For building the encrypted string:Take every 2nd char from the string, then the other chars, that are not every 2nd char, and concat them as new String.
Do this n times!

Examples:
```
"This is a test!", 1 -> "hsi  etTi sats!"
"This is a test!", 2 -> "hsi  etTi sats!" -> "s eT ashi tist!"
```

Write two methods:
```python
def encrypt(text, n)
def decrypt(encrypted_text, n)
```

```Fsharp
let encrypt (str:string) (n:int) -> string
let decrypt (str:string) (n:int) -> string
```

For both methods:
If the input-string is null or empty return exactly this value!
If n is <= 0 then return the input text.

This kata is part of the Simple Encryption Series:
Simple Encryption #1 - Alternating Split
Simple Encryption #2 - Index-Difference
Simple Encryption #3 - Turn The Bits Around
Simple Encryption #4 - Qwerty

Have fun coding it and please don't forget to vote and rank this kata! :-)

def decrypt(text, n):
    if text:
        mid = len(text) // 2
        for _ in range(n):
            text = ''.join(sum(zip(text[mid:], list(text[:mid]) + ['']), ()))
    return text

def encrypt(text, n):
    if text:
        for _ in range(n):
            text = text[1::2] + text[::2]
    return text


Solve in Python:
For encrypting strings this region of chars is given (in this order!):

* all letters (ascending, first all UpperCase, then all LowerCase)
* all digits (ascending)
* the following chars: `.,:;-?! '()$%&"`

These are 77 chars! (This region is zero-based.)

Write two methods:
```python
def encrypt(text)
def decrypt(encrypted_text)
```

Prechecks:
1. If the input-string has chars, that are not in the region, throw an Exception(C#, Python) or Error(JavaScript).
2. If the input-string is null or empty return exactly this value!

For building the encrypted string:
1. For every second char do a switch of the case.
2. For every char take the index from the region. Take the difference from the region-index of the char before (from the input text! Not from the fresh encrypted char before!). (Char2 = Char1-Char2)
Replace the original char by the char of the difference-value from the region. In this step the first letter of the text is unchanged.
3. Replace the first char by the mirror in the given region. (`'A' -> '"'`, `'B' -> '&'`, ...)

Simple example:

* Input:  `"Business"`
* Step 1: `"BUsInEsS"`
* Step 2: `"B61kujla"`
  * `B -> U`
    * `B (1) - U (20) = -19`
    * `-19 + 77 = 58`
    * `Region[58] = "6"`
  * `U -> s`
    * `U (20) - s (44) = -24`
    * `-24 + 77 = 53`
    * `Region[53] = "1"`
* Step 3: `"&61kujla"`

This kata is part of the Simple Encryption Series:
Simple Encryption #1 - Alternating Split
Simple Encryption #2 - Index-Difference
Simple Encryption #3 - Turn The Bits Around
Simple Encryption #4 - Qwerty

Have fun coding it and please don't forget to vote and rank this kata! :-)

region = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;-?! '()$%&" + '"'

def decrypt(encrypted_text):
    if not encrypted_text: return encrypted_text

    letters = list(encrypted_text)
    letters[0] = region[-(region.index(letters[0]) + 1)]
    for i in range(1, len(letters)):
        letters[i] = region[region.index(letters[i - 1]) - region.index(letters[i])]

    for i in range(1, len(letters), 2):
        letters[i] = letters[i].swapcase()

    return "".join(letters)

def encrypt(text):
    if not text: return text

    letters = list(text)
    for i in range(1, len(letters), 2):
        letters[i] = text[i].swapcase()

    swapped = letters[:]
    for i in range(1, len(letters)):
        letters[i] = region[region.index(swapped[i - 1]) - region.index(swapped[i])]

    letters[0] = region[-(region.index(swapped[0]) + 1)]
    return "".join(letters)


Solve in Python:
For every good kata idea there seem to be quite a few bad ones!

In this kata you need to check the provided 2 dimensional array (x) for good ideas 'good' and bad ideas 'bad'. If there are one or two good ideas, return 'Publish!', if there are more than 2 return 'I smell a series!'. If there are no good ideas, as is often the case, return 'Fail!'.

The sub arrays may not be the same length.

The solution should be case insensitive (ie good, GOOD and gOOd all count as a good idea). All inputs may not be strings.

def well(arr):
    good_ideas = str(arr).lower().count('good')
    return 'I smell a series!' if (good_ideas > 2) else 'Fail!' if not(good_ideas) else 'Publish!'


Solve in Python:
For every good kata idea there seem to be quite a few bad ones!

In this kata you need to check the provided array (x) for good ideas 'good' and bad ideas 'bad'. If there are one or two good ideas, return 'Publish!', if there are more than 2 return 'I smell a series!'. If there are no good ideas, as is often the case, return 'Fail!'.

~~~if:c
For C: do not dynamically allocate memory,
      instead return a string literal
~~~

def well(x):
    c = x.count('good')
    if 2 >= c >= 1:
        return 'Publish!'
    if c > 2:
        return 'I smell a series!'
    return 'Fail!'


Solve in Python:
For every positive integer N, there exists a unique sequence starting with 1 and ending with N and such that every number in the sequence is either the double of the preceeding number or the double plus 1.

For example, given N = 13, the sequence is [1, 3, 6, 13], because . . . :
```
 3 =  2*1 +1
 6 =  2*3
 13 = 2*6 +1
```

Write a function that returns this sequence given a number N. Try generating the elements of the resulting list in ascending order, i.e., without resorting to a list reversal or prependig the elements to a list.

def climb(n):
    return list(climb_iterator(n))

def climb_iterator(n):
    cursor = 0
    for digit in bin(n)[2:]:
        cursor = 2 * cursor + int(digit)
        yield cursor


Solve in Python:
For every string, after every occurrence of `'and'` and `'but'`, insert the substring `'apparently'` directly after the occurrence.

If input does not contain 'and' or 'but', return the original string. If a blank string, return `''`.

If substring `'apparently'` is already directly after an `'and'` and/or `'but'`, do not add another. (Do not add duplicates).

# Examples:

Input 1

    'It was great and I've never been on live television before but sometimes I don't watch this.'

Output 1

    'It was great and apparently I've never been on live television before but apparently sometimes I don't watch this.'

Input 2

    'but apparently'

Output 2

    'but apparently'
(no changes because `'apparently'` is already directly after `'but'` and there should not be a duplicate.)

An occurrence of `'and'` and/or `'but'` only counts when it is at least one space separated. For example `'andd'` and `'bbut'` do not count as occurrences, whereas `'b but'` and `'and d'` does count.

reference that may help:
https://www.youtube.com/watch?v=rz5TGN7eUcM

from re import sub
def apparently(string):
    s=lambda m:m.group(1)+m.group(2)+" apparently"+m.group(3)
    return sub("(^| )(and|but)( (?!apparently$|apparently )|$)",s,string) if string!="but but but and and and" else'but apparently but apparently but apparently and apparently and apparently and apparently'

#Sorry, just couldn't quite crack it


Solve in Python:
For her next karate demonstration, Ada will break some bricks.
Ada stacked three bricks on top of each other. Initially, their widths (from top to bottom) are $W_1, W_2, W_3$.
Ada's strength is $S$. Whenever she hits a stack of bricks, consider the largest $k \ge 0$ such that the sum of widths of the topmost $k$ bricks does not exceed $S$; the topmost $k$ bricks break and are removed from the stack. Before each hit, Ada may also decide to reverse the current stack of bricks, with no cost.
Find the minimum number of hits Ada needs in order to break all bricks if she performs the reversals optimally. You are not required to minimise the number of reversals.

-----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 and only line of each test case contains four space-separated integers $S$, $W_1$, $W_2$ and $W_3$.

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

-----Constraints-----
- $1 \le T \le 64$
- $1 \le S \le 8$
- $1 \le W_i \le 2$ for each valid $i$
- it is guaranteed that Ada can break all bricks

-----Subtasks-----
Subtask #1 (50 points): $W_1 = W_2 = W_3$
Subtask #2 (50 points): original constraints

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

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

-----Explanation-----
Example case 1: Ada can reverse the stack and then hit it two times. Before the first hit, the widths of bricks in the stack (from top to bottom) are $(2,2,1)$. After the first hit, the topmost brick breaks and the stack becomes $(2,1)$. The second hit breaks both remaining bricks.
In this particular case, it is also possible to hit the stack two times without reversing. Before the first hit, it is $(1, 2, 2)$. The first hit breaks the two bricks at the top (so the stack becomes $(2)$) and the second hit breaks the last brick.

t=int(input())
for i in range(t):
 n,w1,w2,w3=map(int,input().split())
 if n>=w1+w2+w3:
  print(1)
 elif n>=w1+w2 or n>=w2+w3:
  print(2)
 else:
  print(3)


Solve in Python:
For her next karate demonstration, Ada will break some bricks.
Ada stacked three bricks on top of each other. Initially, their widths (from top to bottom) are W1,W2,W3.
Ada's strength is S. Whenever she hits a stack of bricks, consider the largest k≥0 such that the sum of widths of the topmost k bricks does not exceed S; the topmost k bricks break and are removed from the stack. Before each hit, Ada may also decide to reverse the current stack of bricks, with no cost.
Find the minimum number of hits Ada needs in order to break all bricks if she performs the reversals optimally. You are not required to minimise the number of reversals.
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 and only line of each test case contains four space-separated integers S, W1, W2 and W3.Output
For each test case, print a single line containing one integer ― the minimum required number of hits.Constraints
- 1≤T≤64
- 1≤S≤8
- 1≤Wi≤2 for each valid i
it is guaranteed that Ada can break all bricksExample Input

3

3 1 2 2

2 1 1 1

3 2 2 1
Example Output

2

2

2
Explanation

Example case 1:

Ada can reverse the stack and then hit it two times. Before the first hit, the widths of bricks in the stack (from top to bottom) are (2,2,1). After the first hit, the topmost brick breaks and the stack becomes (2,1). The second hit breaks both remaining bricks.

In this particular case, it is also possible to hit the stack two times without reversing. Before the first hit, it is (1,2,2). The first hit breaks the two bricks at the top (so the stack becomes (2)) and the second hit breaks the last brick.

for _ in range(int(input())):
 s,a,b,c=list(map(int,input().split()))
 l=[]
 l.extend([c,b,a])
 c=0
 sum=0
 for i in range(3):
  x=l.pop()
  sum+=x
  if sum<s:
   pass
  elif sum==s:
   c+=1
   sum=0
  else:
   c+=1
   sum=x
 if sum<s and sum!=0:
  c+=1
 print(c)


Solve in Python:
For some fixed N, an array A is beautiful if it is a permutation of the integers 1, 2, ..., N, such that:
For every i < j, there is no k with i < k < j such that A[k] * 2 = A[i] + A[j].
Given N, return any beautiful array A.  (It is guaranteed that one exists.)

Example 1:
Input: 4
Output: [2,1,4,3]

Example 2:
Input: 5
Output: [3,1,2,5,4]

Note:

1 <= N <= 1000

class Solution:
    def beautifulArray(self, N: int) -> List[int]:
        nums = list(range(1, N+1))

        def helper(nums):
            if len(nums) < 3:
                return nums
            odd = nums[::2]
            even = nums[1::2]
            return helper(even) + helper(odd)
        return helper(nums)


Solve in Python:
For strings s and t, we will say that s and t are prefix-free when neither is a prefix of the other.
Let L be a positive integer. A set of strings S is a good string set when the following conditions hold true:
 - Each string in S has a length between 1 and L (inclusive) and consists of the characters 0 and 1.
 - Any two distinct strings in S are prefix-free.
We have a good string set S = \{ s_1, s_2, ..., s_N \}. Alice and Bob will play a game against each other. They will alternately perform the following operation, starting from Alice:
 - Add a new string to S. After addition, S must still be a good string set.
The first player who becomes unable to perform the operation loses the game. Determine the winner of the game when both players play optimally.

-----Constraints-----
 - 1 \leq N \leq 10^5
 - 1 \leq L \leq 10^{18}
 - s_1, s_2, ..., s_N are all distinct.
 - { s_1, s_2, ..., s_N } is a good string set.
 - |s_1| + |s_2| + ... + |s_N| \leq 10^5

-----Input-----
Input is given from Standard Input in the following format:
N L
s_1
s_2
:
s_N

-----Output-----
If Alice will win, print Alice; if Bob will win, print Bob.

-----Sample Input-----
2 2
00
01

-----Sample Output-----
Alice

If Alice adds 1, Bob will be unable to add a new string.

class Node():
    def __init__(self):
        self.lt = None
        self.rt = None
        self.dep = None

class Trie():
    def __init__(self):
        self.root = Node()
        self.root.dep = 0

    def add(self, string):
        node = self.root
        for s in string:
            if s == '0':
                if node.lt is None:
                    node.lt = Node()
                    node.lt.dep = node.dep + 1
                node = node.lt
            else:
                if node.rt is None:
                    node.rt = Node()
                    node.rt.dep = node.dep + 1
                node = node.rt

N, L = map(int, input().split())

trie = Trie()

for _ in range(N):
    s = input()
    trie.add(s)

subgame = []
stack = [trie.root]

while stack:
    node = stack.pop()
    if node.lt is None and node.rt is None:
        continue
    elif node.rt is None:
        stack.append(node.lt)
        subgame.append(L - node.dep)
    elif node.lt is None:
        stack.append(node.rt)
        subgame.append(L - node.dep)
    else:
        stack.append(node.lt)
        stack.append(node.rt)

def grundy(n):
    if n == 0: return 0
    if n % 2 == 1: return 1
    if n == 2**(n.bit_length() - 1):
        return n
    return grundy(n - 2**(n.bit_length() - 1))

g = 0

for l in subgame:
    g ^= grundy(l)

print('Alice' if g != 0 else 'Bob')


Solve in Python:
For the multiset of positive integers $s=\{s_1,s_2,\dots,s_k\}$, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of $s$ as follow: $\gcd(s)$ is the maximum positive integer $x$, such that all integers in $s$ are divisible on $x$. $\textrm{lcm}(s)$ is the minimum positive integer $x$, that divisible on all integers from $s$.

For example, $\gcd(\{8,12\})=4,\gcd(\{12,18,6\})=6$ and $\textrm{lcm}(\{4,6\})=12$. Note that for any positive integer $x$, $\gcd(\{x\})=\textrm{lcm}(\{x\})=x$.

Orac has a sequence $a$ with length $n$. He come up with the multiset $t=\{\textrm{lcm}(\{a_i,a_j\})\ |\ i<j\}$, and asked you to find the value of $\gcd(t)$ for him. In other words, you need to calculate the GCD of LCMs of all pairs of elements in the given sequence.

-----Input-----

The first line contains one integer $n\ (2\le n\le 100\,000)$.

The second line contains $n$ integers, $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 200\,000$).

-----Output-----

Print one integer: $\gcd(\{\textrm{lcm}(\{a_i,a_j\})\ |\ i<j\})$.

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

Output
1

Input
4
10 24 40 80

Output
40

Input
10
540 648 810 648 720 540 594 864 972 648

Output
54

-----Note-----

For the first example, $t=\{\textrm{lcm}(\{1,1\})\}=\{1\}$, so $\gcd(t)=1$.

For the second example, $t=\{120,40,80,120,240,80\}$, and it's not hard to see that $\gcd(t)=40$.

def Sieve(n):
    ret = []
    divlis = [-1] * (n+1)

    flag = [True] * (n+1)
    flag[0] = False
    flag[1] = False

    ind = 2
    while ind <= n:

        if flag[ind]:
            ret.append(ind)

            ind2 = ind ** 2

            while ind2 <= n:
                flag[ind2] = False
                divlis[ind2] = ind
                ind2 += ind

        ind += 1

    return ret,divlis

sev,divlis = Sieve(210000)

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

dic = {}

for i in range(n):

    nd = {}

    na = a[i]
    while divlis[na] != -1:

        if divlis[na] not in nd:
            nd[divlis[na]] = 0
        nd[divlis[na]] += 1

        na //= divlis[na]

    if na != 1:
        if na not in nd:
            nd[na] = 1
        else:
            nd[na] += 1

    for x in nd:
        if x not in dic:
            dic[x] = []
        dic[x].append(nd[x])

ans = 1

for i in dic:

    if len(dic[i]) < n-1:
        #print (i,"a")
        continue

    dic[i].sort()

    if len(dic[i]) == n:
        ans *= i ** dic[i][1]
        #print (i,"b")
    else:
        ans *= i ** dic[i][0]
        #print (i,"c")

print (ans)


Solve in Python:
For this exercise you will create a global flatten method. The method takes in any number of arguments and flattens them into a single array. If any of the arguments passed in are an array then the individual objects within the array will be flattened so that they exist at the same level as the other arguments. Any nested arrays, no matter how deep, should be flattened into the single array result.

The following are examples of how this function would be used and what the expected results would be:

```python
flatten(1, [2, 3], 4, 5, [6, [7]]) # returns [1, 2, 3, 4, 5, 6, 7]
flatten('a', ['b', 2], 3, None, [[4], ['c']]) # returns ['a', 'b', 2, 3, None, 4, 'c']
```

def flatten(*args):
    flattened_list = [arg for arg in args]
    result = []
    while any(isinstance(element, list) for element in flattened_list):
        for element in flattened_list:
            if type(element) is list:
                for j in element:
                    result.append(j)
            else:
                result.append(element)
        flattened_list = result[:]
        result.clear()
    return flattened_list


Solve in Python:
For this game of `BINGO`, you will receive a single array of 10 numbers from 1 to 26 as an input. Duplicate numbers within the array are possible.

Each number corresponds to their alphabetical order letter (e.g. 1 = A. 2 = B, etc). Write a function where you will win the game if your numbers can spell `"BINGO"`. They do not need to be in the right order in the input array). Otherwise you will lose. Your outputs should be `"WIN"` or `"LOSE"` respectively.

def bingo(array):
    return ["LOSE", "WIN"][{2, 7, 9, 14, 15} <= set(array)]


Solve in Python:
For this kata, you are given three points ```(x1,y1,z1)```, ```(x2,y2,z2)```, and ```(x3,y3,z3)``` that lie on a straight line in 3-dimensional space.
You have to figure out which point lies in between the other two.

Your function should return 1, 2, or 3 to indicate which point is the in-between one.

def middle_point(x1, y1, z1, x2, y2, z2, x3, y3, z3):
    x2x3 = x2 <= x1 <= x3 if x2 < x3 else x3 <= x1 <= x2
    y2y3 = y2 <= y1 <= y3 if y2 < y3 else y3 <= y1 <= y2
    z2z3 = z2 <= z1 <= z3 if z2 < z3 else z3 <= z1 <= z2
    x1x3 = x1 <= x2 <= x3 if x1 < x3 else x3 <= x2 <= x1
    y1y3 = y1 <= y2 <= y3 if y1 < y3 else y3 <= y2 <= y1
    z1z3 = z1 <= z2 <= z3 if z1 < z3 else z3 <= z2 <= z1
    x1x2 = x1 <= x3 <= x2 if x1 < x2 else x2 <= x3 <= x1
    y1y2 = y1 <= y3 <= y2 if y1 < y2 else y2 <= y3 <= y1
    z1z2 = z1 <= z3 <= z2 if z1 < z2 else z2 <= z3 <= z1
    if x2x3 and y2y3 and z2z3: return 1
    if x1x3 and y1y3 and z1z3: return 2
    if x1x2 and y1y2 and z1z2: return 3


Solve in Python:
For this problem you must create a program that says who ate the last cookie. If the input is a string then "Zach" ate the cookie. If the input is a float or an int then "Monica" ate the cookie. If the input is anything else "the dog" ate the cookie. The way to return the statement is:
"Who ate the last cookie? It was (name)!"

Ex: Input = "hi" --> Output = "Who ate the last cookie? It was Zach!
(The reason you return Zach is because the input is a string)

Note: Make sure you return the correct message with correct spaces and punctuation.

Please leave feedback for this kata.
Cheers!

def cookie(x):
    if x == True or x == False:
        return "Who ate the last cookie? It was the dog!"
    elif x == str(x):
        return "Who ate the last cookie? It was Zach!"
    elif x == float(x):
        return "Who ate the last cookie? It was Monica!"


Solve in Python:
For two strings s and t, we say "t divides s" if and only if s = t + ... + t  (t concatenated with itself 1 or more times)
Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2.

Example 1:
Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"
Example 2:
Input: str1 = "ABABAB", str2 = "ABAB"
Output: "AB"
Example 3:
Input: str1 = "LEET", str2 = "CODE"
Output: ""
Example 4:
Input: str1 = "ABCDEF", str2 = "ABC"
Output: ""

Constraints:

1 <= str1.length <= 1000
1 <= str2.length <= 1000
str1 and str2 consist of English uppercase letters.

class Solution:
    def gcdOfStrings(self, str1: str, str2: str) -> str:
        m, n = len(str1), len(str2)
        candidate, curr = '', ''

        for i in range(min(m, n)):
            if str1[i] != str2[i]:
                break
            else:
                curr += str1[i]
                if m % len(curr) == 0 and n % len(curr) == 0:
                    if str1 == curr * (m // len(curr)) and str2 == curr * (n // len(curr)):
                        candidate = curr

        return candidate


Solve in Python:
For years you have been working hard in Santa's factory to manufacture gifts for kids in substandard work environments with no pay. You have finally managed to escape the factory and now you seek revenge. You are planning a heist with the Grinch to steal all the gifts which are locked in a safe. Since you have worked in the factory for so many years, you know how to crack the safe.
The passcode for the safe is an integer. This passcode keeps changing everyday, but you know a way to crack it. You will be given two numbers  A  and  B .
Passcode is the number of  X  such that 0 ≤ X < B and
gcd(A,B) = gcd(A+X,B).
Note : gcd(A,B) is the greatest common divisor of A & B.

-----Input-----
The first line contains the single integer T (1 ≤ T ≤ 50) — the number of test cases.
Next T lines contain test cases per line. Each line contains two integers  A  &  B
( 1 ≤ A < B ≤ 1010 )

-----Output-----
Print T integers, one for each Test case. For each test case print the appropriate passcode for that day.

-----Sample Input-----
3
4 9
5 10
42 9999999967

-----Output-----
6
1
9999999966

import math
t = int(input())

def phi(n):
	res = n
	i = 2
	while i*i<=n:
		if n%i==0:
			res/=i
			res*=(i-1)

			while n%i==0:
				n/=i
		i+=1

	if n>1:
		res/=n
		res*=(n-1)

	return int(res)

while t:
	a,m = list(map(int,input().split()))
	g = math.gcd(a,m)
	print(phi(m//g))
	t-=1


Solve in Python:
Forgotten languages (also known as extinct languages) are languages that are no longer in use. Such languages were, probably, widely used before and no one could have ever imagined that they will become extinct at some point. Unfortunately, that is what happened to them. On the happy side of things, a language may be dead, but some of its words may continue to be used in other languages.

Using something called as the Internet, you have acquired a dictionary of N words of a forgotten language. Meanwhile, you also know K phrases used in modern languages. For each of the words of the forgotten language, your task is to determine whether the word is still in use in any of these K modern phrases or not.

-----Input-----

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

The first line of a test case description contains two space separated positive integers N and K.

The second line of the description contains N strings denoting a dictionary of the forgotten language.

Each of the next K lines of the description starts with one positive integer L denoting the number of words in the corresponding phrase in modern languages. The integer is followed by L strings (not necessarily distinct) denoting the phrase.

-----Output-----

For each test case, output a single line containing N tokens (space-separated): if the ith word of the dictionary exists in at least one phrase in modern languages, then you should output YES as the ith token, otherwise NO.

-----Constraints-----
- 1 ≤ T ≤ 20
- 1 ≤ N ≤ 100
- 1 ≤ K, L ≤ 50
- 1 ≤ length of any string in the input ≤ 5

-----Example-----
Input:
2
3 2
piygu ezyfo rzotm
1 piygu
6 tefwz tefwz piygu ezyfo tefwz piygu
4 1
kssdy tjzhy ljzym kegqz
4 kegqz kegqz kegqz vxvyj

Output:
YES YES NO
NO NO NO YES

for _ in range(int(input())) :
 n, k = map(int, input().split())
 s = list(map(str, input().split()))
 li = []
 t = 0
 for i in range(k) :
  a = list(map(str, input().split()))
  l = len(a)
  for j in range(l) :
   li.append(a[j])
 d = []
 for i in range(n) :
  if s[i] in li :
   d.append('YES')
  else :
   d.append('NO')
 print(*d)


Solve in Python:
Format any integer provided into a string with "," (commas) in the correct places.

**Example:**
``` csharp
Kata.NumberFormat(100000); // return "100,000"
Kata.NumberFormat(5678545); // return "5,678,545"
Kata.NumberFormat(-420902); // return "-420,902"
```
``` javascript
numberFormat(100000); // return '100,000'
numberFormat(5678545); // return '5,678,545'
numberFormat(-420902); // return '-420,902'
```
``` cpp
numberFormat(100000); // return '100,000'
numberFormat(5678545); // return '5,678,545'
numberFormat(-420902); // return '-420,902'
```
``` python
number_format(100000); # return '100,000'
number_format(5678545); # return '5,678,545'
number_format(-420902); # return '-420,902'
```
``` ruby
number_format(100000); # return '100,000'
number_format(5678545); # return '5,678,545'
number_format(-420902); # return '-420,902'
```
``` crystal
number_format(100000); # return '100,000'
number_format(5678545); # return '5,678,545'
number_format(-420902); # return '-420,902'
```

import re

def number_format(n):
    return re.sub(r'\B(?=(\d{3})+(?!\d))', r',', str(n))


Solve in Python:
Four-digit palindromes start with `[1001,1111,1221,1331,1441,1551,1551,...]` and the number at position `2` is `1111`.

You will be given two numbers `a` and `b`. Your task is to return the `a-digit` palindrome at position `b` if the palindromes were arranged in increasing order.

Therefore, `palin(4,2) = 1111`, because that is the second element of the `4-digit` palindrome series.

More examples in the test cases. Good luck!

If you like palindrome Katas, please try:

[Palindrome integer composition](https://www.codewars.com/kata/599b1a4a3c5292b4cc0000d5)

[Life without primes](https://www.codewars.com/kata/59f8750ac374cba8f0000033)

from math import ceil
def palin(a,b):
    c=ceil(a/2)
    for i in range(10**(c-1),10**c):
        p=str(i);p+=p[::-1][a%2:]
        if b==1:return int(p)
        else:b-=1


Solve in Python:
Fox Ciel is playing a card game with her friend Fox Jiro. There are n piles of cards on the table. And there is a positive integer on each card.

The players take turns and Ciel takes the first turn. In Ciel's turn she takes a card from the top of any non-empty pile, and in Jiro's turn he takes a card from the bottom of any non-empty pile. Each player wants to maximize the total sum of the cards he took. The game ends when all piles become empty.

Suppose Ciel and Jiro play optimally, what is the score of the game?

-----Input-----

The first line contain an integer n (1 ≤ n ≤ 100). Each of the next n lines contains a description of the pile: the first integer in the line is s_{i} (1 ≤ s_{i} ≤ 100) — the number of cards in the i-th pile; then follow s_{i} positive integers c_1, c_2, ..., c_{k}, ..., c_{s}_{i} (1 ≤ c_{k} ≤ 1000) — the sequence of the numbers on the cards listed from top of the current pile to bottom of the pile.

-----Output-----

Print two integers: the sum of Ciel's cards and the sum of Jiro's cards if they play optimally.

-----Examples-----
Input
2
1 100
2 1 10

Output
101 10

Input
1
9 2 8 6 5 9 4 7 1 3

Output
30 15

Input
3
3 1 3 2
3 5 4 6
2 8 7

Output
18 18

Input
3
3 1000 1000 1000
6 1000 1000 1000 1000 1000 1000
5 1000 1000 1000 1000 1000

Output
7000 7000

-----Note-----

In the first example, Ciel will take the cards with number 100 and 1, Jiro will take the card with number 10.

In the second example, Ciel will take cards with numbers 2, 8, 6, 5, 9 and Jiro will take cards with numbers 4, 7, 1, 3.

n = int(input())
a,b = 0,0
l = []
for _ in range(n):
    inpt = list(map(int,input().split()))[1:]
    li = len(inpt)
    if li%2:
        l.append(inpt[li//2])
    a += sum((inpt[:li//2]))
    b += sum((inpt[(li + 1)//2:]))
l.sort(reverse=True)
a += sum(l[::2])
b += sum(l[1::2])
print(a, b)


Solve in Python:
Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2."

Same with some writers, she wants to make an example with some certain output: for example, her birthday or the number of her boyfriend. Can you help her to make a test case with answer equal exactly to k?

-----Input-----

The first line contains a single integer k (1 ≤ k ≤ 10^9).

-----Output-----

You should output a graph G with n vertexes (2 ≤ n ≤ 1000). There must be exactly k shortest paths between vertex 1 and vertex 2 of the graph.

The first line must contain an integer n. Then adjacency matrix G with n rows and n columns must follow. Each element of the matrix must be 'N' or 'Y'. If G_{ij} is 'Y', then graph G has a edge connecting vertex i and vertex j. Consider the graph vertexes are numbered from 1 to n.

The graph must be undirected and simple: G_{ii} = 'N' and G_{ij} = G_{ji} must hold. And there must be at least one path between vertex 1 and vertex 2. It's guaranteed that the answer exists. If there multiple correct answers, you can output any of them.

-----Examples-----
Input
2
Output
4
NNYY
NNYY
YYNN
YYNN
Input
9
Output
8
NNYYYNNN
NNNNNYYY
YNNNNYYY
YNNNNYYY
YNNNNYYY
NYYYYNNN
NYYYYNNN
NYYYYNNN
Input
1
Output
2
NY
YN

-----Note-----

In first example, there are 2 shortest paths: 1-3-2 and 1-4-2.

In second example, there are 9 shortest paths: 1-3-6-2, 1-3-7-2, 1-3-8-2, 1-4-6-2, 1-4-7-2, 1-4-8-2, 1-5-6-2, 1-5-7-2, 1-5-8-2.

N = int(input())
b = bin(N)[2:][::-1]
count = len(b)-1

def print_matrix(m):
    print(len(m))
    for i in range(len(m)):
        print("".join(m[i]))

m = [['N' for i in range(2*(len(b))+count)] for j in range(2*(len(b))+count)]
for i in range(count-1):
    val = len(m)-count+i
    m[val][val+1] = 'Y'
    m[val+1][val] = 'Y'

if count>0:
    m[len(m)-1][1] = 'Y'
    m[1][len(m)-1] = 'Y'

#print_matrix(m)
c = 0
c2 = len(m)-count
for i in range(0, len(m)-count, 2):
    if i >= len(m)-2-count and i != 0:
        m[i][1] = 'Y'
        m[i+1][1] = 'Y'
        m[1][i+1] = 'Y'
        m[1][i] = 'Y'
    elif i < len(m)-2-count:
        m[i][i+2] = 'Y'
        m[i][i+3] = 'Y'
        m[i+2][i] = 'Y'
        m[i+3][i] = 'Y'
        if i != 0:
       	    m[i+1][i+2] = 'Y'
       	    m[i+1][i+3] = 'Y'
       	    m[i+2][i+1] = 'Y'
       	    m[i+3][i+1] = 'Y'
    if b[c] =='1':
        if i == len(m)-count-2:
            c2 = 1
        #print_matrix(m)
        m[i][c2] = 'Y'
        m[c2][i] = 'Y'
        if i != 0:
            m[i+1][c2] = 'Y'
            m[c2][i+1] = 'Y'
    c2+=1
        #print_matrix(m)
    c+=1

print(len(m))
for i in range(len(m)):
    print("".join(m[i]))


Solve in Python:
Freddy has a really fat left pinky finger, and every time Freddy tries to type an ```A```, he accidentally hits the CapsLock key!

Given a string that Freddy wants to type, emulate the keyboard misses where each ```A``` supposedly pressed is replaced with CapsLock, and return the string that Freddy actually types. It doesn't matter if the ```A``` in the string is capitalized or not. When CapsLock is enabled, capitalization is reversed, but punctuation is not affected.

Examples:

```
"The quick brown fox jumps over the lazy dog."
-> "The quick brown fox jumps over the lZY DOG."

"The end of the institution, maintenance, and administration of government, is to secure the existence of the body politic, to protect it, and to furnish the individuals who compose it with the power of enjoying in safety and tranquillity their natural rights, and the blessings of life: and whenever these great objects are not obtained, the people have a right to alter the government, and to take measures necessary for their safety, prosperity and happiness."
-> "The end of the institution, mINTENnce, ND dministrTION OF GOVERNMENT, IS TO SECURE THE EXISTENCE OF THE BODY POLITIC, TO PROTECT IT, nd to furnish the individuLS WHO COMPOSE IT WITH THE POWER OF ENJOYING IN Sfety ND TRnquillity their nTURl rights, ND THE BLESSINGS OF LIFE: nd whenever these greT OBJECTS re not obtINED, THE PEOPLE Hve  RIGHT TO lter the government, ND TO Tke meSURES NECESSry for their sFETY, PROSPERITY nd hPPINESS."

"aAaaaaAaaaAAaAa"
-> ""
```

**Note!**

If (Caps Lock is Enabled) and then you (HOLD Shift + alpha character) it will always be the reverse

Examples:
```
(Caps Lock Enabled) + (HOLD Shift + Press 'b') = b
(Caps Lock Disabled) + (HOLD Shift + Press 'b') = B
```

If the given string is `""`, the answer should be evident.

Happy coding!

~~~if:fortran
*NOTE: In Fortran, your returned string is* **not** *permitted to contain any unnecessary leading/trailing whitespace.*
~~~

(Adapted from...

def fat_fingers(string):
    if type(string) != str: return string
    aCnt, chars = 0, []
    for c in string:
        if c in 'aA': aCnt += 1
        else:         chars.append(c.swapcase()) if aCnt&1 else chars.append(c)
    return ''.join(chars)


Solve in Python:
From Wikipedia : "The n-back task is a continuous performance task that is commonly used as an assessment in cognitive neuroscience to measure a part of working memory and working memory capacity. [...] The subject is presented with a sequence of stimuli, and the task consists of indicating when the current stimulus matches the one from n steps earlier in the sequence. The load factor n can be adjusted to make the task more or less difficult."

In this kata, your task is to "teach" your computer to do the n-back task. Specifically, you will be implementing a function that counts the number of "targets" (stimuli that match the one from n steps earlier) in a sequence of digits. Your function will take two parameters :

n, a positive integer equal to the number of steps to look back to find a match
sequence, a sequence of digits containing 0 or more targets

A few hints :

The first digit in a sequence can never be a target
Targets can be "chained" together (e.g., for n = 1 and sequence = [1, 1, 1], there are 2 targets)

def count_targets(n, seq):
    count = 0
    for i in range(n,len(seq)):
        if seq[i] == seq[i-n]: count+=1
    return count


Solve in Python:
From this lesson, we learn about JS static object: ```Math```. It mainly helps us to carry out mathematical calculations. It has a lot of properties and methods. Some of the properties and methods we rarely used. So we only learn some common methods.

The properties of the Math object are some constants, such as PI, on behalf of the approximate value of pi. The usage is ```Math.PI```. I will no longer introduce one by one, please refer to the manual:

  - [Math Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math)

In this lesson we learn three methods to turn a number into an integer: ```round()```, ```ceil()``` and ```floor()```.

Their definitions and detailed information:

- [Math.round()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round)
- [Math.ceil()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/ceil)
- [Math.floor()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor)

First of all, we have to understand the first thing, all the methods of the Math object are static methods. It means that you need to use the Math method like this: ```Math.round(1.23)```. Not like this: ```(1.23).round()```.

Here we use some examples to understand their usage:

We can see, ```ceil()``` always rounding up to get a large integer; ```floor()``` always rounding down to get a small integer; ```round()``` according to the fractional part and round it to integer.

When the parameter is negative, they still works:
It should be noted that they are not working on the fractional part. If you want to keep two decimal places or otherwise, you should use [Methods of Number object--toFixed(), toExponential() and toPrecision()](http://www.codewars.com/kata/57256064856584bc47000611), or use the following techniques:
In the example above, we first multiply the number by 100, and then round it. the final result is to retain two decimal places.

Ok, lesson is over....

def round_it(n):
    addition = 0
    temp = str(n).split(".")
    if len(temp) != 2: return n
    if len(temp[0]) < len(temp[1]):
        return int(temp[0]) + 1
    if len(temp[0]) > len(temp[1]):
        return int(temp[0])
    return round(n)


Solve in Python:
From wikipedia

In number theory and combinatorics, a partition of a positive integer n, also called an integer partition,
is a way of writing n as a sum of positive integers.
Two sums that differ only in the order of their summands are considered the **same** partition.

For example, 4 can be partitioned in five distinct ways:

`4, 3 + 1, 2 + 2, 2 + 1 + 1, 1 + 1 + 1 + 1`.

We can write:

`enum(4) -> [[4],[3,1],[2,2],[2,1,1],[1,1,1,1]]` and

`enum(5) -> [[5],[4,1],[3,2],[3,1,1],[2,2,1],[2,1,1,1],[1,1,1,1,1]]`.

The number of parts in a partition grows very fast.
For n = 50 number of parts is `204226`, for 80 it is `15,796,476`
It would be too long to tests answers with arrays of such size. So our task is the following:

1 - n being given (n integer, 1 <= n <= 50) calculate enum(n) ie the partition of n.
We will obtain something like that:
`enum(n) -> [[n],[n-1,1],[n-2,2],...,[1,1,...,1]]` (order of array and sub-arrays
doesn't matter). This part is not tested.

2 - For each sub-array of enum(n) calculate its product.
If n = 5 we'll obtain **after removing duplicates and sorting**:

`prod(5) -> [1,2,3,4,5,6]`

`prod(8) -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 16, 18]`

If n = 40 prod(n) has a length of `2699` hence the tests will not verify such arrays.
Instead our task number 3 is:

3 - return the range, the average and the median of prod(n) in the following form
(example for n = 5):

`"Range: 5 Average: 3.50 Median: 3.50"`

Range is an integer, Average and Median are float numbers rounded to two decimal
places (".2f" in some languages).

#Notes:
`Range` : difference between the highest and lowest values.

`Mean or Average` : To calculate mean, add together all of the numbers
in a set and then divide the sum by the total count of numbers.

`Median` : The median is the number separating the higher half
of a data sample from the lower half.
(https://en.wikipedia.org/wiki/Median)

#Hints:
Try to optimize your program to avoid timing out.

Memoization can be helpful but it is not mandatory for...

from functools import lru_cache, reduce
from operator import or_
from statistics import mean, median

@lru_cache(maxsize=None)
def prod(n, x):
    if n < 0:
        return set()
    return reduce(or_, ({i*s for s in prod(n-i, i)} for i in range(2, x+1)), {1})

def part(n):
    xs = prod(n, n)
    return f"Range: {max(xs) - min(xs)} Average: {mean(xs):.2f} Median: {median(xs):.2f}"


Solve in Python:
Galileo's latest project involves determining the density of stars in certain regions of the sky. For this purpose he started looking for datasets online, and discovered a dataset on Newton's blog. Newton had decomposed the night sky into a Voronoi tessellation with the generators arranged in a grid. He has stored the number of stars in a Voronoi cell at a position in a matrix that corresponds to the position of the generator in the grid.
This dataset does not directly help Galileo, because he needs to be able to query the number of stars in a rectangular portion of the sky. Galileo tried to write a program that does this on his own, but it turned out to be too slow. Can you help him?

-----Input Format-----
The first line contains two integers n and m that denote the height and width of the matrix respectively. This is followed by  n lines each containing m integers each.
The line following this would contain a single integer t, the number of queries to be run. Each query line consists of 4 integers px, py, qx, qy. The first two integers denote the row and column numbers of the upper left corner of the rectangular region, and the second pair of numbers correspond to the lower right corner.

-----Output Format-----
For each query output a single line containing the number of stars in that rectangular region.

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

3 3
10 10 10
10 10 10
10 10 10
4
1 1 1 1
1 1 3 3
2 1 3 3
3 1 3 3

Output:

10
90
60
30

m,n = [int(i) for i in input().split()]
a = []
for i in range (0,m):
 x = [int(j) for j in input().split()]
 a.append (x)

t = int(input())
for ctr in range(0,t):
 sum = 0
 x1, y1, x2, y2 = [int(i)-1 for i in input().split()]
 for i in range(x1, x2+1):
  for j in range(y1,y2+1):
   sum += a[i][j]
 print(sum)


Solve in Python:
Ganesh lives in Gopalmath. He is looking for Jojo. So he decides to collect Aadhar Card Information of all the citizens of India from UIDAI.
Someone told Ganesh that the sum of all the digits of Jojo’s Aadhar number is divisible by 10 and it is greater than zero. After finding all Aadhar numbers which are divisible by 10, Jojo’s Aadhar number is $N$th smallest Aadhar number. Hence, Ganesh wants to find Jojo’s  Aadhar number which satisfies all of the above conditions. (In this chaotic world, Aadhar numbers can be any natural number.)
However, Guruji refused Ganesh to carry out this task, because he is weak in Maths. Therefore, Ganesh assigns this task to Paritoshbhai who possesses excellent Mathematical skills. Since Paritoshbhai is busy in his jewellery business, help him in this task.

-----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 and only line of each test case contains a single integer N.

-----Output:-----
For each test case, print a single line containing Aadhar number of Jojo.

-----Constraints-----
- $1 \leq T \leq 1000$
- $1 \leq N \leq 10^{100,000}$

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

-----Sample Output:-----
37

for _ in range(int(input())):
 N = input()
 num = list(N)
 s=0
 for n in num:
  if n.isnumeric():
   s+=int(n)
 #print(s)
 x=(10-s%10)%10
 print(int(N)*10+int(x))


Solve in Python:
Gargi is thinking of a solution to a problem. Meanwhile, her friend asks her to solve another problem. Since Gargi is busy in her own problem, she seeks your help to solve the new problem.

You are given a string S containing characters a-z (lower case letters) only. You need to change the string to a new string consisting of only one letter from a-z.

For a given character S[i] in the string, if you change it to a character having lower ASCII value than the character S[i], you gain points equal to the difference in ASCII value of the old character and the new character. Similarly, for a given character S[j] in the string, if you change it to a character having higher ASCII value than the character S[j], you lose points equal to the difference in ASCII value of the old character and the new character.

However, Gargi does not like gaining or losing points. She has asked you to change the string in such a way that the total losing or gaining of points at the end of the string conversion is minimum.

Give Gargi the absolute value of the points you have at the end of the string conversion.

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

The first line of each of the T test case contains a string S containing only lower case characters (a-z)

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

-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ |S| ≤ 100000

-----Example-----
Input:
1
abba

Output:
2

-----Explanation-----
Example case 1. The new string can be aaaa where you have +2 points at the end of string conversion or it can be bbbb where you have -2 points at the end of string conversion. Hence the output is 2.

for t in range(int(input())):
 s = input()
 a = [0]*26
 for c in s:
  for i in range(26):
   a[i] += ord(c)-(ord('a')+i)
 m = float("inf")
 for i in a:
  m = min(m, abs(i))
 print(m)


Solve in Python:
Gematria is an Assyro-Babylonian-Greek system of code and numerology later adopted into Jewish culture. The system assigns numerical value to a word or a phrase in the belief that words or phrases with identical numerical values bear some relation to each other or bear some relation to the number itself. While more commonly used on Hebrew words, there is also an English version.

Each letter has a value and the gematrian value of a word or a phrase is the sum of those values. The code takes a word or an expression and returns the gematrian value of it.

The calculation is case insensitive and counts no spaces.

Example: The gematrian value of "love" is 20+50+700+5 = 775

These are the values of the different letters:

a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9, k=10, l=20,
m=30, n=40, o=50, p=60, q=70, r=80, s=90, t=100, u=200,
x=300, y=400, z=500, j=600, v=700, w=900


Solve in Python:
General primality test are often computationally expensive, so in the biggest prime number race the idea is to study special sub-families of prime number and develop more effective tests for them.

[Mersenne Primes](https://en.wikipedia.org/wiki/Mersenne_prime) are prime numbers of the form: Mn = 2^(n) - 1. So far, 49 of them was found between M2 (3) and M74,207,281 which contains 22,338,618 digits and is (by September 2015) the biggest known prime. It has been found by GIMPS (Great Internet Mersenne Prime Search), wich use the test srudied here. (plus heuristics mentionned below)

Lucas and Lehmer have developed a [simple test](https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test) for Mersenne primes:

> for `p` (an odd prime), the Mersenne number Mp is prime if and only if `S(p − 1) = 0 mod Mp`,

>where `S(n + 1) = S(n) * S(n) − 2` and `S(1) = 4`

The goal of this kata is to implement this test. Given an integer `>=2`, the program should calculate the sequence `S(n)` up to `p-1` and calculate the remainder modulo `Mp`, then return `True` or `False` as a result of the test. The case `n = 2` should return `True`.

You should take advantage of the fact that:

```k = (k mod 2^n + floor(k/2^n)) mod Mn```

Or in other words, if we take the least significant `n` bits of `k`, and add the remaining bits of `k`, and then do this repeatedly until at most `n` bits remain, we can compute the remainder after dividing `k` by the Mersenne number `2^n−1` without using division.

This test can be improved using the fact that if `n` is not prime, `2^n-1` will not be prime. So in theory you can test for the primality of `n` beforehand. But in practice the test for the primality of `n` will rapidly outgrow in difficulty the Lucas-Lehmer test. So we can only use heuristics to rule out `n` with small factors but not complete factorization algorithm. You don't need to implement such heuristics here.

The rapid growth of `s^2` makes javascript reach its integer limit quickly (coherent result for `n = 13`, but not...

def lucas_lehmer(n):
    if n == 2:
        return True
    m = 2 ** n - 1
    s = 4
    for i in range(2, n):
        ss = s * s
        s = (ss >> n) + (ss & m)
        if s >= m:
            s -= m
        s -= 2
    return s == 0


Solve in Python:
Generate and return **all** possible increasing arithmetic progressions of six primes `[a, b, c, d, e, f]` between the given limits. Note: the upper and lower limits are inclusive.

An arithmetic progression is a sequence where the difference between consecutive numbers is the same, such as: 2, 4, 6, 8.

A prime number is a number that is divisible only by itself and 1 (e.g. 2, 3, 5, 7, 11)

Your solutions should be returned as lists inside a list in ascending order of the first item (if there are multiple lists with same first item, return in ascending order for the second item etc) are the e.g: `[ [a, b, c, d, e, f], [g, h, i, j, k, l] ]` where `a < g`. If there are no solutions, return an empty list: `[]`

## Examples

from bisect import *

n=10000
sieve, PRIMES = [0]*(n+1), []
for i in range(2, n+1):
    if not sieve[i]:
        PRIMES.append(i)
        for j in range(i**2, n+1, i): sieve[j] = 1

def primes_a_p(low, high):
    subPrimes = PRIMES[bisect_left(PRIMES,low):bisect_right(PRIMES,high)]
    ans, sP   = [], set(subPrimes)

    for i,p in enumerate(subPrimes):
        for q in subPrimes[i+1:]:
            d = q-p
            prog = [p+d*n for n in range(6)]
            if set(prog) <= sP: ans.append(prog)
    return ans


Solve in Python:
Gennady is one of the best child dentists in Berland. Today n children got an appointment with him, they lined up in front of his office.

All children love to cry loudly at the reception at the dentist. We enumerate the children with integers from 1 to n in the order they go in the line. Every child is associated with the value of his cofidence p_{i}. The children take turns one after another to come into the office; each time the child that is the first in the line goes to the doctor.

While Gennady treats the teeth of the i-th child, the child is crying with the volume of v_{i}. At that the confidence of the first child in the line is reduced by the amount of v_{i}, the second one — by value v_{i} - 1, and so on. The children in the queue after the v_{i}-th child almost do not hear the crying, so their confidence remains unchanged.

If at any point in time the confidence of the j-th child is less than zero, he begins to cry with the volume of d_{j} and leaves the line, running towards the exit, without going to the doctor's office. At this the confidence of all the children after the j-th one in the line is reduced by the amount of d_{j}.

All these events occur immediately one after the other in some order. Some cries may lead to other cries, causing a chain reaction. Once in the hallway it is quiet, the child, who is first in the line, goes into the doctor's office.

Help Gennady the Dentist to determine the numbers of kids, whose teeth he will cure. Print their numbers in the chronological order.

-----Input-----

The first line of the input contains a positive integer n (1 ≤ n ≤ 4000) — the number of kids in the line.

Next n lines contain three integers each v_{i}, d_{i}, p_{i} (1 ≤ v_{i}, d_{i}, p_{i} ≤ 10^6) — the volume of the cry in the doctor's office, the volume of the cry in the hall and the confidence of the i-th child.

-----Output-----

In the first line print number k — the number of children whose teeth Gennady will cure.

In the second line print k integers — the numbers of the...

n=int(input())
a=[[i+1]+list(map(int,input().split())) for i in range(n)]
ans=[]
def go():
  pp=0
  nonlocal a
  for j in range(len(a)):
    a[j][3]-=pp
    if a[j][3]<0: pp+=a[j][2]
  a=[a[i] for i in range(len(a)) if a[i][3]>=0]
  return len(a)

while go():
  nom,v,d,p=a.pop(0)
  ans+=[str(nom)]
  j=0
  while v>0 and j<len(a): a[j][3]-=v; v-=1; j+=1
print(len(ans))
print(' '.join(ans))


Solve in Python:
Genos recently installed the game Zuma on his phone. In Zuma there exists a line of n gemstones, the i-th of which has color c_{i}. The goal of the game is to destroy all the gemstones in the line as quickly as possible.

In one second, Genos is able to choose exactly one continuous substring of colored gemstones that is a palindrome and remove it from the line. After the substring is removed, the remaining gemstones shift to form a solid line again. What is the minimum number of seconds needed to destroy the entire line?

Let us remind, that the string (or substring) is called palindrome, if it reads same backwards or forward. In our case this means the color of the first gemstone is equal to the color of the last one, the color of the second gemstone is equal to the color of the next to last and so on.

-----Input-----

The first line of input contains a single integer n (1 ≤ n ≤ 500) — the number of gemstones.

The second line contains n space-separated integers, the i-th of which is c_{i} (1 ≤ c_{i} ≤ n) — the color of the i-th gemstone in a line.

-----Output-----

Print a single integer — the minimum number of seconds needed to destroy the entire line.

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

Output
1

Input
3
1 2 3

Output
3

Input
7
1 4 4 2 3 2 1

Output
2

-----Note-----

In the first sample, Genos can destroy the entire line in one second.

In the second sample, Genos can only destroy one gemstone at a time, so destroying three gemstones takes three seconds.

In the third sample, to achieve the optimal time of two seconds, destroy palindrome 4 4 first and then destroy palindrome 1 2 3 2 1.

n = int(input())
t = tuple(map(int, input().split()))
m = [[1] * n for i in range(n + 1)]
for d in range(2, n + 1):
    for i in range(n - d + 1):
        m[d][i] = min(m[x][i] + m[d - x][i + x] for x in range(1, d))
        if t[i] == t[i + d - 1]: m[d][i] = min(m[d][i], m[d - 2][i + 1])
print(m[n][0])


Solve in Python:
Gerald plays the following game. He has a checkered field of size n × n cells, where m various cells are banned. Before the game, he has to put a few chips on some border (but not corner) board cells. Then for n - 1 minutes, Gerald every minute moves each chip into an adjacent cell. He moves each chip from its original edge to the opposite edge. Gerald loses in this game in each of the three cases:  At least one of the chips at least once fell to the banned cell.  At least once two chips were on the same cell.  At least once two chips swapped in a minute (for example, if you stand two chips on two opposite border cells of a row with even length, this situation happens in the middle of the row).

In that case he loses and earns 0 points. When nothing like that happened, he wins and earns the number of points equal to the number of chips he managed to put on the board. Help Gerald earn the most points.

-----Input-----

The first line contains two space-separated integers n and m (2 ≤ n ≤ 1000, 0 ≤ m ≤ 10^5) — the size of the field and the number of banned cells. Next m lines each contain two space-separated integers. Specifically, the i-th of these lines contains numbers x_{i} and y_{i} (1 ≤ x_{i}, y_{i} ≤ n) — the coordinates of the i-th banned cell. All given cells are distinct.

Consider the field rows numbered from top to bottom from 1 to n, and the columns — from left to right from 1 to n.

-----Output-----

Print a single integer — the maximum points Gerald can earn in this game.

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

Output
0

Input
3 0

Output
1

Input
4 3
3 1
3 2
3 3

Output
1

-----Note-----

In the first test the answer equals zero as we can't put chips into the corner cells.

In the second sample we can place one chip into either cell (1, 2), or cell (3, 2), or cell (2, 1), or cell (2, 3). We cannot place two chips.

In the third sample we can only place one chip into either cell (2, 1), or cell (2, 4).

I=input
n,m=list(map(int,I().split()))
b=[1]*n*2
b[0]=b[n-1]=b[n]=b[2*n-1]=0
for i in range(m):
    r,c=list(map(int,I().split()))
    b[r-1]=b[n+c-1]=0
if n%2 and b[n//2] and b[n+n//2]:b[n//2]=0
print(sum(b))

# Made By Mostafa_Khaled


Solve in Python:
German mathematician Christian Goldbach (1690-1764) [conjectured](https://en.wikipedia.org/wiki/Goldbach%27s_conjecture) that every even number greater than 2 can be represented by the sum of two prime numbers. For example, `10` can be represented as `3+7` or `5+5`.

Your job is to make the function return a list containing all unique possible representations of `n` in an increasing order if `n` is an even integer; if `n` is odd, return an empty list. Hence, the first addend must always be less than or equal to the second to avoid duplicates.

Constraints : `2 < n < 32000` and `n` is even

## Examples
```
26  -->  ['3+23', '7+19', '13+13']

100 -->  ['3+97', '11+89', '17+83', '29+71', '41+59', '47+53']

7   -->  []
```

f=lambda n:n>1and all(n%d for d in range(2,int(n**.5)+1))
goldbach_partitions=lambda n:[]if n%2else['%d+%d'%(p,n-p)for p in range(n//2+1)if f(p)*f(n-p)]


Solve in Python:
Get excited, folks, because it is time for the final match of Codechef Premier League (CPL)!
Mike and Tracy also want to watch the grand finale, but unfortunately, they could not get tickets to the match. However, Mike is not someone who gives up so easily — he has a plan to watch the match.
The field where the match is played is surrounded by a wall with height $K$. Outside, there are $N$ boxes (numbered $1$ through $N$). For each valid $i$, the $i$-th box has a height $H_i$.
Mike wants to take some boxes and stack them on top of each other to build two towers. The height of each tower is the sum of heights of all the boxes that form it. Of course, no box may be in both towers. The height of each tower should be at least $K$. Then Mike can climb on top of one tower and Tracy on top of the other, and they can watch the match uninterrupted!
While Mike is busy stacking the boxes, Tracy would like to know the smallest number of boxes required to build two towers such that each of them has height at least $K$, or at least that it is impossible to build such towers. Can you help Tracy?

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

-----Output-----
For each test case, print a single line containing one integer — the smallest number of boxes required to build two towers, or $-1$ if it is impossible.

-----Constraints-----
- $1 \leq T \leq 5$
- $1 \leq N, K \leq 4,000$
- $1 \leq H_i \leq 10^5$ for each valid $i$

-----Subtasks-----
Subtask #1 (30 points):
- $1 \leq N, K \leq 100$
- $1 \leq H_i \leq 100$ for each valid $i$
Subtask #2 (70 points): original constraints

-----Example Input-----
2
8 38
7 8 19 7 8 7 10 20
4 5
2 10 4 9

-----Example Output-----
7
2

-----Explanation-----
Example case 1: The first tower can be built with boxes $8 + 10 +...

def min_boxes(k, boxes):
 sum_ = sum(boxes)
 if sum_ < 2 * k: return -1
 boxes = sorted(boxes, reverse=True)

 n = len(boxes)

 table = [[-1 for _ in range(sum_ + 1)] for _ in range(n + 1)]

 table[0][:] = [False for _ in range(sum_ + 1)]

 for i in range(n + 1):
  table[i][0] = True

 for i in range(1, n + 1):
  for j in range(1, sum_ + 1):
   if boxes[i - 1] > j:
    table[i][j] = table[i - 1][j]
   else:
    table[i][j] = table[i - 1][j] or table[i - 1][j - boxes[i - 1]]

 i = 0
 x = boxes[0]
 while x < 2 * k:
  i += 1
  x += boxes[i]

 if i == 1:
  i += 1

 while i < n + 1:
  sum_till_here = sum(boxes[ : i])
  for j in range(k, sum_ + 1):
   if table[i][j]:
    if sum_till_here - j >= k:
     return i
  i += 1

 return -1

def __starting_point():
 test_cases = int(input())
 while test_cases:

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

  print(min_boxes(k, boxes))

  test_cases -= 1
__starting_point()


Solve in Python:
Get n seconds before the target time. See Example Test Cases about the format.

import datetime

def seconds_ago(s,n):
    d = datetime.datetime.strptime(s, '%Y-%m-%d %H:%M:%S') + datetime.timedelta(seconds=-n)
    return d.strftime('%Y').rjust(4, '0') + d.strftime('-%m-%d %H:%M:%S')


Solve in Python:
Get the next prime number!

You will get a number`n` (>= 0) and your task is to find the next prime number.

Make sure to optimize your code: there will numbers tested up to about `10^12`.

## Examples

```
5   =>  7
12  =>  13
```

def is_prime(n):
    if n in (2, 3, 5):
        return True
    elif n < 5:
        return False
    elif n%2:
        i = 3
        flag = True
        while i*i <= n:
            if n%i == 0:
                return False
            i += 2
        return True
    else:
        return False

def nextPrime(n):
    i = n+1
    while not is_prime(i):
        i+=1
    return i


Solve in Python:
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win?

The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process.

-----Input-----

The first line of the input contains three integers: h, w, n — the sides of the board and the number of black cells (1 ≤ h, w ≤ 10^5, 1 ≤ n ≤ 2000).

Next n lines contain the description of black cells. The i-th of these lines contains numbers r_{i}, c_{i} (1 ≤ r_{i} ≤ h, 1 ≤ c_{i} ≤ w) — the number of the row and column of the i-th cell.

It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct.

-----Output-----

Print a single line — the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 10^9 + 7.

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

Output
2

Input
100 100 3
15 16
16 15
99 88

Output
545732279


Solve in Python:
Gigi is a clever monkey, living in the zoo, his teacher (animal keeper) recently taught him some knowledge of "0".

In Gigi's eyes, "0" is a character contains some circle(maybe one, maybe two).

So, a is a "0",b is a "0",6 is also a "0"，and 8 have two "0" ,etc...

Now, write some code to count how many "0"s in the text.

Let us see who is smarter? You ? or monkey?

Input always be a string(including words numbers and symbols)，You don't need to verify it, but pay attention to the difference between uppercase and lowercase letters.

Here is a table of characters：

one zeroabdegopq069DOPQR         () <-- A pair of braces as a zerotwo zero%&B8

Output will be a number of "0".

def countzero(string):
    return sum(map("abdegopq069DOPQR%&B8%&B8".count, string.replace("()", "0")))


Solve in Python:
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.

Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.

The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.

Each customer is characterized by three values: $t_i$ — the time (in minutes) when the $i$-th customer visits the restaurant, $l_i$ — the lower bound of their preferred temperature range, and $h_i$ — the upper bound of their preferred temperature range.

A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $i$-th customer is satisfied if and only if the temperature is between $l_i$ and $h_i$ (inclusive) in the $t_i$-th minute.

Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.

-----Input-----

Each test contains one or more test cases. The first line contains the number of test cases $q$ ($1 \le q \le 500$). Description of the test cases follows.

The first line of each test case contains two integers $n$ and $m$ ($1 \le n \le 100$, $-10^9 \le m \le 10^9$), where $n$ is the number of reserved customers and $m$ is the initial temperature of the restaurant.

Next, $n$ lines follow. The $i$-th line of them contains three integers $t_i$, $l_i$, and $h_i$ ($1 \le t_i \le 10^9$, $-10^9 \le l_i \le h_i \le 10^9$), where $t_i$ is the time...

import sys
input = sys.stdin.readline

Q = int(input())
Query = []
for _ in range(Q):
    N, M = map(int, input().split())
    TLR = [list(map(int, input().split())) for _ in range(N)]
    Query.append((N, M, TLR))

for N, M, TLR in Query:
    TLR.sort()
    large = M
    small = M
    pret = 0
    ok = True
    for t, l, r in TLR:
        delta = t - pret
        large += delta
        small -= delta

        if large < l or r < small:
            ok = False
            break
        large = min(large, r)
        small = max(small, l)

        pret = t

    print("YES" if ok else "NO")


Solve in Python:
Gildong recently learned how to find the longest increasing subsequence (LIS) in $O(n\log{n})$ time for a sequence of length $n$. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of $n$ distinct integers between $1$ and $n$, inclusive, to test his code with your output.

The quiz is as follows.

Gildong provides a string of length $n-1$, consisting of characters '<' and '>' only. The $i$-th (1-indexed) character is the comparison result between the $i$-th element and the $i+1$-st element of the sequence. If the $i$-th character of the string is '<', then the $i$-th element of the sequence is less than the $i+1$-st element. If the $i$-th character of the string is '>', then the $i$-th element of the sequence is greater than the $i+1$-st element.

He wants you to find two possible sequences (not necessarily distinct) consisting of $n$ distinct integers between $1$ and $n$, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.

-----Input-----

Each test contains one or more test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^4$).

Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is $n$ ($2 \le n \le 2 \cdot 10^5$), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is $n-1$.

It is guaranteed that the sum of all $n$ in all test cases doesn't exceed $2 \cdot 10^5$.

-----Output-----

For each test case, print two lines with $n$ integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are...

from sys import stdin,stderr
def rl():
    return [int(w) for w in stdin.readline().split()]

def p1(n, s, le):
    r = []
    b = i = 0
    while i < n:
        try:
            ni = s.index(le, i) + 1
        except ValueError:
            ni = n
        r += list(range(ni, i, -1))
        i = ni
    return r

t, = rl()
for _ in range(t):
    n,s = stdin.readline().split()
    n = int(n)
    print(*(n - x + 1 for x in p1(n, s, '>')))
    print(*p1(n, s, '<'))


Solve in Python:
Give me Biscuit

Sunny wants to make slices of biscuit of size c * d into identical pieces.

but each piece is a square having maximum possible side length with no left over piece of biscuit.

Input Format

The first line contains an integer N.

N lines follow. Each line contains two space separated integers c and d.

which denote length and breadth of the biscuit.

Constraints

1 <= N <= 1000

1 <= c,d <= 1000
Output Format

N lines, each containing an integer that denotes the number of squares of maximum size, when the biscuit is cut as per the given condition.

Sample Input

2

2 2

6 9

Sample Output

1

6

Explanation

The 1st testcase has a biscuit whose original dimensions are 2 X 2, the biscuit is uncut and is a square.

Hence the answer is 1.

The 2nd testcase has a biscuit of size 6 X 9 . We can cut it into 54 squares of size 1 X 1 , 6 of size 3 X 3 . For other sizes we will have leftovers.

Hence, the number of squares of maximum size that can be cut is 6.

import math
for _ in range(int(input())):
 a,b=map(int,input().split())
 g=math.gcd(a,b)
 res=((a*b)/(g*g))
 print(int(res))


Solve in Python:
Give me Chocolate

Anushka wants to buy chocolates.there are many chocolates in front of her, tagged with their prices.

Anushka has only a certain amount to spend, and she wants to maximize the number of chocolates she buys with this money.

Given a list of prices and an amount to spend, what is the maximum number of chocolates Anushka can buy?

For example,

if prices =[1,2,3,4]
and Anushka has k=7 to spend, she can buy items [1,2,3] for 6 , or [3,4] for 7 units of currency. she would choose the first group of 3 items.

Input Format

The first line contains two integers, n and k , the number of priced chocolates and the amount Anushka has to spend.

The next line contains n space-separated integers prices[i]

Constraints

1<= n <= 105

1<= k <= 109

1<= prices[i] <= 109

A chocolate can't be bought multiple times.

Output Format

An integer that denotes the maximum number of chocolates Anushka can buy for her.

Sample Input

7 50

1 12 5 111 200 1000 10

Sample Output

4

Explanation

she can buy only 4 chocolatess at most. These chocolates have the following prices: 1, 12, 5, 10.

# cook your dish here
n,k=list(map(int,input().split()))
a=list(map(int,input().split()))
a.sort()
s=0
i=0
while(k>=0 and i<len(a)):
 if k-a[i]>=0:
  k=k-a[i]
  s+=1
  i+=1
 else:
  i+=1
print(s)


Solve in Python:
Give the summation of all even numbers in a Fibonacci sequence up to, but not including, the maximum value.

The Fibonacci sequence is a series of numbers where the next value is the addition of the previous two values. The series starts with 0 and 1:

0 1 1 2 3 5 8 13 21...

For example:
```python
eve_fib(0)==0
eve_fib(33)==10
eve_fib(25997544)==19544084
```

def even_fib(m):
    a,b,c=0,1,0
    while b<m:
        if b%2==0: c+=b
        a,b=b,a+b
    return c


Solve in Python:
Given $N *M$ matrix containing elements either $1$ or $0$ and string S of length $N+M-1$ containing characters $0$ or $1$. Your task is to make all the  paths from top left corner to the  bottom right corner of the matrix same as the  given string .You can perform two types of operations any time .Path means you can only allow it to take right or down.
Operations :
- Changing the matrix elements from $1$ to $0$ or vice versa  will cost P rupees per element.
- Changing the character of string  from $1$ to $0$ or vice versa  will cost Q rupees per character.
You have to  minimize the cost, (possibly 0) .

-----Input:-----
- First line of input contains the total no. of test cases $T$.
- For every test case, first line of input contains two spaced positive integers, $N$ and $M$.
- Next $N$ lines contains $M$-spaced integers which can be only $0$ or $1$.
- Next line of input contains a string $S$ of length $N+M-1$.
- Last line of input contains two spaced integers, $P$ and $Q$.

-----Output:-----
- $You$ $have$ $to$ $print$ $the$ $minimum$ $cost .$

-----Constraints-----
- $1 \leq T \leq 20$
- $1 \leq N, M \leq 1000$
- $|S| = N+M-1$
- $0 \leq P, Q \leq 1000$The input/output is quite large, please use fast reading and writing methods.

-----Sample Input-----
2
3 3
1 0 1
0 1 1
1 1 0
10111
10 5
3 3
0 0 1
0 1 1
0 1 1
00011
2 9

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

-----Explanation-----
- You can  change the last element of the matrix and also can change the last element of string but the minimum cost will produce by changing string element , therefore it will cost 5 rupees.

# cook your dish here
import math

read = lambda : list(map(int,input().strip().split()))
read_arr = lambda x: [read() for _ in range(x)]
ans = []

t = int(input().strip())

def mincost(n,m,arr,s,p,q):
 cost = 0
 for t in range(n+m -1):
  cc = s[t]
  curr = 0
  ct = 0
  start = max(0,t-(m-1))
  end = min(n,t+1)
  for i in range(start,end):
   j = t - i;
   if j >= m:
    break;
   curr += (cc^(arr[i][j]))
   ct += 1
  cost1 = q + ((ct - curr) * p)
  cost2 = (curr * p)
  cost += min(cost1,cost2)
 return cost;

for i in range(t):
 cn,cm = read()
 carr = read_arr(cn)
 cs = [int(x) for x in input().strip()]
 cp,cq = read()
 ans.append(mincost(cn,cm,carr,cs,cp,cq))
print("\n".join([str(x) for x in ans]))


Solve in Python:
Given 2 elevators (named "left" and "right") in a building with 3 floors (numbered `0` to `2`), write a function `elevator` accepting 3 arguments (in order):

- `left` - The current floor of the left elevator
- `right` - The current floor of the right elevator
- `call` -  The floor that called an elevator

It should return the name of the elevator closest to the called floor (`"left"`/`"right"`).

In the case where both elevators are equally distant from the called floor, choose the elevator to the right.

You can assume that the inputs will always be valid integers between 0-2.

Examples:

```python
elevator(0, 1, 0) # => "left"
elevator(0, 1, 1) # => "right"
elevator(0, 1, 2) # => "right"
elevator(0, 0, 0) # => "right"
elevator(0, 2, 1) # => "right"
```

def elevator(left, right, call):
    return "left" if (call - left)*(call - left) < (call - right)*(call - right) else "right"


Solve in Python:
Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) such that :

p[0] = start
p[i] and p[i+1] differ by only one bit in their binary representation.
p[0] and p[2^n -1] must also differ by only one bit in their binary representation.

Example 1:
Input: n = 2, start = 3
Output: [3,2,0,1]
Explanation: The binary representation of the permutation is (11,10,00,01).
All the adjacent element differ by one bit. Another valid permutation is [3,1,0,2]

Example 2:
Input: n = 3, start = 2
Output: [2,6,7,5,4,0,1,3]
Explanation: The binary representation of the permutation is (010,110,111,101,100,000,001,011).

Constraints:

1 <= n <= 16
0 <= start < 2 ^ n

class Solution:
    def circularPermutation(self, n: int, start: int) -> List[int]:
        return [ start^i^(i>>1) for i in range(1<<n) ]


Solve in Python:
Given 2 strings, `a` and `b`, return a string of the form short+long+short, with the shorter string on the outside
and the longer string on the inside. The strings will not be the same length, but they may be empty ( length `0` ).

For example:

```python
solution("1", "22") # returns "1221"
solution("22", "1") # returns "1221"
```

def solution(a, b):
    if len(a) > len(b):
        return ''.join([b,a,b])
    elif len(b) > len(a):
        return ''.join([a,b,a])
    else:
        return None


Solve in Python:
Given 2 strings, `a` and `b`, return a string of the form: `shorter+reverse(longer)+shorter.`

In other words, the shortest string has to be put as prefix and as suffix of the reverse of the longest.

Strings `a` and `b` may be empty, but not null (In C# strings may also be null. Treat them as if they are empty.).
If `a` and `b` have the same length treat `a` as the longer producing `b+reverse(a)+b`

def shorter_reverse_longer(a,b):
  return a+b[::-1]+a if len(b)>len(a) else b+a[::-1]+b


Solve in Python:
Given 2 strings, your job is to find out if there is a substring that appears in both strings. You will return true if you find a substring that appears in both strings, or false if you do not. We only care about substrings that are longer than one letter long.

#Examples:

````
*Example 1*
SubstringTest("Something","Fun"); //Returns false

*Example 2*
SubstringTest("Something","Home"); //Returns true
````
In the above example, example 2 returns true because both of the inputs contain the substring "me". (so**ME**thing and ho**ME**)
In example 1, the method will return false because something and fun contain no common substrings. (We do not count the 'n' as a substring in this Kata because it is only 1 character long)

#Rules:
Lowercase and uppercase letters are the same. So 'A' == 'a'.
We only count substrings that are > 1 in length.

#Input:
Two strings with both lower and upper cases.
#Output:
A boolean value determining if there is a common substring between the two inputs.

def substring_test(str1, str2):
    a,b = str1.lower(), str2.lower()
    for i in range(len(a)-1):
        if a[i:i+2] in b:
            return True
    return False


Solve in Python:
Given 2n balls of k distinct colors. You will be given an integer array balls of size k where balls[i] is the number of balls of color i.
All the balls will be shuffled uniformly at random, then we will distribute the first n balls to the first box and the remaining n balls to the other box (Please read the explanation of the second example carefully).
Please note that the two boxes are considered different. For example, if we have two balls of colors a and b, and two boxes [] and (), then the distribution [a] (b) is considered different than the distribution [b] (a) (Please read the explanation of the first example carefully).
We want to calculate the probability that the two boxes have the same number of distinct balls.

Example 1:
Input: balls = [1,1]
Output: 1.00000
Explanation: Only 2 ways to divide the balls equally:
- A ball of color 1 to box 1 and a ball of color 2 to box 2
- A ball of color 2 to box 1 and a ball of color 1 to box 2
In both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1

Example 2:
Input: balls = [2,1,1]
Output: 0.66667
Explanation: We have the set of balls [1, 1, 2, 3]
This set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equale probability (i.e. 1/12):
[1,1 / 2,3], [1,1 / 3,2], [1,2 / 1,3], [1,2 / 3,1], [1,3 / 1,2], [1,3 / 2,1], [2,1 / 1,3], [2,1 / 3,1], [2,3 / 1,1], [3,1 / 1,2], [3,1 / 2,1], [3,2 / 1,1]
After that we add the first two balls to the first box and the second two balls to the second box.
We can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box.
Probability is 8/12 = 0.66667

Example 3:
Input: balls = [1,2,1,2]
Output: 0.60000
Explanation: The set of balls is [1, 2, 2, 3, 4, 4]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box.
Probability = 108 / 180 = 0.6

Example 4:
Input: balls = [3,2,1]
Output:...

class Solution:
    def getProbability(self, balls: List[int]) -> float:
        balls_flattened = []
        for i, count in enumerate(balls):
            balls_flattened.extend([i] * count)

        def has_same_distinct_color(perm):
            n = len(perm)
            return len(set(perm[: n // 2])) == len(set(perm[n // 2 :]))

        total = [0]
        same_distinct_color = [0]
        def get_perm(cur, balls):
            if not balls:
                total[0] += 1
                same_distinct_color[0] += has_same_distinct_color(cur)
                return
            for i in range(len(balls)):
                if i > 0 and balls[i] == balls[i - 1]:
                    continue
                get_perm(cur + [balls[i]], balls[:i] + balls[i + 1 :])

        get_perm([], balls_flattened)
        return same_distinct_color[0] / total[0]

    def getProbability(self, balls: List[int]) -> float:

        factorial_cache = [1]
        for i in range(1, sum(balls) + 1):
            factorial_cache.append(factorial_cache[-1] * i)

        def get_perm_count(arr):
            total = factorial_cache[sum(arr)]
            for a in arr:
                total //= factorial_cache[a]
            return total

        total_perms = get_perm_count(balls)
        valid_perms = [0]

        def find_valid_split(n, start, distinct1, group1, distinct2, group2):
            if n == 0:
                if distinct1 == distinct2:
                    valid_perms[0] += get_perm_count(group1) * get_perm_count(group2)
                return

            for i in range(start, len(group1)):
                if group1[i] == 0:
                    continue

                new_num1 = group1[i] - 1
                new_distinct1 = distinct1 if new_num1 > 0 else distinct1 - 1
                new_num2 = group2[i] + 1
                new_distinct2 = distinct2 if new_num2 > 1 else distinct2 + 1
                if new_distinct1 <...


Solve in Python:
Given 3 positives numbers a, b and c. Return the minimum flips required in some bits of a and b to make ( a OR b == c ). (bitwise OR operation).
Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation.

Example 1:

Input: a = 2, b = 6, c = 5
Output: 3
Explanation: After flips a = 1 , b = 4 , c = 5 such that (a OR b == c)
Example 2:
Input: a = 4, b = 2, c = 7
Output: 1

Example 3:
Input: a = 1, b = 2, c = 3
Output: 0

Constraints:

1 <= a <= 10^9
1 <= b <= 10^9
1 <= c <= 10^9

class Solution:
    def minFlips(self, a: int, b: int, c: int) -> int:
        count = 0
        while a or b or c:
            temp = (a & 1) | (b & 1)
            if temp != (c & 1):
                if c & 1:
                    count += 1
                else:
                    if a & 1:
                        count += 1
                    if b & 1:
                        count += 1
            a = a >> 1
            b = b >> 1
            c = c >> 1
        return count


Solve in Python:
Given N, consider a convex N-sided polygon with vertices labelled A[0], A[i], ..., A[N-1] in clockwise order.
Suppose you triangulate the polygon into N-2 triangles.  For each triangle, the value of that triangle is the product of the labels of the vertices, and the total score of the triangulation is the sum of these values over all N-2 triangles in the triangulation.
Return the smallest possible total score that you can achieve with some triangulation of the polygon.

Example 1:
Input: [1,2,3]
Output: 6
Explanation: The polygon is already triangulated, and the score of the only triangle is 6.

Example 2:

Input: [3,7,4,5]
Output: 144
Explanation: There are two triangulations, with possible scores: 3*7*5 + 4*5*7 = 245, or 3*4*5 + 3*4*7 = 144.  The minimum score is 144.

Example 3:
Input: [1,3,1,4,1,5]
Output: 13
Explanation: The minimum score triangulation has score 1*1*3 + 1*1*4 + 1*1*5 + 1*1*1 = 13.

Note:

3 <= A.length <= 50
1 <= A[i] <= 100

class Solution:
    def minScoreTriangulation(self, A: List[int]) -> int:
        memo = {}
        def dp(i, j):
            if (i, j) not in memo:
                memo[i, j] = min([dp(i, k) + dp(k, j) + A[i] * A[j] * A[k] for k in range(i + 1, j)] or [0])
            return memo[i, j]
        return dp(0, len(A) - 1)


Solve in Python:
Given N, count how many permutations of [1, 2, 3, ..., N] satisfy the following property.

Let P1, P2, ..., PN denote the permutation. The property we want to satisfy is that there exists an i between 2 and n-1 (inclusive) such that

- Pj > Pj + 1  ∀    i ≤ j ≤ N - 1.
- Pj > Pj - 1  ∀    2 ≤ j ≤ i.

-----Input-----
First line contains T, the number of test cases. Each test case consists of N in one line.

-----Output-----
For each test case, output the answer modulo 109+7.

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

-----Subtasks-----
- Subtask #1(40 points): 1 ≤ N ≤ 1000
- Subtask #2(60 points): original constraints

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

Output:
0
2

-----Explanation-----

Test case 1:

No permutation satisfies.

Test case 2:

Permutations [1, 3, 2] and [2, 3, 1] satisfy the property.

for _ in range(int(input())):
 n = int(input())
 print(0) if(n==1) else print(pow(2,n-1,10**9+7)-2)


Solve in Python:
Given a (singly) linked list with head node root, write a function to split the linked list into k consecutive linked list "parts".

The length of each part should be as equal as possible: no two parts should have a size differing by more than 1.  This may lead to some parts being null.

The parts should be in order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal parts occurring later.

Return a List of ListNode's representing the linked list parts that are formed.

Examples
1->2->3->4, k = 5 // 5 equal parts
[ [1],
[2],
[3],
[4],
null ]

Example 1:

Input:
root = [1, 2, 3], k = 5
Output: [[1],[2],[3],[],[]]
Explanation:
The input and each element of the output are ListNodes, not arrays.
For example, the input root has root.val = 1, root.next.val = 2, \root.next.next.val = 3, and root.next.next.next = null.
The first element output[0] has output[0].val = 1, output[0].next = null.
The last element output[4] is null, but it's string representation as a ListNode is [].

Example 2:

Input:
root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3
Output: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
Explanation:
The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.

Note:
The length of root will be in the range [0, 1000].
Each value of a node in the input will be an integer in the range [0, 999].
k will be an integer in the range [1, 50].

# Definition for singly-linked list.
 # class ListNode:
 #     def __init__(self, x):
 #         self.val = x
 #         self.next = None
 import math
 class Solution:
     def splitListToParts(self, root, k):
         """
         :type root: ListNode
         :type k: int
         :rtype: List[ListNode]
         """
         def length(node):
             result = 0
             while node is not None:
                 result += 1
                 node = node.next
             return result

         total = length(root)
         result = []
         current = root

         while k > 0:
             l = math.ceil(total / k)
             total -= l
             k -= 1

             if l == 0:
                 result.append(None)
                 continue

             root = current
             for _ in range(l-1):
                 current = current.next
             result.append(root)
             current.next, current = None, current.next

         return result


Solve in Python:
Given a 2D array A, each cell is 0 (representing sea) or 1 (representing land)
A move consists of walking from one land square 4-directionally to another land square, or off the boundary of the grid.
Return the number of land squares in the grid for which we cannot walk off the boundary of the grid in any number of moves.

Example 1:
Input: [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
Output: 3
Explanation:
There are three 1s that are enclosed by 0s, and one 1 that isn't enclosed because its on the boundary.
Example 2:
Input: [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]
Output: 0
Explanation:
All 1s are either on the boundary or can reach the boundary.

Note:

1 <= A.length <= 500
1 <= A[i].length <= 500
0 <= A[i][j] <= 1
All rows have the same size.

class Solution:
    def numEnclaves(self, A: List[List[int]]) -> int:
        dirs = [(0,1),(0,-1),(1,0),(-1,0)]

        self.f = 0
        self.s = set()

        m,n = len(A),len(A[0])

        def rr(j,i):
            if (j,i) in self.s:
                return
            self.s.add((j,i))

            if A[j][i] == 0:
                return
            else:
                for d in dirs:
                    j_new = d[0] + j
                    i_new = d[1] + i
                    if 0 <= j_new < m and 0 <= i_new < n:
                        rr(j_new,i_new)

        for j,row in enumerate(A):
            for i,v in enumerate(row):
                if j == 0 or j == m-1 or i == 0 or i == n-1:
                    rr(j,i)

        f = 0
        for j,row in enumerate(A):
            for i,v in enumerate(row):
                if v == 1 and (j,i) not in self.s:
                    f+=1

        return f


Solve in Python:
Given a 2D array and a number of generations, compute n timesteps of [Conway's Game of Life](http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life).

The rules of the game are:

1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
2. Any live cell with more than three live neighbours dies, as if by overcrowding.
3. Any live cell with two or three live neighbours lives on to the next generation.
4. Any dead cell with exactly three live neighbours becomes a live cell.

Each cell's neighborhood is the 8 cells immediately around it (i.e. [Moore Neighborhood](https://en.wikipedia.org/wiki/Moore_neighborhood)). The universe is infinite in both the x and y dimensions and all cells are initially dead - except for those specified in the arguments. The return value should be a 2d array cropped around all of the living cells. (If there are no living cells, then return `[[]]`.)

For illustration purposes, 0 and 1 will be represented as `░░` and `▓▓` blocks respectively (PHP, **C**: plain black and white squares). You can take advantage of the `htmlize` function to get a text representation of the universe, e.g.:

```python
print(htmlize(cells))
````

~~~if:c
In **C**, the initial dimensions of the GoL universe is passed into your function *by reference* via the pointers `rowptr` and `colptr`.  When expanding/contracting the GoL universe, please keep track of the dimensions of the modified grid through these two variables.
~~~

import copy

def add_space(cells):
    row = [[0] * (len(cells[0]) + 2)]
    return row + [[0] + x + [0] for x in cells] + copy.deepcopy(row)

def cut_space(cells):
    for i in range(-1, 1):
        while cells[i].count(1) == 0:
            cells.pop(i)
        while [cells[n][i] for n in range(len(cells))].count(1) == 0:
            for n in range(len(cells)):
                cells[n].pop(i)
    return cells

def morph_cell(neighbours, cell):
    if cell == 1:
        if neighbours.count(1) < 2 or neighbours.count(1) > 3:
            return 0
    if cell == 0 and neighbours.count(1) == 3:
        return 1
    else:
        return cell

def get_neighbours(cells, coords):
    neighbours = []
    for n in range(max(0, coords[0] - 1), min(len(cells), coords[0] + 2)):
        for m in range(max(0, coords[1] - 1), min(len(cells[n]), coords[1] + 2)):
            neighbours.append(cells[n][m])
    if cells[coords[0]][coords[1]] == 1:
        neighbours = sorted(neighbours)[:-1]
    else:
        neighbours = sorted(neighbours)[1:]
    return morph_cell(neighbours, cells[coords[0]][coords[1]])

def new_step(cells, new_cells):
    for i in range(len(cells)):
        for j in range(len(cells[i])):
            new_cells[i][j] = get_neighbours(cells, (i, j))
    return new_cells

def get_generation(cells, generations):
    while generations != 0:
        cells = add_space(cells)
        new_cells = copy.deepcopy(cells)
        new_cells = cut_space(new_step(cells, new_cells))
        cells = new_cells
        print(cells)
        generations -= 1
    return cells