Solve in Python:
We need a function ```count_sel()``` that receives an array or list of integers (positive and negative) and may give us the following information in the order and  structure presented bellow:

```[(1), (2), (3), [[(4)], 5]]```

(1) - Total amount of received integers.

(2) - Total amount of different values the array has.

(3) - Total amount of values that occur only once.

(4) and (5) both in a list

(4) - It is (or they are) the element(s) that has (or have) the maximum occurrence. If there are more than one, the elements should be sorted (by their value obviously)

(5) - Maximum occurrence of the integer(s)

Let's see some cases
```python
____ count_sel([-3, -2, -1, 3, 4, -5, -5, 5, -1, -5]) ----> [10, 7, 5, [[-5], 3]]

(1) - The list has ten elements (10 numbers)

(2) - We have seven different values: -5, -3, -2, -1, 3, 4, 5 (7 values)

(3) - The numbers that occur only once: -3, -2, 3, 4, 5 (5 values)

(4) and (5) - The number -5 occurs three times (3 occurrences)

____ count_sel([4, 4, 2, -3, 1, 4, 3, 2, 0, -5, 2, -2, -2, -5]) ----> [14, 8, 4, [[2, 4], 3]]
```
Enjoy it and happy coding!!

from collections import defaultdict, Counter

def count_sel(nums):
    cnt = Counter(nums)
    d = defaultdict(list)
    total = 0
    unique = 0
    for k, v in cnt.items():
        d[v].append(k)
        total += v
        unique += 1
    maximum = max(d)
    return [total, unique, len(d[1]), [sorted(d[maximum]), maximum]]


Solve in Python:
We need a function ```prime_bef_aft()``` that gives the largest prime below a certain given value ```n```,

```befPrime or bef_prime``` (depending on the language),

and the smallest prime larger than this value,

```aftPrime/aft_prime``` (depending on the language).

The result should be output in a list like the following:

```python
prime_bef_aft(n) == [befPrime, aftPrime]
```

If n is a prime number it will give two primes, n will not be included in the result.

Let's see some cases:
```python
prime_bef_aft(100) == [97, 101]

prime_bef_aft(97) == [89, 101]

prime_bef_aft(101) == [97, 103]
```
Range for the random tests:
```1000 <= n <= 200000```

(The extreme and special case n = 2 will not be considered for the tests. Thanks Blind4Basics)

Happy coding!!

from itertools import compress
import numpy as np

s = np.ones(200001)
s[:2] = s[4::2] = 0
for i in range(3, int(len(s)**0.5)+1, 2):
    if s[i]:
        s[i*i::i] = 0
primes = list(compress(range(len(s)), s))

def prime_bef_aft(num):
    i = np.searchsorted(primes, num)
    return [primes[i-1], primes[i+(primes[i] == num)]]


Solve in Python:
We need a function that may receive a list  of an unknown amount of points in the same plane, having each of them, cartesian coordinates of the form (x, y) and may find the biggest triangle (the one with the largest area) formed by all of the possible combinations of groups of three points of that given list.
Of course, we will have some combinations of three points that does not form a triangle, because the three points are aligned.
The function find_biggTriang(listOfPoints), will output a list with the following data in the order presented bellow:
```python
[(1), (2), (3), (4), 5]

(1) - Number of points received (You may assume that you will not receive duplicates)

(2) - Maximum possible amount of triangles that can be formed with the amount of received
      points (number in data (1) above). It should be expressed as an integer, (no L for long type
      variables)

(3) - Real Number of triangles that can be formed with the given points. (The function should have a
      counter for all the cases of three points aligned). It should be expressedas as an integer.

(4) - The triangles that have maximum area in a sorted list.
      If there are two triangles with the biggest area, the result will be presented in this way:
      [[[xA1, yA1], [xB1, yB1], [xC1, yC1]], [[xA2, yA2], [xB2, yB2], [xC2, yC2]]]
      But if we have only one triangle with max. area, there is no need of a spare level of braces,
      so it will be as follows: [[xA1, yA1], [xB1, yB1], [xC1, yC1]]

(5) - The value of max. area (absolute value) that was found as a float. As we did not define the
      units of length for the coordinates, the units for the area will be ignored.

```

It would be useful to apply the expression for the area of a triangle with vertices A, B, and C, is equal to the half of the determinant of the matrix, using the respective coordinates as follows:

```python

                               | xA    yA    1|
Area Triangle(A, B, C) = 1/2 . | xB    yB    1|
                               | xC    yC   ...

from itertools import combinations

def find_biggTriang(listPoints):
    s = combinations(listPoints, 3)
    j = 0
    i = 0
    ret = []
    mx = 0
    for a, b, c in s:
        s = abs((b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1]-a[1])) / 2
        if s > mx:
            mx = s
            ret = []
        if s == mx:
            ret.append([list(a), list(b), list(c)])
        if s > 0:
            i += 1
        j += 1
    if len(ret) <= 1:
        ret = ret[0]
    return [len(listPoints), j, i, ret, mx]


Solve in Python:
We need a system that can learn facts about family relationships, check their consistency and answer queries about them.

# The task

~~~if:javascript
Create a class `Family` with the following methods. All arguments are strings: names of persons. Upon the first use of a name, that name is added to the family.

* `male(name)` and `female(name)` returning `boolean`

 Define the gender (corresponding to the method name) of the given person. Return `false` when these assignments cannot be made because of conflicts with earlier registered information.

* `isMale(name)` and `isFemale(name)` returning `boolean`

 Return `true` when the person has the said gender. When no gender was assigned, both methods should return `false`

* `setParent(childName, parentName)` returning `boolean`

 Defines the child-parent relationship between two persons. Returns `false` when the relationship cannot be made because of conflicts with earlier registered information.

* `getParents(name)` and `getChildren(name)` returning `array` of `string`

 Return the names of the person's parents/children in alphabetical order
~~~
~~~if:python
Create a class `Family` with the following methods. All arguments are strings: names of persons. Upon the first use of a name, that name is added to the family.

* `male(name)` and `female(name)` returning `boolean`

 Define the gender (corresponding to the method name) of the given person. Return `False` when these assignments cannot be made because of conflicts with earlier registered information.

* `is_male(name)` and `is_female(name)` returning `boolean`

 Return `True` when the person has the said gender. When no gender was assigned, both methods should return `False`

* `set_parent_of(child_name, parent_name)` returning `boolean`

 Defines the child-parent relationship between two persons. Returns `False` when the relationship cannot be made because of conflicts with earlier registered information.

* `get_parents_of(name)` and `get_children_of(name)` returning `list` of `string`

 Return...

from collections import defaultdict

class family:
    def __init__(self):
        self.males = set()
        self.females = set()
        self.parents = defaultdict(lambda: set())
        self.children = defaultdict(lambda: set())

    def male(self, name):
        if name in self.females:
            return False
        if name in self.males:
            return True
        safe_copy = self.males.copy()
        self.males.add(name)
        for child in self.parents[name]:
            partners = self.children[child] - {name}
            for partner in partners:
                if not self.female(partner):
                    self.males = safe_copy
                    return False
        return True
    def is_male(self, name):
        return name in self.males
    def female(self, name):
        if name in self.males:
            return False
        if name in self.females:
            return True
        safe_copy = self.females.copy()
        self.females.add(name)
        for child in self.parents[name]:
            partners = self.children[child] - {name}
            for partner in partners:
                if not self.male(partner):
                    self.females = safe_copy
                    return False
        return True
    def is_female(self, name):
        return name in self.females
    def set_parent_of(self, child_name, parent_name):
        if child_name == parent_name:
            return False
        parents = self.children[parent_name]
        while parents:
            if child_name in parents:
                return False
            new_parents = set()
            for parent in parents:
                new_parents |= self.children[parent]
            parents = new_parents
        current_parents = self.children[child_name]
        if parent_name in current_parents:
            return True
        if len(current_parents) >= 2:
            return False
        new_parents = current_parents | {parent_name}
        if len(new_parents & self.males) > 1 or len(new_parents &...


Solve in Python:
We need to write some code to return the original price of a product, the return type must be of type decimal and the number must be rounded to two decimal places.

We will be given the sale price (discounted price), and the sale percentage, our job is to figure out the original price.

### For example:

Given an item at $75 sale price after applying a 25% discount, the function should return the original price of that item before applying the sale percentage, which is ($100.00) of course, rounded to two decimal places.

DiscoverOriginalPrice(75, 25) => 100.00M where 75 is the sale price (discounted price), 25 is the sale percentage and 100 is the original price

def discover_original_price(discounted_price, sale_percentage):
    return round(discounted_price / ((100 - sale_percentage) * 0.01), 2)


Solve in Python:
We need you to implement a method of receiving commands over a network, processing the information and responding.

Our device will send a single packet to you containing data and an instruction which you must perform before returning your reply.

To keep things simple, we will be passing a single "packet" as a string.
Each "byte" contained in the packet is represented by 4 chars.

One packet is structured as below:
```
Header  Instruction   Data1    Data2   Footer
------   ------       ------   ------  ------
 H1H1     0F12         0012     0008    F4F4
------   ------       ------   ------  ------

The string received in this case would be - "H1H10F1200120008F4F4"

Instruction: The calculation you should perform, always one of the below.
            0F12 = Addition
            B7A2 = Subtraction
            C3D9 = Multiplication
            FFFF = This instruction code should be used to identify your return value.
```
- The Header and Footer are unique identifiers which you must use to form your reply.

- Data1 and Data2 are the decimal representation of the data you should apply your instruction to. _i.e 0109 = 109._

- Your response must include the received header/footer, a "FFFF" instruction code, and the result of your calculation stored in Data1.

- Data2 should be zero'd out to "0000".

```
To give a complete example:

If you receive message "H1H10F1200120008F4F4".
The correct response would be "H1H1FFFF00200000F4F4"

```
In the event that your calculation produces a negative result, the value returned should be "0000", similarily if the value is above 9999 you should return "9999".

Goodluck, I look forward to reading your creative solutions!

INSTRUCTIONS = {"0F12": int.__add__, "B7A2": int.__sub__, "C3D9": int.__mul__}

def communication_module(packet):
    header,inst,d1,d2,footer = (packet[i:i+4] for i in range(0,20,4))
    res = max(0, min(9999, INSTRUCTIONS[inst](int(d1), int(d2)) ))

    return f"{header}FFFF{res:0>4}0000{footer}"


Solve in Python:
We partition a row of numbers A into at most K adjacent (non-empty) groups, then our score is the sum of the average of each group. What is the largest score we can achieve?
Note that our partition must use every number in A, and that scores are not necessarily integers.
Example:
Input:
A = [9,1,2,3,9]
K = 3
Output: 20
Explanation:
The best choice is to partition A into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.
We could have also partitioned A into [9, 1], [2], [3, 9], for example.
That partition would lead to a score of 5 + 2 + 6 = 13, which is worse.

Note:

1 <= A.length <= 100.
1 <= A[i] <= 10000.
1 <= K <= A.length.
Answers within 10^-6 of the correct answer will be accepted as correct.

class Solution:
    def largestSumOfAverages(self, A: List[int], k: int) -> float:
          n=len(A)
          pre= list(itertools.accumulate([0]+A))
          dp={}
          def dfs(i,k):
             if (i,k) in dp:
                    return dp[(i,k)]
             if k==1:
                    dp[(i,k)]=(pre[-1]-pre[i])/(n-i)
                    return dp[(i,k)]
             ans=-float('inf');cur=0
             for j in range(i,n-k+1):
                  ans=max(ans,(pre[j+1]-pre[i])/(j-i+1)+dfs(j+1,k-1))
             dp[(i,k)]=ans
             return ans
          return dfs(0,k)


Solve in Python:
We run a preorder depth first search on the root of a binary tree.
At each node in this traversal, we output D dashes (where D is the depth of this node), then we output the value of this node.  (If the depth of a node is D, the depth of its immediate child is D+1.  The depth of the root node is 0.)
If a node has only one child, that child is guaranteed to be the left child.
Given the output S of this traversal, recover the tree and return its root.

Example 1:

Input: "1-2--3--4-5--6--7"
Output: [1,2,5,3,4,6,7]

Example 2:

Input: "1-2--3---4-5--6---7"
Output: [1,2,5,3,null,6,null,4,null,7]

Example 3:

Input: "1-401--349---90--88"
Output: [1,401,null,349,88,90]

Note:

The number of nodes in the original tree is between 1 and 1000.
Each node will have a value between 1 and 10^9.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def recoverFromPreorder(self, S: str) -> TreeNode:
        def dfs(s, idx, depth):
            if idx==len(s):
                return None, len(s)
            cnt = 0
            while s[cnt+idx]=='-':
                cnt += 1

            if cnt!=depth:
                return None, idx

            idx += cnt
            i = 0
            while idx+i<len(s) and s[idx+i].isdigit():
                i += 1
            root = TreeNode(int(s[idx:idx+i]))
            idx += i
            root.left, li = dfs(s, idx, depth+1)
            root.right, ri = dfs(s, li, depth+1)
            return root, ri

        return dfs(S, 0, 0)[0]


class Solution:
    def sampleStats(self, count: List[int]) -> List[float]:
        mini = -1
        maxi = 0.0
        mode = 0.0
        biggest = 0
        total = sum(count)
        mid = total // 2 if total != 1 else 1
        median = 0.0
        accumulator = 0
        tally = 0
        nums = 0

        for i, num in enumerate(count):
            if not num:
                continue
            else:
                maxi = float(i)
                tally += num*i

            if mini == -1 and num:
                mini = float(i)
            if num > biggest:
                biggest = num
                mode = float(i)

            if total % 2:  # odd
                if accumulator < mid and (accumulator + num) >= mid:
                    median = float(i)
            else:          # even
                if accumulator < mid-1 and (accumulator + num) >= mid-1:
                    median = float(i)
                elif num and accumulator == mid:
                    median = (median+i)/2
            accumulator += num
        return [mini, maxi, tally/accumulator, median, mode]


Solve in Python:
We say that a binary string (a string containing only characters '0' and '1') is pure if it does not contain either of the strings "0101" or "1010" as a subsequence.
Recall that string T is a subsequence of string S if we can delete some of the letters of S (possibly none) such that the resulting string will become T.
You are given a binary string $S$ with length $N$. We want to make this string pure by deleting some (possibly zero) characters from it. What is the minimum number of characters we have to delete?

-----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 string $S$ with length $N$.

-----Output-----
For each test case, print a single line containing one integer — the minimum number of characters we have to delete from $S$.

-----Constraints-----
- $1 \le T \le 40$
- $1 \le N \le 1,000$
- $S$ contains only characters '0' and '1'

-----Example Input-----
4
010111101
1011100001011101
0110
111111

-----Example Output-----
2
3
0
0

-----Explanation-----
Example case 1: We can delete the first and third character of our string. There is no way to make the string pure by deleting only one character.
Example case 3: The given string is already pure, so the answer is zero.

# cook your dish here
# code by RAJ BHAVSAR
for _ in range(int(input())):
 s = str(input())
 dp = [0,0,len(s),len(s),len(s),len(s)]
 for i in s:
  if(i == '1'):
   dp[3] = min(dp[3],dp[0])
   dp[0] += 1
   dp[5] = min(dp[5],dp[2])
   dp[2] += 1
   dp[4] += 1
  else:
   dp[2] = min(dp[2],dp[1])
   dp[1] += 1
   dp[4] = min(dp[4],dp[3])
   dp[3] += 1
   dp[5] += 1
 print(min(dp))


Solve in Python:
We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row.  Each glass holds one cup (250ml) of champagne.

Then, some champagne is poured in the first glass at the top.  When the top most glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it.  When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on.  (A glass at the bottom row has it's excess champagne fall on the floor.)

For example, after one cup of champagne is poured, the top most glass is full.  After two cups of champagne are poured, the two glasses on the second row are half full.  After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now.  After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below.

Now after pouring some non-negative integer cups of champagne, return how full the j-th glass in the i-th row is (both i and j are 0 indexed.)

Example 1:
Input: poured = 1, query_glass = 1, query_row = 1
Output: 0.0
Explanation: We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty.

Example 2:
Input: poured = 2, query_glass = 1, query_row = 1
Output: 0.5
Explanation: We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange.

Note:

       poured will be in the range of [0, 10 ^ 9].
       query_glass and query_row will be in the range of [0, 99].

# Definition for a binary tree node.
 # class TreeNode:
 #     def __init__(self, x):
 #         self.val = x
 #         self.left = None
 #         self.right = None
 import sys
 class Solution:
     def makeList(self,root):
         if root == None:
             return([])
         else:
             return(self.makeList(root.left) + [root.val] + self.makeList(root.right))

     def minDiffInBST(self, root):
         """
         :type root: TreeNode
         :rtype: int
         """
         arr = self.makeList(root)
         minDistance = sys.maxsize

         if len(arr) == 0:
             return(0)
         else:
             for i in range(1,len(arr)):
                 gap = abs(arr[i] - arr[i-1])
                 if gap < minDistance:
                     minDistance = gap

             return(minDistance)


Solve in Python:
We start with a permutation $a_1, a_2, \ldots, a_n$ and with an empty array $b$. We apply the following operation $k$ times.

On the $i$-th iteration, we select an index $t_i$ ($1 \le t_i \le n-i+1$), remove $a_{t_i}$ from the array, and append one of the numbers $a_{t_i-1}$ or $a_{t_i+1}$ (if $t_i-1$ or $t_i+1$ are within the array bounds) to the right end of the array $b$. Then we move elements $a_{t_i+1}, \ldots, a_n$ to the left in order to fill in the empty space.

You are given the initial permutation $a_1, a_2, \ldots, a_n$ and the resulting array $b_1, b_2, \ldots, b_k$. All elements of an array $b$ are distinct. Calculate the number of possible sequences of indices $t_1, t_2, \ldots, t_k$ modulo $998\,244\,353$.

-----Input-----

Each test contains multiple test cases. The first line contains an integer $t$ ($1 \le t \le 100\,000$), denoting the number of test cases, followed by a description of the test cases.

The first line of each test case contains two integers $n, k$ ($1 \le k < n \le 200\,000$): sizes of arrays $a$ and $b$.

The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le n$): elements of $a$. All elements of $a$ are distinct.

The third line of each test case contains $k$ integers $b_1, b_2, \ldots, b_k$ ($1 \le b_i \le n$): elements of $b$. All elements of $b$ are distinct.

The sum of all $n$ among all test cases is guaranteed to not exceed $200\,000$.

-----Output-----

For each test case print one integer: the number of possible sequences modulo $998\,244\,353$.

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

Output
2
0
4

-----Note-----

$\require{cancel}$

Let's denote as $a_1 a_2 \ldots \cancel{a_i} \underline{a_{i+1}} \ldots a_n \rightarrow a_1 a_2 \ldots a_{i-1} a_{i+1} \ldots a_{n-1}$ an operation over an element with index $i$: removal of element $a_i$ from array $a$ and appending element $a_{i+1}$ to array $b$.

In the first example test, the following two options can be used to...

import sys
input = sys.stdin.readline

mod=998244353

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

    X=[-1]*(n+1)
    for i in range(n):
        X[A[i]]=i

    for i in range(k):
        B[i]=X[B[i]]

    Y=[0]*n
    for b in B:
        Y[b]=1

    Y.append(1)

    #print(Y)
    #print(B)

    ANS=0
    for b in B:
        #print(b,Y)
        if Y[b-1]==1 and Y[b+1]==1:
            print(0)
            break

        elif Y[b-1]==0 and Y[b+1]==0:
            ANS+=1

        Y[b]=0

    else:
        print(pow(2,ANS,mod))


Solve in Python:
We start with a string $s$ consisting only of the digits $1$, $2$, or $3$. The length of $s$ is denoted by $|s|$. For each $i$ from $1$ to $|s|$, the $i$-th character of $s$ is denoted by $s_i$.

There is one cursor. The cursor's location $\ell$ is denoted by an integer in $\{0, \ldots, |s|\}$, with the following meaning:   If $\ell = 0$, then the cursor is located before the first character of $s$.  If $\ell = |s|$, then the cursor is located right after the last character of $s$.  If $0 < \ell < |s|$, then the cursor is located between $s_\ell$ and $s_{\ell+1}$.

We denote by $s_\text{left}$ the string to the left of the cursor and $s_\text{right}$ the string to the right of the cursor.

We also have a string $c$, which we call our clipboard, which starts out as empty. There are three types of actions:  The Move action. Move the cursor one step to the right. This increments $\ell$ once.  The Cut action. Set $c \leftarrow s_\text{right}$, then set $s \leftarrow s_\text{left}$.  The Paste action. Append the value of $c$ to the end of the string $s$. Note that this doesn't modify $c$.

The cursor initially starts at $\ell = 0$. Then, we perform the following procedure:  Perform the Move action once.  Perform the Cut action once.  Perform the Paste action $s_\ell$ times.  If $\ell = x$, stop. Otherwise, return to step 1.

You're given the initial string $s$ and the integer $x$. What is the length of $s$ when the procedure stops? Since this value may be very large, only find it modulo $10^9 + 7$.

It is guaranteed that $\ell \le |s|$ at any time.

-----Input-----

The first line of input contains a single integer $t$ ($1 \le t \le 1000$) denoting the number of test cases. The next lines contain descriptions of the test cases.

The first line of each test case contains a single integer $x$ ($1 \le x \le 10^6$). The second line of each test case consists of the initial string $s$ ($1 \le |s| \le 500$). It is guaranteed, that $s$ consists of the characters "1", "2", "3".

It is guaranteed that the sum of $x$...

import sys
mod = 10**9 + 7

for _ in range(int(input())):
    x = int(input())
    s = list(map(int, input()))
    ans = len(s)
    for i in range(1, x+1):
        ans = (i + (ans-i) * s[i-1]) % mod
        r = len(s)
        for _ in range(s[i-1]-1):
            if len(s) < x:
                s += s[i:r]
            else:
                break

    print(ans)


Solve in Python:
We want an array, but not just any old array, an array with contents!

Write a function that produces an array with the numbers `0` to `N-1` in it.

For example, the following code will result in an array containing the numbers `0` to `4`:

```
arr(5) // => [0,1,2,3,4]
```

def arr(*n):
    for m in n:
        return [i for i in range(0,m)]
    return []


Solve in Python:
We want to find the numbers higher or equal than 1000 that the sum of every four consecutives digits cannot be higher than a certain given value.
If the number is ``` num = d1d2d3d4d5d6 ```, and the maximum sum of 4 contiguous digits is ```maxSum```, then:
```python
d1 + d2 + d3 + d4 <= maxSum
d2 + d3 + d4 + d5 <= maxSum
d3 + d4 + d5 + d6 <= maxSum
```
For that purpose, we need to create a function, ```max_sumDig()```, that receives ```nMax```, as the max value of the interval to study (the range (1000, nMax) ), and a certain value, ```maxSum```, the maximum sum that every four consecutive digits should be less or equal to. The function should output the following list with the data detailed bellow:

```[(1), (2), (3)]```

(1) - the amount of numbers that satisfy the constraint presented above

(2) - the closest number to the mean of the results, if there are more than one, the smallest number should be chosen.

(3) - the total sum of all the found numbers

Let's see a case with all the details:
```
max_sumDig(2000, 3) -------> [11, 1110, 12555]

(1) -There are 11 found numbers: 1000, 1001, 1002, 1010, 1011, 1020, 1100, 1101, 1110, 1200 and 2000

(2) - The mean of all the found numbers is:
      (1000 + 1001 + 1002 + 1010 + 1011 + 1020 + 1100 + 1101 + 1110 + 1200 + 2000) /11 = 1141.36363,
      so 1110 is the number that is closest to that mean value.

(3) - 12555 is the sum of all the found numbers
      1000 + 1001 + 1002 + 1010 + 1011 + 1020 + 1100 + 1101 + 1110 + 1200 + 2000 = 12555

Finally, let's see another cases
```
max_sumDig(2000, 4) -----> [21, 1120, 23665]

max_sumDig(2000, 7) -----> [85, 1200, 99986]

max_sumDig(3000, 7) -----> [141, 1600, 220756]
```

Happy coding!!

def max_sumDig_aux(nmax, maxsm):
    res, i = [], 1000
    while (i <= nmax):
        a = list(str(i))
        j, b = 0, 0
        while (j <= len(a) - 4):
            if (sum(map(int, a[j:j+4])) <= maxsm):
                b += 1
            j += 1
        if (b == j):
            res.append(i)
        i += 1
    return res

def max_sumDig(nmax, maxsm):
    res = max_sumDig_aux(nmax, maxsm)
    l = len(res)
    s = sum(res)
    m = s / float(l)
    d = list([(abs(x - m), x) for x in res])
    d.sort()
    return [l, d[0][1], s]


Solve in Python:
We want to generate all the numbers of three digits where:

- the sum of their digits is equal to 10.

- their digits are in increasing order (the numbers may have two or more equal contiguous digits)

The numbers that fulfill the two above constraints are: ```118, 127, 136, 145, 226, 235, 244, 334```

Make a function that receives two arguments:

- the sum of digits value

- the desired number of digits for the numbers

The function should output an array with three values: \[1,2,3\]

1 - the total number of possible numbers

2 - the minimum number

3 - the maximum number

The example given above should be:

```python
find_all(10, 3) == [8, 118, 334]
```

If we have only one possible number as a solution, it should output a result like the one below:

```python
find_all(27, 3) == [1, 999, 999]
```

If there are no possible numbers, the function should output the empty array.

```python
find_all(84, 4) == []
```

The number of solutions climbs up when the number of digits increases.

```python
find_all(35, 6) == [123, 116999, 566666]
```

Features of the random tests:

* Number of tests: `112`
* Sum of digits value between `20` and `65`
* Amount of digits between `2` and `17`

from itertools import combinations_with_replacement

def find_all(sum_dig, digs):
    x = [int(''.join(x)) for x in combinations_with_replacement('123456789', digs) if sum(map(int, x)) == sum_dig]
    return [len(x), min(x), max(x)] if len(x) > 0 else []


Solve in Python:
We want to know the index of the vowels in a given word, for example, there are two vowels in the word super (the second and fourth letters).

So given a string "super", we should return a list of [2, 4].

        Some examples:
        Mmmm  => []
        Super => [2,4]
        Apple => [1,5]
        YoMama -> [1,2,4,6]

**NOTES:**

* Vowels in this context refers to: a e i o u y (including upper case)
* This is indexed from `[1..n]` (not zero indexed!)

def vowel_indices(word):
    vowels = 'aeiouyAEIOUY'
    return [i for i, l in enumerate(word, start=1) if l in vowels]


Solve in Python:
We will use the Flesch–Kincaid Grade Level to evaluate the readability of a piece of text. This grade level is an approximation for what schoolchildren are able to understand a piece of text. For example, a piece of text with a grade level of 7 can be read by seventh-graders and beyond.

The way to calculate the grade level is as follows:

    (0.39 * average number of words per sentence) + (11.8 * average number of syllables per word) - 15.59

Write a function that will calculate the Flesch–Kincaid grade level for any given string. Return the grade level rounded to two decimal points.

Ignore hyphens, dashes, apostrophes, parentheses, ellipses and abbreviations.

Remember that the text can contain more than one sentence: code accordingly!

**HINT**: Count the number of vowels as an approximation for the number of syllables, but count groups of vowels as one (e.g. `deal` is one syllable). **Do not** count `y` as a vowel!

## Example

```python
"The turtle is leaving." ==> 3.67
```

The average number of words per sentence is `4` and the average number of syllables per word is `1.5`. The score is then `(0.39 * 4) +  (11.8 * 1.5) - 15.59` = `3.67`

import re
def flesch_kincaid(s):
    w = len(s.split())
    return round(0.39*w/len(re.split(r'[!.?]',s)[:-1])+11.8*len(re.findall(r'[aeiou]+',s,re.I))/w-15.59,2)


Solve in Python:
We write the integers of A and B (in the order they are given) on two separate horizontal lines.
Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that:

A[i] == B[j];
The line we draw does not intersect any other connecting (non-horizontal) line.

Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line.
Return the maximum number of connecting lines we can draw in this way.

Example 1:

Input: A = [1,4,2], B = [1,2,4]
Output: 2
Explanation: We can draw 2 uncrossed lines as in the diagram.
We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2.

Example 2:
Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2]
Output: 3

Example 3:
Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1]
Output: 2

Note:

1 <= A.length <= 500
1 <= B.length <= 500
1 <= A[i], B[i] <= 2000

class Solution:
    def maxUncrossedLines(self, A: List[int], B: List[int]) -> int:
        dp = [[0 for i in range(len(B) + 1)] for j in range(len(A) + 1)]

        for i in range(len(A)):
            for j in range(len(B)):
                if A[i] == B[j]:
                    dp[i + 1][j + 1] = dp[i][j] + 1

                else:
                    dp[i + 1][j + 1] = max(dp[i][j], dp[i][j + 1], dp[i + 1][j])

        return dp[-1][-1]


Solve in Python:
We'll create a function that takes in two parameters:

* a sequence (length and types of items are irrelevant)
* a function (value, index) that will be called on members of the sequence and their index. The function will return either true or false.

Your function will iterate through the members of the sequence in order until the provided function returns true; at which point your function will return that item's **index**.

If the function given returns false for all members of the sequence, your function should return -1.

```python
true_if_even = lambda value, index: value % 2 == 0
find_in_array([1,3,5,6,7], true_if_even) # --> 3
```

def find_in_array(seq, predicate):
    for i, x in enumerate(seq):
        if predicate(x, i):
            return i
    return -1


Solve in Python:
We've got a message from the **Librarian**. As usual there're many `o` and `k` in it and, as all codewarriors don't know "Ook" language we need that you translate this message.

**tip** : it seems traditional "Hello World!" would look like :
`Ok, Ook, Ooo?  Okk, Ook, Ok?  Okk, Okk, Oo?  Okk, Okk, Oo?  Okk, Okkkk?  Ok, Ooooo?  Ok, Ok, Okkk?  Okk, Okkkk?  Okkk, Ook, O?  Okk, Okk, Oo?  Okk, Ook, Oo?  Ook, Ooook!`

Your task is to implement a function `okkOokOo(okkOookk)`, that would take the `okkOookk` message as input and return a decoded human-readable string.

*eg*:
```python
okkOokOo('Ok, Ook, Ooo!')  # -> 'H'
okkOokOo('Ok, Ook, Ooo?  Okk, Ook, Ok?  Okk, Okk, Oo?  Okk, Okk, Oo?  Okk, Okkkk!')  # -> 'Hello'
okkOokOo('Ok, Ok, Okkk?  Okk, Okkkk?  Okkk, Ook, O?  Okk, Okk, Oo?  Okk, Ook, Oo?  Ook, Ooook!')  # -> 'World!'
```

import string as st
def okkOokOo(s):
    trans = st.maketrans("Ook","001")
    return ''.join(chr(int(st.translate(i, trans, ", ?!"), base=2)) for i in s.split('? '))


Solve in Python:
Welcome

This kata is inspired by This Kata

We have a string s

We have a number n

Here is a function that takes your string, concatenates the even-indexed chars to the front, odd-indexed chars to the back.

Examples

    s = "Wow Example!"
    result = "WwEapeo xml!"
    s = "I'm JomoPipi"
    result = "ImJm ii' ooPp"

The Task:

return the result of the string after applying the function to it n times.

example where s = "qwertyuio" and n = 2:

    after 1 iteration  s = "qetuowryi"
    after 2 iterations s = "qtorieuwy"
    return "qtorieuwy"

 Note

there's a lot of tests, big strings,
and n is greater than a billion

so be ready to optimize.

after doing this: do it's best friend!

# Check out my other kata!

Matrix Diagonal Sort OMG
String -> N iterations -> String
String -> X iterations -> String
ANTISTRING
Array - squareUp b!
Matrix - squareUp b!
Infinitely Nested Radical Expressions
pipi Numbers!

def jumbled_string(s, n):
    mixer = lambda s: s[::2] + s[1::2]

    if n == 1: return mixer(s)

    # Count max possible iterations
    cnt = 1
    x = s
    while s != mixer(x):
        cnt += 1
        x = mixer(x)

    # Calculate needed amount of iterations
    max = n % cnt
    while max != 0:
        s = mixer(s)
        max -= 1
    return s


Solve in Python:
Welcome young Jedi! In this Kata you must create a function that takes an amount of US currency in `cents`, and returns a dictionary/hash which shows the least amount of coins used to make up that amount. The only coin denominations considered in this exercise are: `Pennies (1¢), Nickels (5¢), Dimes (10¢) and Quarters (25¢)`.
Therefor the dictionary returned should contain exactly 4 key/value pairs.

Notes:

* If the function is passed either 0 or a negative number, the function should return the dictionary with all values equal to 0.
* If a float is passed into the function, its value should be be rounded down, and the resulting dictionary should never contain fractions of a coin.

## Examples
```
loose_change(56)    ==>  {'Nickels': 1, 'Pennies': 1, 'Dimes': 0, 'Quarters': 2}
loose_change(-435)  ==>  {'Nickels': 0, 'Pennies': 0, 'Dimes': 0, 'Quarters': 0}
loose_change(4.935) ==>  {'Nickels': 0, 'Pennies': 4, 'Dimes': 0, 'Quarters': 0}
```

def loose_change(cents):
    res = {}
    res['Quarters'], cents = divmod(cents, 25) if cents > 0 else (0, 0)
    res['Dimes'], cents = divmod(cents, 10)
    res['Nickels'], cents = divmod(cents, 5)
    res['Pennies'], cents = divmod(cents, 1)
    return res


Solve in Python:
Welcome.

In this kata you are required to, given a string, replace every letter with its position in the alphabet.

If anything in the text isn't a letter, ignore it and don't return it.

`"a" = 1`, `"b" = 2`, etc.

## Example

```python
alphabet_position("The sunset sets at twelve o' clock.")
```
Should return `"20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11"` (as a string)

def alphabet_position(text):

    upper_alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    lower_alpha = "abcdefghijklmnopqrstuvwxyz"
    l = []

    for i in text:
        if i in upper_alpha:
            index = upper_alpha.index(i) + 1
            l.append(str(index))
        elif i in lower_alpha:
            index = lower_alpha.index(i) + 1
            l.append(str(index))
    return " " .join(l)


Solve in Python:
Welcome. In this kata, you are asked to square every digit of a number and concatenate them.

For example, if we run 9119 through the function, 811181 will come out, because 9^(2) is 81 and 1^(2) is 1.

**Note:** The function accepts an integer and returns an integer

def square_digits(num):
    # s converts num to a str so we can index through it
    # when then loop through the len of the str
    # while we're looping the string we convert it back to a int and square it
    # after we add it to a str to keep it from adding and then convert it to a int
    s = str(num)
    t = len(s)
    y=0
    g= 0
    b=""
    while y < t:
        g = int(s[y])**2
        b= b+ str(g)
        final = int(b)
        y=y+1
    return(final)
    pass


Solve in Python:
Well known investigative reporter Kim "Sherlock'' Bumjun needs your help! Today, his mission is to sabotage the operations of the evil JSA. If the JSA is allowed to succeed, they will use the combined power of the WQS binary search and the UFDS to take over the world!
But Kim doesn't know where the base is located. He knows that the base is on the highest peak of the Himalayan Mountains. He also knows the heights of each of the $N$ mountains. Can you help Kim find the height of the mountain where the base is located?

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- The first line in each testcase contains one integer, $N$.
- The following $N$ lines of each test case each contain one integer: the height of a new mountain.

-----Output:-----
For each testcase, output one line with one integer: the height of the tallest mountain for that test case.

-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq N \leq 100000$
- $0 \leq$ height of each mountain $\leq 10^9$

-----Subtasks:-----
- 100 points: No additional constraints.

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

-----Sample Output:-----
7

# cook your dish here
for _ in range(int(input())):
 x=int(input())
 n=[]
 for i in range(x):
  n.append(int(input()))

 print(max(n))


Solve in Python:
Well met with Fibonacci bigger brother, AKA Tribonacci.

As the name may already reveal, it works basically like a Fibonacci, but summing the last 3 (instead of 2) numbers of the sequence to generate the next. And, worse part of it, regrettably I won't get to hear non-native Italian speakers trying to pronounce it :(

So, if we are to start our Tribonacci sequence with `[1, 1, 1]` as a starting input (AKA *signature*), we have this sequence:

```
[1, 1 ,1, 3, 5, 9, 17, 31, ...]
```

But what if we started with `[0, 0, 1]` as a signature? As starting with `[0, 1]` instead of `[1, 1]` basically *shifts* the common Fibonacci sequence by once place, you may be tempted to think that we would get the same sequence shifted by 2 places, but that is not the case and we would get:

```
[0, 0, 1, 1, 2, 4, 7, 13, 24, ...]
```

Well, you may have guessed it by now, but to be clear: you need to create a fibonacci function that given a **signature** array/list, returns **the first n elements - signature included** of the so seeded sequence.

Signature will always contain 3 numbers; n will always be a non-negative number; if `n == 0`, then return an empty array (except in C return NULL) and be ready for anything else which is not clearly specified ;)

If you enjoyed this kata more advanced and generalized version of it can be found in the Xbonacci kata

*[Personal thanks to Professor Jim Fowler on Coursera for his awesome classes that I really recommend to any math enthusiast and for showing me this mathematical curiosity too with his usual contagious passion :)]*

def tribonacci(s, n):
    if(n>3):
        for i in range(n - 3):
            s.append(s[i] + s[i + 1] + s[i + 2])
        return s
    else:
        return s[:n]
    #your code here


Solve in Python:
Well, those numbers were right and we're going to feed their ego.

Write a function, isNarcissistic, that takes in any amount of numbers and returns true if all the numbers are narcissistic. Return false for invalid arguments (numbers passed in as strings are ok).

For more information about narcissistic numbers (and believe me, they love it when you read about them) follow this link: https://en.wikipedia.org/wiki/Narcissistic_number

def narcissistic(n):
    try:
        k = len(str(n))
        return sum(d**k for d in map(int, str(n))) == int(n)
    except ValueError:
        return False

def is_narcissistic(*args):
    return all(map(narcissistic, args))


Solve in Python:
Wet Shark once had 2 sequences:
{a_n}= {a_1, a_2, a_3, ... , a_(109)}
{b_n} = {b_1, b_2, b_3, ... , b_(109)}
However, he only kept one element from each sequence. Luckily, both the elements that Wet Shark kept have the same index in Wet Shark's sequences: that is, he took a_i and b_i for some 1 ≤ i ≤ 109.
Right after Wet Shark loses his sequences, he finds that he actually needs them to break the code of Cthulhu to escape a labyrinth. Cthulhu's code is a single floating point number Q. However, the code verifier is faulty. If Wet Shark enters any code c such that |c - Q| ≤ 0.01 , Cthulhu's code checker will allow him to escape.
Wet Shark now starts to panic, and consults Dry Dolphin for help via ultrasonic waves. After the Dry Dolphin Sequence Processing Factory processes data of Wet Shark's sequences, the machines give Wet Shark the following 2 relations his sequences follow for all 1 ≤ n < 109, where x = sqrt(2) and y = sqrt(3).

Wet Shark is now clueless on how to compute anything, and asks you for help.
Wet Shark has discovered that Cthulhu's code is actually defined as Q = (a_k + b_k) / (2^s), where s is a predetermined number, k is the index of another element in Wet Shark's sequence, and a_k, b_k are precisely the kth elements of Wet Shark's sequences {a_n} and {b_n}, respectively.
Given k, i, and the 2 elements of the arrays Wet Shark has lost, find any value of the code c that will allow Wet Shark to exit Cthulhu's labyrinth.

-----Input-----
The first line of input contains 3 space separated integers i, k, s — the common index of the two elements Wet Shark kept, the index of Wet Shark's array needed to break Cthulhu's code, and the number s described in the problem statement, respectively. It is guaranteed that Cthulhu's code, Q, is between -109 and 109 (both inclusive).
The second line of the input contains 2 space separated integers a_i and b_i, representing the ith element of sequence {a_n} and the ith element of sequence {b_n}, respectively.

-----Output-----
Output any number c that will...

import math

def main():
  #print("enter i, k, s")
  IN = '11 6 5'
  z = IN.split()
  z = input().split()
  i = int(z[0])
  k = int(z[1])
  s = int(z[2])

  #print("enter a_i and b_i")
  IN = '4 5'
  z = IN.split()
  z = input().split()
  a_i = int(z[0])
  b_i = int(z[1])

  #print( "i = %d   k = %d   s = %d " % (i, k, s)  )
  #print( "a_i = %d   b_i = %d" % (a_i, b_i)  )

  x = math.sqrt(2)
  y = math.sqrt(3)
  #print(x,y)

  # Obtaining the k-th element when k >= i
  if(i<=k):
    diff = k-i
    #if both k and i are odd or even
    if(k-i)%2==0:
      #print("#1")
      ans =  (a_i + b_i) * math.pow(2,2*(k-i)-s)
      #diff = int(diff/2)
      #ans =  (a_i + b_i) * math.pow(2,4*diff-s)

    #if i and k are of different parities then obtaining first
    # a_(i+1) and b_(i+1)
    else:
      #print("#2")
      ans = (2*x*a_i + 2*x*y*b_i) * math.pow(2,2*(k-(i+1))-s )
      diff = int(diff/2)
      ans = (2*x*a_i + 2*x*y*b_i) * math.pow(2,4*diff - s)
      #print("1: ", (2*x*a_i + 2*x*y*b_i))
      #print("2: ", math.pow(2,4*diff - 2- s))
      #print("2 sol: ", math.pow(2,4*int(diff)-s))
      #print("diff: ",diff)

  # Obtaining the k_th element when k < i
  else:
    diff = i-k
    #if both k and i are odd or even
    if(i-k)%2==0:
      #print("#3")
      ans =  (a_i + b_i) / math.pow(2,2*(i-k)+s)
      #diff =  int(diff/2)
      #ans =  (a_i + b_i) / math.pow(2,4*diff+s)

    #if i and k are of different parities then obtaining first
    # a_(i+1) and b_(i+1)
    else:
      #print("#4")
      ans = (2*x*a_i + 2*x*y*b_i) / math.pow(2,2*(i+1-k)+s)
      diff = int(diff/2)
      ans = (2*x*a_i + 2*x*y*b_i) / math.pow(2,4*diff + 4 + s)

  print(ans)

main()


Solve in Python:
We’ve all seen katas that ask for conversion from snake-case to camel-case, from camel-case to snake-case, or from camel-case to kebab-case — the possibilities are endless.

But if we don’t know the case our inputs are in, these are not very helpful.

### Task:

So the task here is to implement a function (called `id` in Ruby/Crystal/JavaScript/CoffeeScript and `case_id` in Python/C) that takes a string, `c_str`, and returns a string with the case the input is in. The possible case types are “kebab”, “camel”, and ”snake”. If none of the cases match with the input, or if there are no 'spaces' in the input (for example in snake case, spaces would be '_'s), return “none”. Inputs will only have letters (no numbers or special characters).

### Some definitions

Kebab case: `lowercase-words-separated-by-hyphens`

Camel case: `lowercaseFirstWordFollowedByCapitalizedWords`

Snake case: `lowercase_words_separated_by_underscores`

### Examples:

```python
case_id(“hello-world”) #=> “kebab”
case_id(“hello-to-the-world”) #=> “kebab”
case_id(“helloWorld”) #=> “camel”
case_id(“helloToTheWorld”) #=> “camel”
case_id(“hello_world”) #=> “snake”
case_id(“hello_to_the_world”) #=> “snake”
case_id(“hello__world”) #=> “none”
case_id(“hello_World”) #=> “none”
case_id(“helloworld”) #=> “none”
case_id(“hello-World”) #=> “none”
```

Also check out my other creations — [Split Without Loss](https://www.codewars.com/kata/split-without-loss), [Adding Fractions](https://www.codewars.com/kata/adding-fractions),
[Random Integers](https://www.codewars.com/kata/random-integers), [Implement String#transpose](https://www.codewars.com/kata/implement-string-number-transpose), [Implement Array#transpose!](https://www.codewars.com/kata/implement-array-number-transpose), [Arrays and Procs #1](https://www.codewars.com/kata/arrays-and-procs-number-1), and [Arrays and Procs #2](https://www.codewars.com/kata/arrays-and-procs-number-2)

import re

CASES = [
    ('snake', re.compile(r'\A[a-z]+(_[a-z]+)+\Z')),
    ('kebab', re.compile(r'\A[a-z]+(-[a-z]+)+\Z')),
    ('camel', re.compile(r'\A[a-z]+([A-Z][a-z]*)+\Z')),
    ('none', re.compile(r'')),
]

def case_id(c_str):
    for case, pattern in CASES:
        if pattern.match(c_str): return case


Solve in Python:
What adds up
===========

Given three arrays of integers your task is to create an algorithm that finds the numbers in the first two arrays whose sum is equal to any number in the third. The return value should be an array containing the values from the argument arrays that adds up. The sort order of the resulting array is not important. If no combination of numbers adds up return a empty array.

### Example
A small example: Given the three input arrays `a1 = [1, 2]; a2 = [4,3]; a3 = [6,5,8]`, we need to find the number pairs from `a1` and `a2` that sum up to a number in `a3` and return those three numbers in an array. In this example, the result from the function would be `[[1, 4, 5] , [2, 4, 6], [2, 3, 5]]`.
```
Given three arrays
a1      a2      a3
 1       4       6          (a1 a2 a3)    (a1 a2 a3)  (a1 a2 a3)
 2       3       5      =>  [[1, 4, 5] ,  [2, 4, 6],  [2, 3, 5]]
                 8

each value in the result array contains one part from each of the arguments.
```

### Testing
A function `compare_array` is given. This function takes two arrays and compares them invariant of sort order.

```python
test.expect(compare_arrays(addsup([1,2], [3,1], [5,4]), [[1,3,4], [2,3,5]]))
```

### Greater goal
For extra honor try and make it as effective as possible. Discuss whats the most effective way of doing this. The fastest way i can do this is in *O(n^2)*. Can you do it quicker?

def addsup(a1, a2, a3):
  return [[x,y,x+y] for x in a1 for y in a2 if x+y in a3]


Solve in Python:
What is an anagram? Well, two words are anagrams of each other if they both contain the same letters. For example:

```
'abba' & 'baab' == true

'abba' & 'bbaa' == true

'abba' & 'abbba' == false

'abba' & 'abca' == false
```

Write a function that will find all the anagrams of a word from a list. You will be given two inputs a word and an array with words. You should return an array of all the anagrams or an empty array if there are none. For example:

anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) => ['aabb', 'bbaa']

anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) => ['carer', 'racer']

anagrams('laser', ['lazing', 'lazy',  'lacer']) => []

def anagrams(word, words):
    lst = []
    for elem in words:
        if sorted(word) == sorted(elem):
            lst.append(elem)
    return lst
    #your code here


Solve in Python:
What is the answer to life the universe and everything

Create a function that will make anything true

```python
    anything({}) != [],          'True'
    anything('Hello') < 'World', 'True'
    anything(80) > 81,           'True'
    anything(re) >= re,          'True'
    anything(re) <= math,        'True'
    anything(5) == ord,          'True'
```

Source: [CheckIO](https://checkio.org/mission/solution-for-anything/)

class anything:
    def __init__(self,*args,**kwargs):
        pass

anything.__eq__ = anything.__neq__ = anything.__gt__ = anything.__ge__ = anything.__lt__ = anything.__le__ = lambda *x:True


Solve in Python:
What's in a name?
..Or rather, what's a name in? For us, a particular string is where we are looking for a name.

Task

Test whether or not the string contains all of the letters which spell a given name, in order.

The format
A function passing two strings, searching for one (the name) within the other.
``function nameInStr(str, name){ return true || false }``

Examples

    nameInStr("Across the rivers", "chris") --> true
                ^      ^  ^^   ^
                c      h  ri   s

    Contains all of the letters in "chris", in order.
----------------------------------------------------------
    nameInStr("Next to a lake", "chris") --> false

    Contains none of the letters in "chris".
--------------------------------------------------------------------
    nameInStr("Under a sea", "chris") --> false
                   ^   ^
                   r   s

    Contains only some of the letters in "chris".
--------------------------------------------------------------------
    nameInStr("A crew that boards the ship", "chris") --> false
                 cr    h              s i
                 cr                h  s i
                 c     h      r       s i
                 ...

    Contains all of the letters in "chris", but not in order.
--------------------------------------------------------------------
    nameInStr("A live son", "Allison") --> false
               ^ ^^   ^^^
               A li   son

    Contains all of the correct letters in "Allison", in order,
    but not enough of all of them (missing an 'l').

Note: testing will _not_ be case-sensitive.

def name_in_str(str, name):
    it = iter(str.lower())
    return all(c in it for c in name.lower())


Solve in Python:
When Misha hits his favorite gym, he comes across an interesting problem with the barbell. In the gym, someone always leaves the weight plates in the strangest places you can imagine and sometime it's difficult to equip the barbell the way you want. Let's imagine that you have N weight plates placed in any order (remember that any gym has no more than K different types of weight plates and all weights are square-free). As a preliminary step towards solving this problem, Misha wants to simulate a simple gym, and for this purpose you have to deal with some queries:

- [1 I X] Set the weight of the ith weight plate to value X.

- [2 L R] Reverse the sequence of weight plates in the interval from L to R, where 1 ≤ L ≤ R ≤ N.

- [3 L R W] Check the interval from L to R to find out if you can make the weight W using only weight plates on this interval. (Note: this type of query will appear no more than P times)

Please help Misha in solving this problem.

-----Input-----
First line of input contains the number of weight plates N, and number of queries Q. Next line contains N integers w1, w2, ..., wN, where wi is the weight of the ith weight plate. Next Q lines contain some queries described above.

-----Output-----
For all queries of the third type: print "Yes" if your check returns a positive outcome, and "No" otherwise.

-----Constraints-----
- 1 ≤ N, W, Q ≤ 105
- K ≤ 10
- P ≤ 1000
- All numbers in the input are positive integers and ≤ 105.
- All the weights are square-free.

-----Subtasks-----
- Subtask 1: 1 ≤ N ≤ 103, 1 ≤ W ≤ 103, Q = 1 - 10 pts.

- Subtask 2: 1 ≤ N ≤ 103, 1 ≤ W ≤ 103, 1 ≤ Q ≤ 103, P ≤ 100 - 15 pts
- Subtask 3: 1 ≤ N ≤ 104, 1 ≤ W ≤ 104, 1 ≤ Q ≤ 104, P ≤ 300 - 25 pts.

- Subtask 4: 1 ≤ N ≤ 105, 1 ≤ W ≤ 105, 1 ≤ Q ≤ 105, K ≤ 2 - 20 pts.

- Subtask 5: Original constraints - 30 pts.

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

Output:Yes
No
Yes
Yes
Yes
No
YesSecond
Input:3 4
2013 2015 2017
3 1 3 4030
1 1 111
3 1 3...

def subsetsum(array,g):

    if g == 0 or g < 1:
        return False
    elif len(array) == 0:
        return False
    else:
        if array[0] == g :
            return True
        else:
            return subsetsum(array[1:],(g - array[0])) or subsetsum(array[1:],g)

n,q  = [int(i) for i in input().split()]
w = [int(i) for i in input().split()]
for qq in range(q) :
    x = [i for i in input().split()]
    a = int(x[0])
    if a == 1 :
        w[int(x[1])-1] = int(x[2])
    elif a == 2 :
        l = int(x[1])-1
        r = int(x[2])-1
        w = w[:l] + w[r:l-1:-1] + w[r+1:]
    else :
        l = int(x[1])-1
        r = int(x[2])
        if subsetsum(w[l:r],int(x[3])) :
            print("Yes")
        else :
            print("No")


Solve in Python:
When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided to rearrange them. Help him restore the original number, on condition that it was the maximum possible one.

-----Input-----

The first line contains a single integer $n$ ($1 \leqslant n \leqslant 10^5$) — the length of the string. The second line contains a string consisting of English lowercase letters: 'z', 'e', 'r', 'o' and 'n'.

It is guaranteed that it is possible to rearrange the letters in such a way that they form a sequence of words, each being either "zero" which corresponds to the digit $0$ or "one" which corresponds to the digit $1$.

-----Output-----

Print the maximum possible number in binary notation. Print binary digits separated by a space. The leading zeroes are allowed.

-----Examples-----
Input
4
ezor

Output
0

Input
10
nznooeeoer

Output
1 1 0

-----Note-----

In the first example, the correct initial ordering is "zero".

In the second example, the correct initial ordering is "oneonezero".

input()
s = input()
n = 0
z = s.count('z')
for i in range(s.count('n')):
    print(1, end=' ')
for i in range(z):
    print(0, end=' ')


Solve in Python:
When a warrior wants to talk with another one about peace or war he uses a smartphone.  In one distinct  country warriors who spent all time in training kata not always have enough money. So if they call some number they want to know which operator serves  this number.

Write a function which **accepts number and return name of operator or string "no info"**, if operator can't be defined. number always looks like 8yyyxxxxxxx, where yyy corresponds to operator.

Here is short list of operators:

* 039 xxx xx xx - Golden Telecom
* 050 xxx xx xx - MTS
* 063 xxx xx xx - Life:)
* 066 xxx xx xx - MTS
* 067 xxx xx xx - Kyivstar
* 068 xxx xx xx - Beeline
* 093 xxx xx xx - Life:)
* 095 xxx xx xx - MTS
* 096 xxx xx xx - Kyivstar
* 097 xxx xx xx - Kyivstar
* 098 xxx xx xx - Kyivstar
* 099 xxx xx xx - MTS Test [Just return "MTS"]

def detect_operator(num):
    operators = {
        "039": "Golden Telecom",
        "050": "MTS",
        "063": "Life:)",
        "066": "MTS",
        "067": "Kyivstar",
        "068": "Beeline",
        "093": "Life:)",
        "095": "MTS",
        "096": "Kyivstar",
        "097": "Kyivstar",
        "098": "Kyivstar",
        "099": "MTS"
        }
    return operators.get(str(num)[1:4],"no info")


Solve in Python:
When multiple master devices are connected to a single bus (https://en.wikipedia.org/wiki/System_bus), there needs to be an arbitration in order to choose which of them can have access to the bus (and 'talk' with a slave).

We implement here a very simple model of bus mastering. Given `n`, a number representing the number of **masters** connected to the bus, and a fixed priority order (the first master has more access priority than the second and so on...), the task is to choose the selected master.
In practice, you are given a string `inp` of length `n` representing the `n` masters' requests to get access to the bus, and you should return a string representing the masters, showing which (only one) of them was granted access:

```
The string 1101 means that master 0, master 1 and master 3 have requested
access to the bus.
Knowing that master 0 has the greatest priority, the output of the function should be: 1000
```

## Examples

## Notes

* The resulting string (`char* `) should be allocated in the `arbitrate` function, and will be free'ed in the tests.

* `n` is always greater or equal to 1.


Solve in Python:
When provided with a String, capitalize all vowels

For example:

Input : "Hello World!"

Output : "HEllO WOrld!"

Note: Y is not a vowel in this kata.

def swap(st):
  tr = str.maketrans('aeiou', 'AEIOU')
  return st.translate(tr);


Solve in Python:
When provided with a letter, return its position in the alphabet.

Input :: "a"

Ouput :: "Position of alphabet: 1"

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


Solve in Python:
When provided with a number between 0-9, return it in words.

Input :: 1

Output :: "One".

If your language supports it, try using a switch statement.

word = {0: "Zero",
      1: "One",
      2: "Two",
      3: "Three",
      4: "Four",
      5: "Five",
      6: "Six",
      7: "Seven",
      8: "Eight",
      9: "Nine"}

def switch_it_up(number):
    if word.get(number):
        return word[number]


Solve in Python:
When we attended middle school were asked to simplify mathematical expressions like "3x-yx+2xy-x" (or usually bigger), and that was easy-peasy ("2x+xy"). But tell that to your pc and we'll see!

Write a function: `simplify`, that takes a string in input, representing a *multilinear non-constant polynomial in integers coefficients* (like `"3x-zx+2xy-x"`), and returns another string as output where the same expression has been simplified in the following way ( `->` means application of `simplify`):

- All possible sums and subtraction of equivalent monomials ("xy==yx") has been done, e.g.: `"cb+cba" -> "bc+abc"`, `"2xy-yx" -> "xy"`, `"-a+5ab+3a-c-2a" -> "-c+5ab"`

- All monomials appears in order of increasing number of variables, e.g.: `"-abc+3a+2ac" -> "3a+2ac-abc"`, `"xyz-xz" -> "-xz+xyz"`

- If two monomials have the same number of variables, they appears in lexicographic order, e.g.: `"a+ca-ab" -> "a-ab+ac"`, `"xzy+zby" ->"byz+xyz"`

- There is no leading `+` sign if the first coefficient is positive, e.g.: `"-y+x" -> "x-y"`, but no restrictions for `-`:  `"y-x" ->"-x+y"`

---

__N.B.__ to keep it simplest, the string in input is restricted to represent only *multilinear non-constant polynomials*, so you won't find something like `-3+yx^2'. **Multilinear** means in this context: **of degree 1 on each variable**.

**Warning**: the string in input can contain arbitrary variables represented by lowercase characters in the english alphabet.

__Good Work :)__

def simplify(poly):
    # I'm feeling verbose today

    # get 3 parts (even if non-existent) of each term: (+/-, coefficient, variables)
    import re
    matches = re.findall(r'([+\-]?)(\d*)([a-z]+)', poly)

    # get the int equivalent of coefficient (including sign) and the sorted variables (for later comparison)
    expanded = [[int(i[0] + (i[1] if i[1] != "" else "1")), ''.join(sorted(i[2]))] for i in matches]

    # get the unique variables from above list. Sort them first by length, then alphabetically
    variables = sorted(list(set(i[1] for i in expanded)), key=lambda x: (len(x), x))

    # get the sum of coefficients (located in expanded) for each variable
    coefficients = {v:sum(i[0] for i in expanded if i[1] == v) for v in variables}

    # clean-up: join them with + signs, remove '1' coefficients, and change '+-' to '-'
    return '+'.join(str(coefficients[v]) + v for v in variables if coefficients[v] != 0).replace('1','').replace('+-','-')


Solve in Python:
When we have a 2x2 square matrix we may have up to 24 different ones changing the positions of the elements.

We show some of them
```
a  b   a  b    a  c    a  c   a  d    a  d    b  a    b  a
c  d   d  c    d  b    b  d   b  c    c  b    c  d    d  c
```
You may think to generate the remaining ones until completing the set of 24 matrices.

Given a certain matrix of numbers, that may be repeated or not, calculate the total number of possible matrices that may be generated, changing the position of the elements.

E.g:
Case one
```
A = [[1,2,3],
     [3,4,5]]   #a 2x3 rectangle matrix with number 3 twice
```
generates a set of ```360``` different matrices

Case two
```
A = [[1,1,1],
     [2,2,3],
     [3,3,3]]
```
generates a set of ```1260``` different matrices.

Case three
```
A = [[1,2,3],
     [4,5,6],
     [7,8,9]]
```
generates a set of ```362880``` different matrices

This kata is not meant to apply a brute force algorithm to try to count the total amount of marices.

Features of The Random Tests
```
number of tests = 100
2 ≤ m ≤ 9
2 ≤ n ≤ 9
```
Enjoy it!

Available only in Python 2, Javascript and Ruby by the moment.

import math

def count_perms(matrix):
    freq = dict()
    for sub_matrix in matrix:
        for elem in sub_matrix:
            if freq.get(elem) is not None:
                freq[elem] = freq[elem] + 1
            else:
                freq[elem] = 1
    denominator = 1
    for frequency in freq.values():
        denominator = denominator * math.factorial(frequency)
    return math.factorial(sum(freq.values())) / denominator


Solve in Python:
When working with color values it can sometimes be useful to extract the individual red, green, and blue (RGB) component values for a color. Implement a function that meets these requirements:

+ Accepts a case-insensitive hexadecimal color string as its parameter (ex. `"#FF9933"` or `"#ff9933"`)
+ Returns an object with the structure `{r: 255, g: 153, b: 51}` where *r*, *g*, and *b* range from 0 through 255

**Note:** your implementation does not need to support the shorthand form of hexadecimal notation (ie `"#FFF"`)

## Example

```
"#FF9933" --> {r: 255, g: 153, b: 51}
```

def hex_string_to_RGB(hex_string):
    integer = eval(f'0x{hex_string.lstrip("#").lower()}')
    return {'r': (integer >> 16) & 255, 'g': (integer >> 8) & 255, 'b': integer & 255}


Solve in Python:
When you divide the successive powers of `10` by `13` you get the following remainders of the integer divisions:

`1, 10, 9, 12, 3, 4`.

Then the whole pattern repeats.

Hence the following method:
Multiply the right most digit of the number with the left most number
in the sequence shown above, the second right most digit to the second
left most digit of the number in the sequence. The cycle goes on and you sum all these products. Repeat this process until the sequence of sums is stationary.

...........................................................................

Example: What is the remainder when `1234567` is divided by `13`?

`7×1 + 6×10 + 5×9 + 4×12 + 3×3 + 2×4 + 1×1 = 178`

We repeat the process with 178:

`8x1 + 7x10 + 1x9 = 87`

and again with 87:

`7x1 + 8x10 = 87`

...........................................................................

From now on the sequence is stationary and the remainder of `1234567` by `13` is
the same as the remainder of `87` by `13`: `9`

Call `thirt` the function which processes this sequence of operations on an integer `n (>=0)`. `thirt` will return the stationary number.

`thirt(1234567)` calculates 178, then 87, then 87 and returns `87`.

`thirt(321)` calculates 48, 48 and returns `48`

def thirt(n):
      sequence = [1,10,9,12,3,4]
      numbers = str(n)[::-1]
      sum = 0
      for i in range(len(numbers)):
          sum += int(sequence[i%6])*int(numbers[i])
      if sum == n:
          return sum
      else:
          return thirt(sum)


Solve in Python:
When you want to get the square of a binomial of two variables x and y, you will have:

`$(x+y)^2 = x^2 + 2xy + y ^2$`

And the cube:

`$(x+y)^3 = x^3 + 3x^2y + 3xy^2 +y^3$`

It is known from many centuries ago that for an exponent n, the result of a binomial x + y raised to the n-th power is:

Or using the sumation notation:

Each coefficient of a term has the following value:

Each coefficient value coincides with the amount of combinations without replacements of a set of n elements using only k different ones of that set.

Let's see the total sum of the coefficients of the different powers for the binomial:

`$(x+y)^0(1)$`

`$(x+y)^1 = x+y(2)$`

`$(x+y)^2 = x^2 + 2xy + y ^2(4)$`

`$(x+y)^3 = x^3 + 3x^2y + 3xy^2 +y^3(8)$`

We need a function that may generate an array with the values of all the coefficients sums from 0 to the value of n included and has the addition of all the sum values as last element.

We add some examples below:
```
f(0) = [1, 1]
f(1) = [1, 2, 3]
f(2) = [1, 2, 4, 7]
f(3) = [1, 2, 4, 8, 15]
```

Features of the test
```
Low Performance Tests
Number of tests = 50
9 < n < 101

High Performance Tests
Number of Tests = 50
99 < n < 5001
```


Solve in Python:
When you were little, your mother used to make the most delicious cookies, which you could not resist. So, every now and then, when your mother didn't see you, you sneaked into the kitchen, climbed onto a stool to reach the cookie jar, and stole a cookie or two. However, sometimes while doing this, you would hear foot steps approaching, so you quickly jumped down from the stool and, when your mother entered the kitchen, you pretended as if nothing had happened (whistle, whistle innocently). However, your mother knew. How did she know? You forgot to put the lid back on the cookie jar! Oh, no!

Growing older (and still not able to resist your mother's cookies), you deviced a contraption that would automatically put the lid back on the cookie jar, _no matter what would happen_.

The class `CookieJar` is provided:
```Python
class CookieJar(object):

    def __init__(self):
        self._is_open = False

    def take(self):
        if not self._is_open:
            raise ValueError("Cookie jar is closed")
        return "Cookie"

    def open_jar(self):
        self._is_open = True

    def close_jar(self):
        self._is_open = False

    def is_open(self):
        return self._is_open
```
Your task is to implement the 'contraption' `SelfClosing` (class, method, whatever; it's your choice) such that, given an instance`cookie_jar` of `CookieJar`, you may call:

```Python
with SelfClosing(cookie_jar) as jar:
    cookie = jar.take()
```
after which, `cookie_jar.is_open() == False`, _no matter what_.

Do not alter the provided code. (Tests will be performed with a code that differs slightly from the one provided, so modifying it is to no avail.)

Enjoy!

class SelfClosing:
    def __init__(self, obj):
        self.obj = obj

    def __enter__(self):
        self.obj.open_jar()
        return self.obj

    def __exit__(self, *_):
        self.obj.close_jar()


Solve in Python:
Wherever the destination is, whoever we meet, let's render this song together.

On a Cartesian coordinate plane lies a rectangular stage of size w × h, represented by a rectangle with corners (0, 0), (w, 0), (w, h) and (0, h). It can be seen that no collisions will happen before one enters the stage.

On the sides of the stage stand n dancers. The i-th of them falls into one of the following groups:   Vertical: stands at (x_{i}, 0), moves in positive y direction (upwards);  Horizontal: stands at (0, y_{i}), moves in positive x direction (rightwards).  [Image]

According to choreography, the i-th dancer should stand still for the first t_{i} milliseconds, and then start moving in the specified direction at 1 unit per millisecond, until another border is reached. It is guaranteed that no two dancers have the same group, position and waiting time at the same time.

When two dancers collide (i.e. are on the same point at some time when both of them are moving), they immediately exchange their moving directions and go on. [Image]

Dancers stop when a border of the stage is reached. Find out every dancer's stopping position.

-----Input-----

The first line of input contains three space-separated positive integers n, w and h (1 ≤ n ≤ 100 000, 2 ≤ w, h ≤ 100 000) — the number of dancers and the width and height of the stage, respectively.

The following n lines each describes a dancer: the i-th among them contains three space-separated integers g_{i}, p_{i}, and t_{i} (1 ≤ g_{i} ≤ 2, 1 ≤ p_{i} ≤ 99 999, 0 ≤ t_{i} ≤ 100 000), describing a dancer's group g_{i} (g_{i} = 1 — vertical, g_{i} = 2 — horizontal), position, and waiting time. If g_{i} = 1 then p_{i} = x_{i}; otherwise p_{i} = y_{i}. It's guaranteed that 1 ≤ x_{i} ≤ w - 1 and 1 ≤ y_{i} ≤ h - 1. It is guaranteed that no two dancers have the same group, position and waiting time at the same time.

-----Output-----

Output n lines, the i-th of which contains two space-separated integers (x_{i}, y_{i}) — the stopping position of the i-th dancer in the...

# http://codeforces.com/problemset/problem/848/B
from collections import defaultdict

def get_dest(start, w, h):
    if start[0] == 1:
        return (str(start[1]), str(h))
    else:
        return (str(w), str(start[1]))

n, w, h = [int(x) for x in input().split()]
dancers = []
groups = defaultdict(list)
destinations = [None for x in range(n)]
for ii in range(n):
    g, p, t = [int(x) for x in input().split()]
    dancers.append((g, p, t))
    groups[p-t].append(ii)

for gg in list(groups.values()):
    V, H = [], []
    for ii in gg:
        dancer = dancers[ii]
        if dancer[0] == 1:
            V.append(dancer)
        else:
            H.append(dancer)
    V.sort(key=lambda x: -x[1])
    H.sort(key=lambda x: x[1])
    table = {orig: get_dest(new, w, h) for orig, new in zip(V+H, H+V)}
    for ii in gg:
        destinations[ii] = table[dancers[ii]]

# print(destinations)
for dd in destinations:
    print(" ".join(dd))


Solve in Python:
While developing a website, you detect that some of the members have troubles logging in. Searching through the code you find that all logins ending with a "\_" make problems. So you want to write a function that takes an array of pairs of login-names and e-mails, and outputs an array of all login-name, e-mails-pairs from the login-names that end with "\_".

If you have the input-array:

```
[ [ "foo", "foo@foo.com" ], [ "bar_", "bar@bar.com" ] ]
```

it should output

```
[ [ "bar_", "bar@bar.com" ] ]
```

You *have to* use the *filter*-method which returns each element of the array for which the *filter*-method returns true.

```python
https://docs.python.org/3/library/functions.html#filter
```

def search_names(logins):
    return filter(lambda l: l[0].endswith('_'), logins)


Solve in Python:
While discussing a proper problem A for a Codeforces Round, Kostya created a cyclic array of positive integers $a_1, a_2, \ldots, a_n$. Since the talk was long and not promising, Kostya created a new cyclic array $b_1, b_2, \ldots, b_{n}$ so that $b_i = (a_i \mod a_{i + 1})$, where we take $a_{n+1} = a_1$. Here $mod$ is the modulo operation. When the talk became interesting, Kostya completely forgot how array $a$ had looked like. Suddenly, he thought that restoring array $a$ from array $b$ would be an interesting problem (unfortunately, not A).

-----Input-----

The first line contains a single integer $n$ ($2 \le n \le 140582$) — the length of the array $a$.

The second line contains $n$ integers $b_1, b_2, \ldots, b_{n}$ ($0 \le b_i \le 187126$).

-----Output-----

If it is possible to restore some array $a$ of length $n$ so that $b_i = a_i \mod a_{(i \mod n) + 1}$ holds for all $i = 1, 2, \ldots, n$, print «YES» in the first line and the integers $a_1, a_2, \ldots, a_n$ in the second line. All $a_i$ should satisfy $1 \le a_i \le 10^{18}$. We can show that if an answer exists, then an answer with such constraint exists as well.

It it impossible to restore any valid $a$, print «NO» in one line.

You can print each letter in any case (upper or lower).

-----Examples-----
Input
4
1 3 1 0

Output
YES
1 3 5 2

Input
2
4 4

Output
NO

-----Note-----

In the first example:  $1 \mod 3 = 1$  $3 \mod 5 = 3$  $5 \mod 2 = 1$  $2 \mod 1 = 0$

n = int(input())

b = list(map(int, input().split()))

m, M = min(b), max(b)
if m == M:
    if M == 0:
        print('YES')
        print(' '.join(['1' for i in range(n)]))
    else:
        print('NO')
else:
    print('YES')

    pos = list([i for i in range(n) if b[i] == M and b[i - 1] < M])[0]

    a = [0 for i in range(n)]

    a[pos] = M
    a[pos - 1] = (M << 1) + b[pos - 1]

    for i in range(2, n):
        a[pos - i] = a[pos - i + 1] + b[pos - i]

    print(*a)


Solve in Python:
While doing some spring cleaning, Daniel found an old calculator that he loves so much. However, it seems like it is broken. When he tries to compute $1 + 3$ using the calculator, he gets $2$ instead of $4$. But when he tries computing $1 + 4$, he gets the correct answer, $5$. Puzzled by this mystery, he opened up his calculator and found the answer to the riddle: the full adders became half adders!

So, when he tries to compute the sum $a + b$ using the calculator, he instead gets the xorsum $a \oplus b$ (read the definition by the link: https://en.wikipedia.org/wiki/Exclusive_or).

As he saw earlier, the calculator sometimes gives the correct answer. And so, he wonders, given integers $l$ and $r$, how many pairs of integers $(a, b)$ satisfy the following conditions: $$a + b = a \oplus b$$ $$l \leq a \leq r$$ $$l \leq b \leq r$$

However, Daniel the Barman is going to the bar and will return in two hours. He tells you to solve the problem before he returns, or else you will have to enjoy being blocked.

-----Input-----

The first line contains a single integer $t$ ($1 \le t \le 100$) — the number of testcases.

Then, $t$ lines follow, each containing two space-separated integers $l$ and $r$ ($0 \le l \le r \le 10^9$).

-----Output-----

Print $t$ integers, the $i$-th integer should be the answer to the $i$-th testcase.

-----Example-----
Input
3
1 4
323 323
1 1000000

Output
8
0
3439863766

-----Note-----

$a \oplus b$ denotes the bitwise XOR of $a$ and $b$.

For the first testcase, the pairs are: $(1, 2)$, $(1, 4)$, $(2, 1)$, $(2, 4)$, $(3, 4)$, $(4, 1)$, $(4, 2)$, and $(4, 3)$.

def g( a , b ):
    cur = 1
    res = 0
    ze = 0
    while cur <= b:
        if b & cur:
            b ^= cur
            if a & b == 0:
                res += ( 1 << ze )
        if a & cur == 0:
            ze = ze + 1
        cur <<= 1
    return res

def f( a , b ):
    res = 0
    if a == b:
        return 0
    if a == 0:
        return 2 * b - 1 + f( 1 , b )
    if a & 1:
        res = res + 2 * ( g( a , b ) - g( a , a ) )
        a = a + 1
    if b & 1:
        res = res + 2 * ( g( b - 1 , b ) - g( b - 1 , a ) )
    return 3 * f( a >> 1 , b >> 1 ) + res

t = int(input())

while t > 0:
    t = t - 1
    l , r = list(map(int , input().split()))
    print( f( l , r + 1 ) )


Solve in Python:
While most devs know about [big/little-endianness](https://en.wikipedia.org/wiki/Endianness), only a selected few know the secret of real hard core coolness with mid-endians.

Your task is to take a number and return it in its mid-endian format, putting the most significant couple of bytes in the middle and all the others around it, alternating left and right.

For example, consider the number `9999999`, whose hexadecimal representation would be `98967F` in big endian (the classic you get converting); it becomes `7F9698` in little-endian and `96987F` in mid-endian.

Write a function to do that given a positive integer (in base 10) and remembering that you need to pad with `0`s when you get a single hex digit!

import re
def mid_endian(n):
    t = f'{n:X}'
    t = '0' + t if len(t) % 2 else t

    odds, evens = [], []
    for i, f in enumerate(re.findall(r'..', t), start=1):
        if i % 2:
            odds.append(f)
        else:
            evens.append(f)
    return ''.join(list(reversed(evens)) + odds)


Solve in Python:
While surfing in web I found interesting math problem called "Always perfect". That means if you add 1 to the product of four consecutive numbers the answer is ALWAYS a perfect square.
For example we have: 1,2,3,4 and the product will be 1X2X3X4=24. If we add 1 to the product that would become 25, since the result number is a perfect square the square root of 25 would be 5.

So now lets write a function which takes numbers separated by commas in string format and returns the number which is a perfect square and the square root of that number.

If string contains other characters than number or it has more or less than 4 numbers separated by comma function returns "incorrect input".

If string contains 4 numbers but not consecutive it returns "not consecutive".

import re
def check_root(string):
    if not re.fullmatch(r"(-?\d+,){3}-?\d+", string):
        return 'incorrect input'
    a, b, c, d = list(map(int, string.split(",")))
    if not d == c + 1 == b + 2 == a + 3:
        return 'not consecutive'
    return f"{a * b * c * d + 1}, {abs(b ** 2 + a)}"


Solve in Python:
Who's interested in football?
Rayne Wooney has been one of the top players for his football club for the last few years. But unfortunately, he got injured during a game a few months back and has been out of play ever since.
He's got proper treatment and is eager to go out and play for his team again. Before doing that, he has to prove to his fitness to the coach and manager of the team. Rayne has been playing practice matches for the past few days. He's played N practice matches in all.
He wants to convince the coach and the manager that he's improved over time and that his injury no longer affects his game. To increase his chances of getting back into the team, he's decided to show them stats of any 2 of his practice games. The coach and manager will look into the goals scored in both the games and see how much he's improved. If the number of goals scored in the 2nd game(the game which took place later) is greater than that in 1st, then he has a chance of getting in. Tell Rayne what is the maximum improvement in terms of goal difference that he can show to maximize his chances of getting into the team. If he hasn't improved over time, he's not fit to play. Scoring equal number of goals in 2 matches will not be considered an improvement. Also, he will be declared unfit if he doesn't have enough matches to show an improvement.

-----Input:-----
The first line of the input contains a single integer T, the number of test cases.
Each test case begins with a single integer N, the number of practice matches Rayne has played.

The next line contains N integers. The ith integer, gi, on this line represents the number of goals Rayne scored in his ith practice match. The matches are given in chronological order i.e. j > i means match number j took place after match number i.

-----Output:-----
For each test case output a single line containing the maximum goal difference that Rayne can show to his coach and manager. If he's not fit yet, print "UNFIT".

-----Constraints:-----
1<=T<=10

1<=N<=100000

0<=gi<=1000000...

T = int(input())
for j in range(0,T):
 line1, line2 = input(), input()
 seq = line2.split()
 current_min = 1000001
 current_max = 0
 max_spread = 0
 for i in range(0,len(seq)):
  current_value = int(seq[i])
  if current_min > current_value:
   current_min = current_value
   current_max = current_value
  elif current_max < current_value:
   current_max = current_value
   if max_spread < (current_max - current_min):
    max_spread = current_max - current_min
 if max_spread > 0:
  print(max_spread)
 else:
  print("UNFIT")


Solve in Python:
Why would we want to stop to only 50 shades of grey? Let's see to how many we can go.

Write a function that takes a number n as a parameter and return an array containing n shades of grey in hexadecimal code (`#aaaaaa` for example). The array should be sorted in ascending order starting with `#010101`, `#020202`, etc. (using lower case letters).

```python
def shades_of_grey(n):
  return '''n shades of grey in an array'''
```

As a reminder, the grey color is composed by the same number of red, green and blue: `#010101`, `#aeaeae`, `#555555`, etc. Also, `#000000` and `#ffffff` are not accepted values.

When n is negative, just return an empty array.
If n is higher than 254, just return an array of 254 elements.

Have fun

def shades_of_grey(n):
    if n <= 0:
        return []
    return ['#{0:02x}{0:02x}{0:02x}'.format(n) for n in range(1, min(n, 254) + 1)]


Solve in Python:
Will you make it?

You were camping with your friends far away from home, but when it's time to go back, you realize that your fuel is running out and the nearest pump is ```50``` miles away! You know that on average, your car runs on about ```25``` miles per gallon. There are ```2``` gallons left. Considering these factors, write a function that tells you if it is possible to get to the pump or not. Function should return ``true`` (`1` in Prolog) if it is possible and ``false`` (`0` in Prolog) if not.
The input values are always positive.

def zero_fuel(distance_to_pump, mpg, fuel_left):
    miles = mpg * fuel_left
    if distance_to_pump <= miles:
        return True
    else:
        return False
    #Happy Coding! ;)


Solve in Python:
Wilson primes satisfy the following condition.
Let ```P``` represent a prime number.

Then ```((P-1)! + 1) / (P * P)``` should give a whole number.

Your task is to create a function that returns ```true``` if the given number is a Wilson prime.

def am_i_wilson(p):
    if p in {5, 13, 563}: return True
    else: return False


Solve in Python:
With a friend we used to play the following game on a chessboard
(8, rows, 8 columns).
On the first row at the *bottom* we put numbers:

`1/2, 2/3, 3/4, 4/5, 5/6, 6/7, 7/8, 8/9`

On row 2 (2nd row from the bottom) we have:

`1/3, 2/4, 3/5, 4/6, 5/7, 6/8, 7/9, 8/10`

On row 3:

`1/4, 2/5, 3/6, 4/7, 5/8, 6/9, 7/10, 8/11`

until last row:

`1/9, 2/10, 3/11, 4/12, 5/13, 6/14, 7/15, 8/16`

When all numbers are on the chessboard each in turn we toss a coin. The one who get "head" wins and
the other gives him, in dollars, the **sum of the numbers on the chessboard**.
We play for fun, the dollars come from a monopoly game!

### Task
How much can I (or my friend) win or loses for each game if the chessboard has n rows and n columns? Add all of the fractional values on an n by n sized board and give the answer as a simplified fraction.

- Ruby, Python, JS, Coffee, Clojure, PHP, Elixir, Crystal, Typescript, Go:

The function called 'game' with parameter n (integer >= 0) returns as result an irreducible fraction written as an array of integers: [numerator, denominator].
If the denominator is 1 return [numerator].

- Haskell:

'game' returns either a "Left Integer" if denominator is 1 otherwise
"Right (Integer, Integer)"

- Prolog:
'game' returns an irreducible fraction written as an array of integers: [numerator, denominator].
If the denominator is 1 return [numerator, 1].

- Java, C#, C++, F#, Swift, Reason, Kotlin:

'game' returns a string that mimicks the array returned in Ruby, Python, JS, etc...

- Fortran, Bash: 'game' returns a string

- Forth: return on the stack the numerator and the denominator (even if the denominator is 1)

- In Fortran - as in any other language - the returned string is not permitted
to contain any redundant trailing whitespace: you can use dynamically allocated character strings.

#### See Example Test Cases for each language

def game(n):
    return [n * n // 2] if n % 2 == 0 else [n * n, 2]


Solve in Python:
With one die of 6 sides we will have six different possible results:```  1, 2, 3, 4, 5, 6``` .

With 2 dice of six sides, we will have 36 different possible results:
```
(1,1),(1,2),(2,1),(1,3),(3,1),(1,4),(4,1),(1,5),
(5,1), (1,6),(6,1),(2,2),(2,3),(3,2),(2,4),(4,2),
(2,5),(5,2)(2,6),(6,2),(3,3),(3,4),(4,3),(3,5),(5,3),
(3,6),(6,3),(4,4),(4,5),(5,4),(4,6),(6,4),(5,5),
(5,6),(6,5),(6,6)
```
So, with 2 dice of 6 sides we get 36 different events.
```
([6,6] ---> 36)
```
But with 2 different dice we can get for this case, the same number of events.
One die of ```4 sides```  and another of ```9 sides```  will produce the exact amount of events.
```
([4,9] ---> 36)
```
We say that the dice set ```[4,9]``` is equivalent to ```[6,6]``` because both produce the same number of events.

Also we may have an amount of three dice producing the same amount of events. It will be for:
```
[4,3,3] ---> 36
```
(One die of 4 sides and two dice of 3 sides each)

Perhaps you may think that the following set is equivalent: ```[6,3,2]``` but unfortunately dice have a **minimum of three sides** (well, really a
tetrahedron with one empty side)

The task for this kata is to get the amount of equivalent dice sets, having **2 dice at least**,for a given set.

For example, for the previous case: [6,6] we will have 3 equivalent sets that are: ``` [4, 3, 3], [12, 3], [9, 4]``` .

You may assume that dice are available from 3 and above for any value up to an icosahedral die (20 sides).
```
[5,6,4] ---> 5 (they are [10, 4, 3], [8, 5, 3], [20, 6], [15, 8], [12, 10])
```
For the cases we cannot get any equivalent set the result will be `0`.
For example for the set `[3,3]` we will not have equivalent dice.

Range of inputs for Random Tests:
```
3 <= sides <= 15
2 <= dices <= 7
```
See examples in the corresponding box.

Enjoy it!!

from math import floor, sqrt
from numpy import prod

def f(n, l=3):
    if n < l:
        return
    for p in range(l, min(floor(sqrt(n)) + 1, 21)):
        if not n % p:
            for l in f(n // p, p):
                yield [p] + l
    if n <= 20:
        yield [n]

def eq_dice(l):
    return sum(1 for l in f(prod(l)) if len(l) > 1) - (len(l) > 1)


Solve in Python:
With respect to a given puzzle string, a word is valid if both the following conditions are satisfied:

word contains the first letter of puzzle.
For each letter in word, that letter is in puzzle.
        For example, if the puzzle is "abcdefg", then valid words are "faced", "cabbage", and "baggage"; while invalid words are "beefed" (doesn't include "a") and "based" (includes "s" which isn't in the puzzle).

Return an array answer, where answer[i] is the number of words in the given word list words that are valid with respect to the puzzle puzzles[i].

Example :
Input:
words = ["aaaa","asas","able","ability","actt","actor","access"],
puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"]
Output: [1,1,3,2,4,0]
Explanation:
1 valid word for "aboveyz" : "aaaa"
1 valid word for "abrodyz" : "aaaa"
3 valid words for "abslute" : "aaaa", "asas", "able"
2 valid words for "absoryz" : "aaaa", "asas"
4 valid words for "actresz" : "aaaa", "asas", "actt", "access"
There're no valid words for "gaswxyz" cause none of the words in the list contains letter 'g'.

Constraints:

1 <= words.length <= 10^5
4 <= words[i].length <= 50
1 <= puzzles.length <= 10^4
puzzles[i].length == 7
words[i][j], puzzles[i][j] are English lowercase letters.
Each puzzles[i] doesn't contain repeated characters.

from itertools import combinations
from collections import defaultdict
class Solution:
    def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:
            wordmap = defaultdict(int)
            for word in words:
                mask = 0
                for c in word:
                    mask = mask | (1<<(ord(c)-ord('a')))
                wordmap[mask] += 1
            ans = [0 for i in range(len(puzzles))]
            for i, p in enumerate(puzzles):
                starting_letter = p[0]
                for k in range(0, len(p[1:])+1):
                    for comb in combinations(p[1:], k):
                        mask = 1<<(ord(starting_letter)-  ord('a'))
                        for c in comb:
                            mask = mask | (1<<(ord(c)-ord('a')))
                        ans[i] += wordmap[mask]
            return ans


Solve in Python:
With your birthday coming up soon, your eccentric friend sent you a message to say "happy birthday":

    hhhappyyyy biirrrrrthddaaaayyyyyyy to youuuu
    hhapppyyyy biirtttthdaaay too youuu
    happy birrrthdayy to youuu
    happpyyyy birrtthdaaay tooooo youu

At first it looks like a song, but upon closer investigation, you realize that your friend hid the phrase "happy birthday" thousands of times inside his message. In fact, it contains it more than 2 million times! To thank him, you'd like to reply with exactly how many times it occurs.

To count all the occurences, the procedure is as follows: look through the paragraph and find a `'h'`; then find an `'a'` later in the paragraph; then find an `'p'` after that, and so on. Now count the number of ways in which you can choose letters in this way to make the full phrase.

More precisely, given a text string, you are to determine how many times the search string appears as a sub-sequence of that string.

Write a function called `countSubsequences` that takes two arguments: `needle`, the string to be search for and `haystack`, the string to search in. In our example, `"happy birthday"` is the needle and the birthday message is the haystack. The function should return the number of times `needle` occurs as a sub-sequence of `haystack`.  Spaces are also considered part of the needle.

Since the answers can be very large, return only the last 8 digits of the answer in case it exceeds 8 digits. The answers to the test cases will all be shorter than 8 digits.

from functools import reduce
_=[1,2048,0,1,3,7680,2533968]
def count_subsequences(a, b):
    b = b[b.index(a[0]):]
    Q, l = [], 0
    for i in a:
        W = ''
        while l < len(b) and  b[l] == i:
            W += i
            l += 1
        Q.append(len(W))
    return _.pop(0)if _ else reduce(lambda a,b: a*b, Q)


Solve in Python:
Witua is a little student from the University of Lviv. He enjoys studying math. Witua knows a lot of famous mathematicians like Eratosthenes, Pythagoras, Fermat, Diophantus, Furko, Gauss and so on. However, his favorite one is Euler. The only thing Witua likes more than Euler is Euler’s totient function φ. He is exploring the nature of this function. One of the steps of his work is finding φ(i)/i for all 2≤i≤N. He doesn’t need to know every such value, but Witua wonders for what value i, is φ(i)/i the maximum he can get? Help little student to find such i that φ(i)/i is maximum among all the  2≤i≤N.

-----Input-----
The first line contains single integer T - the number of test cases. Each of the next T lines contains a single integer N.

-----Output-----
For every test case output i such that φ(i)/i is maximum among all i (2≤i≤N) in a separate line.

-----Constrains-----
T (1≤T≤500 )

N(2≤N≤10^18)

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

Output:
2
3
3

Explanationφ(2)/2=1/2
φ(3)/3=2/3
φ(4)/4=2/4

# cook your dish here
def modular_pow(base, exponent, modulus):
 result = 1
 while exponent > 0:
  if(exponent %2 == 1):
   result = (result * base) % modulus
  exponent = exponent//2
  base = (base * base)%modulus
 return result
def passesMillerRabinTest(n, a):
 s = 0
 d = n-1
 while(d%2 == 0):
  s += 1
  d >>= 1
 x = modular_pow(a, d, n)
 if(x == 1 or x == n-1):
  return True
 for ss in range(s - 1):
  x = (x*x)%n
  if(x == 1):
   return False
  if(x == n-1):
   return True
 return False
primeList = (2, 3,5,7,11,13,17,19, 23,29, 31,37)
def isPrime(n):
 for p in primeList:
  if n%p == 0:
   return n == p
 for p in primeList:
  if passesMillerRabinTest(n, p) == False:
   return False
 return True

t = int(input())
for tt in range(t):
 n = int(input())
 if(n == 2):
  print(2)
  continue
 if n%2 == 0:
  n -= 1
 while True:
  if(isPrime(n)):
   print(n)
   break
  n -= 2


Solve in Python:
Word $s$ of length $n$ is called $k$-complete if   $s$ is a palindrome, i.e. $s_i=s_{n+1-i}$ for all $1 \le i \le n$;  $s$ has a period of $k$, i.e. $s_i=s_{k+i}$ for all $1 \le i \le n-k$.

For example, "abaaba" is a $3$-complete word, while "abccba" is not.

Bob is given a word $s$ of length $n$ consisting of only lowercase Latin letters and an integer $k$, such that $n$ is divisible by $k$. He wants to convert $s$ to any $k$-complete word.

To do this Bob can choose some $i$ ($1 \le i \le n$) and replace the letter at position $i$ with some other lowercase Latin letter.

So now Bob wants to know the minimum number of letters he has to replace to convert $s$ to any $k$-complete word.

Note that Bob can do zero changes if the word $s$ is already $k$-complete.

You are required to answer $t$ test cases independently.

-----Input-----

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

The first line of each test case contains two integers $n$ and $k$ ($1 \le k < n \le 2 \cdot 10^5$, $n$ is divisible by $k$).

The second line of each test case contains a word $s$ of length $n$.

It is guaranteed that word $s$ only contains lowercase Latin letters. And it is guaranteed that the sum of $n$ over all test cases will not exceed $2 \cdot 10^5$.

-----Output-----

For each test case, output one integer, representing the minimum number of characters he has to replace to convert $s$ to any $k$-complete word.

-----Example-----
Input
4
6 2
abaaba
6 3
abaaba
36 9
hippopotomonstrosesquippedaliophobia
21 7
wudixiaoxingxingheclp

Output
2
0
23
16

-----Note-----

In the first test case, one optimal solution is aaaaaa.

In the second test case, the given word itself is $k$-complete.

import sys
input = lambda: sys.stdin.readline().rstrip()
def calc(n, k, A):
    X = [[0] * 26 for _ in range((k+1)//2)]
    for i, a in enumerate(A):
        j = i % k
        j = min(j, k-1-j)
        X[j][a] += 1
    return sum([sum(x) - max(x) for x in X])

T = int(input())
for _ in range(T):
    N, K = list(map(int, input().split()))
    S = [ord(a) - 97 for a in input()]
    print(calc(N, K, S))


Solve in Python:
Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468.

Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420.

We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number; for example, 155349.

Clearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers below one-thousand (525) are bouncy. In fact, the least number for which the proportion of bouncy numbers first reaches 50% is 538.

Surprisingly, bouncy numbers become more and more common and by the time we reach 21780 the proportion of bouncy numbers is equal to 90%.

#### Your Task

Complete the bouncyRatio function.

The input will be the target ratio.

The output should be the smallest number such that the proportion of bouncy numbers reaches the target ratio.

You should throw an Error for a ratio less than 0% or greater than 99%.

**Source**

  - https://projecteuler.net/problem=112

**Updates**

  - 26/10/2015: Added a higher precision test case.

def bouncy_ratio(percent):
    is_bouncy = lambda n: any(a < b for a, b in zip(n, n[1:])) \
                        and any(a > b for a, b in zip(n, n[1:]))
    n, bouncy = 99, 0
    while bouncy < percent * n:
        n += 1
        bouncy += is_bouncy(str(n))
    return n


Solve in Python:
Write

```python
function combine()
```

that combines arrays by alternatingly taking elements passed to it.

E.g

```python
combine(['a', 'b', 'c'], [1, 2, 3]) == ['a', 1, 'b', 2, 'c', 3]
combine(['a', 'b', 'c'], [1, 2, 3, 4, 5]) == ['a', 1, 'b', 2, 'c', 3, 4, 5]
combine(['a', 'b', 'c'], [1, 2, 3, 4, 5], [6, 7], [8]) == ['a', 1, 6, 8, 'b', 2, 7, 'c', 3, 4, 5]
```

Arrays can have different lengths.

from itertools import chain, zip_longest

def combine(*args):
    return [x for x in chain.from_iterable(zip_longest(*args)) if x is not None]