Solve in Python:
We are given two arrays A and B of words.  Each word is a string of lowercase letters.
Now, say that word b is a subset of word a if every letter in b occurs in a, including multiplicity.  For example, "wrr" is a subset of "warrior", but is not a subset of "world".
Now say a word a from A is universal if for every b in B, b is a subset of a.
Return a list of all universal words in A.  You can return the words in any order.

Example 1:
Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["e","o"]
Output: ["facebook","google","leetcode"]

Example 2:
Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["l","e"]
Output: ["apple","google","leetcode"]

Example 3:
Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["e","oo"]
Output: ["facebook","google"]

Example 4:
Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["lo","eo"]
Output: ["google","leetcode"]

Example 5:
Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["ec","oc","ceo"]
Output: ["facebook","leetcode"]

Note:

1 <= A.length, B.length <= 10000
1 <= A[i].length, B[i].length <= 10
A[i] and B[i] consist only of lowercase letters.
All words in A[i] are unique: there isn't i != j with A[i] == A[j].

class Solution:
    def wordSubsets(self, A: List[str], B: List[str]) -> List[str]:
        superword = [0] * 26
        result = []
        for word in B:
            current = [0] * 26
            for ch in word:
                i = ord(ch) - ord('a')
                current[i] += 1

            for i in range(26):
                superword[i] = max(superword[i],current[i])

        for word in A:
            current = [0] * 26
            for ch in word:
                i = ord(ch) - ord('a')
                current[i] += 1

            found = True
            for i in range(26):
                if superword[i] > current[i]:
                    found = False
                    break

            if found == True:
                result.append(word)

        return result


Solve in Python:
We are given head, the head node of a linked list containing unique integer values.
We are also given the list G, a subset of the values in the linked list.
Return the number of connected components in G, where two values are connected if they appear consecutively in the linked list.
Example 1:
Input:
head: 0->1->2->3
G = [0, 1, 3]
Output: 2
Explanation:
0 and 1 are connected, so [0, 1] and [3] are the two connected components.

Example 2:
Input:
head: 0->1->2->3->4
G = [0, 3, 1, 4]
Output: 2
Explanation:
0 and 1 are connected, 3 and 4 are connected, so [0, 1] and [3, 4] are the two connected components.

Note:

If N is the length of the linked list given by head, 1 <= N <= 10000.
The value of each node in the linked list will be in the range [0, N - 1].
1 <= G.length <= 10000.
G is a subset of all values in the linked list.

class Solution:
    def numComponents(self, head: ListNode, G: List[int]) -> int:
        tail = head
        components = 0
        connected = False
        while tail is not None:
            if tail.val in G:
                connected = True
            elif connected:
                components += 1
                connected = False
            tail = tail.next
        if connected:
            components += 1
            connected = False
        return components


Solve in Python:
We are interested in collecting the sets of six prime numbers, that having a starting prime p, the following values are also primes forming the sextuplet ```[p, p + 4, p + 6, p + 10, p + 12, p + 16]```

The first sextuplet that we find is ```[7, 11, 13, 17, 19, 23]```

The second one is ```[97, 101, 103, 107, 109, 113]```

Given a number ```sum_limit```, you should give the first sextuplet which sum (of its six primes) surpasses the sum_limit value.

```python
find_primes_sextuplet(70) == [7, 11, 13, 17, 19, 23]

find_primes_sextuplet(600) == [97, 101, 103, 107, 109, 113]
```
Features of the tests:
```
Number Of Tests = 18
10000 < sum_limit < 29700000
```
If you have solved this kata perhaps you will find easy to solve this one:
https://www.codewars.com/kata/primes-with-two-even-and-double-even-jumps/
Enjoy it!!


Solve in Python:
We are interested in collecting the triples of positive integers ```(a, b, c)``` that fulfill the following equation:
```python
a² + b² = c³
```
The first triple with the lowest values that satisfies the equation we have above is (2, 2 ,2).
In effect:
```python
2² + 2² = 2³
4  + 4  = 8
```
The first pair of triples that "shares" the same value of ```c``` is: ```(2, 11, 5)``` and ```(5, 10, 5)```.

Both triples share the same value of ```c```  is ```c = 5```.
```python
Triple (2, 11, 5)                  Triple(5, 10, 5)
2² + 11² =  5³                      5² +  10²  =  5³
4  + 121 = 125                     25  + 100   = 125
```
So, we say that the value ```c``` has two solutions because there are two triples sharing the same value of ```c```.

There are some values of ```c``` with no solutions.

The first value of ```c``` that have a surprising number of solutions is ```65``` with ```8``` different triples.

In order to avoid duplications you will consider that ```a <= b``` always.

Make the function ```find_abc_sumsqcube()```, that may give us the values of c for an specific number of solutions.

For that purpose the above required function will receive two arguments, ```c_max``` and ```num_sol```. It is understandable that ```c_max``` will give to our function the upper limit of ```c``` and ```num_sol```, the specific number of solutions.

The function will output a sorted list with the values of ```c``` that have a number of solutions equals to ```num_sol```

Let's see some cases:
```python
find_abc_sumsqcube(5, 1) == [2] # below or equal to c_max = 5 we have triple the (2, 2, 2) (see above)

find_abc_sumsqcube(5, 2) == [5] # now we want the values of ```c ≤ c_max``` with two solutions (see above again)

find_abc_sumsqcube(10, 2) == [5, 10]

find_abc_sumsqcube(20, 8) == [] # There are no values of c equal and bellow 20 having 8 solutions.
```

Our tests will have the following ranges for our two arguments:
```python
5 ≤ c_max ≤ 1000
1 ≤ num_sol ≤ 10
```
Happy coding!!

from bisect import bisect_right as bisect

RES = [[] for _ in range(11)]

for c in range(1,1001):
    c3 = c**3
    nSol = sum( ((c3-a**2)**.5).is_integer() for a in range(1,int((c3//2)**.5+1)))
    if 0 < nSol < 11: RES[nSol].append(c)

def find_abc_sumsqcube(c_max, nSol):
    return RES[nSol][:bisect(RES[nSol], c_max)]


Solve in Python:
We are interested in obtaining two scores from a given integer:

**First score**: The sum of all the integers obtained from the power set of the digits of the given integer that have the same order

E.g:
```
integer = 1234 ---> (1 + 2 + 3 + 4) + (12 + 13 + 14 + 23 + 24 + 34) +
(123 + 124 + 134 + 234) + 1234 = 10 + 120 + 615 + 1234 = 1979
```
**Second score**: The sum of all the integers obtained from the all the contiguous substrings of the given integer as a string.

E.g.
```
integer = 1234 ---> (1 + 2 + 3 + 4) + (12 + 23 + 34) + (123 + 234) + 1234 = 10 + 69 + 357 + 1234 = 1670
```
The first integer, higher than ```100```, that has both scores with ```3``` common divisors is ```204```. Its first score is ```258``` and the second one ```234```. The common divisors for both scores are ```2, 3, 6```.

In fact the integers ```294``` and ```468``` are the ones in the range ```[100, 500]```, that have both scores with ```7``` common divisors, the maximum amount of common factors in that range.

Your task in this kata is to create a function that may find the integer or integers that have the maximum amount of common divisors for the scores described above.

The example given above will be:
```python
find_int_inrange(100, 500) == [7, 294, 468]
```
As you can see, the function should receive the limits of a range [a, b], and outputs an array with the maximum amount of factors, ```max_am_div``` and the found numbers sorted
```
find_int_inrange(a, b) ----> [max_am_div, k1, k2, ...., kn] # k1 < k2 < ...< kn
```
The function may output only one number.
```python
find_int_inrange(100, 300) == [7, 294]
```
Enjoy it!

Features of the random tests:
```
100 < a < b < 55000
```

from itertools import combinations as C
from functools import lru_cache as LC
get_score1=LC(None)(lambda n:sum([sum([int(''.join(k)) for k in C(n, i)]) for i in range(1, len(n) + 1)]))
get_score2=LC(None)(lambda n:sum(int(n[j:j + i]) for i in range(1, len(n) + 1) for j in range(len(n) - i + 1)))
get_div=LC(None)(lambda n:set(sum([[i, n // i] for i in range(2, int(n ** .5) + 1) if not n % i], [])))
@LC(None)
def find_int_inrange(a, b):
    d = {i:len(get_div(get_score1(str(i))) & get_div( get_score2(str(i)))) for i in range(a, b)}
    m = max(d.values())
    return [m]+sorted([i for i,j in d.items() if j==m]) #sorted for py 3.4


Solve in Python:
We are stacking blocks to form a pyramid.  Each block has a color which is a one letter string, like `'Z'`.

For every block of color `C` we place not in the bottom row, we are placing it on top of a left block of color `A` and right block of color `B`.  We are allowed to place the block there only if `(A, B, C)` is an allowed triple.

We start with a bottom row of bottom, represented as a single string.  We also start with a list of allowed triples allowed.  Each allowed triple is represented as a string of length 3.

Return true if we can build the pyramid all the way to the top, otherwise false.

Example 1:

Input: bottom = "XYZ", allowed = ["XYD", "YZE", "DEA", "FFF"]
Output: true
Explanation:
We can stack the pyramid like this:
    A
   / \
  D   E
 / \ / \
X   Y   Z

This works because ('X', 'Y', 'D'), ('Y', 'Z', 'E'), and ('D', 'E', 'A') are allowed triples.

Example 2:

Input: bottom = "XXYX", allowed = ["XXX", "XXY", "XYX", "XYY", "YXZ"]
Output: false
Explanation:
We can't stack the pyramid to the top.
Note that there could be allowed triples (A, B, C) and (A, B, D) with C != D.

Note:

bottom will be a string with length in range [2, 8].
allowed will have length in range [0, 200].
Letters in all strings will be chosen from the set {'A', 'B', 'C', 'D', 'E', 'F', 'G'}.

import heapq
 class Solution(object):
     def pourWater(self, heights, V, K):
         """
         :type heights: List[int]
         :type V: int
         :type K: int
         :rtype: List[int]
         """

         heap = []
         heapq.heappush(heap, (heights[K], -1, 0))
         l, r = K - 1, K + 1
         lh, rh = [], []

         for i in range(V):
             while l >= 0 and heights[l] <= heights[l + 1]:
                 heapq.heappush(lh, (heights[l], -l))
                 l -= 1

             while r < len(heights) and heights[r] <= heights[r - 1]:
                 heapq.heappush(rh, (heights[r], r))
                 r += 1

             if lh and lh[0][0] < heights[K]:
                 h, i = heapq.heappop(lh)
                 heights[-i] += 1
                 heapq.heappush(lh, (h + 1, i))
                 continue

             if rh and rh[0][0] < heights[K]:
                 h, i = heapq.heappop(rh)
                 heights[i] += 1
                 heapq.heappush(rh, (h + 1, i))
                 continue

             heights[K] += 1

         return heights


Solve in Python:
We are still with squared integers.

Given 4 integers `a, b, c, d` we form the sum of the squares of `a` and `b`
and then the sum of the squares of `c` and `d`. We multiply the two sums hence a number `n` and we try to
decompose `n` in a sum of two squares `e` and `f` (e and f integers >= 0) so that `n = e² + f²`.

More: `e` and `f` must result only from sums (or differences) of products between on the one hand `(a, b)` and on the other `(c, d)` each of `a, b, c, d` taken only once.
For example,
prod2sum(1, 2, 1, 3) should return [[1, 7], [5, 5]])
because
```
1==1*3-1*2
7==2*3+1*1
5==1*2+1*3
```
Suppose we have `a = 1, b = 2, c = 1, d = 3`. First we calculate the sums
`1² + 2² = 5 and 1² + 3² = 10` hence `n = 50`.

`50 = 1² + 7² or 50 = 7² + 1²` (we'll consider that these two solutions are the same)
or `50 = 5² + 5²`.

The return of our function will be an array of subarrays (in C an array of Pairs) sorted on the first elements of the subarrays. In each subarray the lower element should be the first.

`prod2sum(1, 2, 1, 3) should return [[1, 7], [5, 5]]`

`prod2sum(2, 3, 4, 5) should return  [[2, 23], [7, 22]]`

because `(2² + 3²) * (4² + 5²) = 533 = (7² + 22²) = (23² + 2²)`

`prod2sum(1, 2, 2, 3) should return  [[1, 8], [4, 7]]`

`prod2sum(1, 1, 3, 5) should return  [[2, 8]]` (there are not always 2 solutions).

##Hint
Take a sheet of paper and with a bit of algebra try to write the product of squared numbers in another way.

def chsgn(k):
    r = []
    for x in k:
        if (x < 0):
            r.append(-x)
        else:
            r.append(x)
    return r

def prod2sum(a, b, c, d):
    e1 = a * c + b * d
    f1 = a * d - b * c
    e2 = a * c - b * d
    f2 = a * d + b * c
    k = chsgn([e1, e2, f1, f2])
    e1 = k[0]; e2 = k[1]; f1 = k[2]; f2 = k[3]
    if ((e1 == f2) and (f1 == e2)) or ((e1 == e2) and (f1 == f2)):
        res = [[min(e1,f1), max(e1,f1)]]
    else:
        res = [[min(e1,f1), max(e1,f1)]]
        res.append([min(e2,f2), max(e2,f2)])
    res = sorted(res, key=lambda x: x[0])
    return res


Solve in Python:
We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.

Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.

Example 1:

Input: [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].

Note:
The length of the input array will not exceed 20,000.

class Solution:
     def findLHS(self, nums):
         """
         :type nums: List[int]
         :rtype: int
         """
         count = collections.Counter(nums)
         ret = 0
         for i in count:
             if i+1 in count:
                 ret = max(ret, count[i]+count[i+1])

         return ret


Solve in Python:
We define the "unfairness" of a list/array as the *minimal* difference between max(x1,x2,...xk) and min(x1,x2,...xk), for all possible combinations of k elements you can take from the list/array; both minimum and maximum of an empty list/array are considered to be 0.

**More info and constraints:**

* lists/arrays can contain values repeated more than once, plus there are usually more combinations that generate the required minimum;
* the list/array's length can be any value from 0 to 10^(6);
* the value of k will range from 0 to the length of the list/array,
* the minimum unfairness of an array/list with less than 2 elements is 0.

For example:

```python
min_unfairness([30,100,1000,150,60,250,10,120,20],3)==20 #from max(30,10,20)-min(30,10,20)==20, minimum unfairness in this sample
min_unfairness([30,100,1000,150,60,250,10,120,20],5)==90 #from max(30,100,60,10,20)-min(30,100,60,10,20)==90, minimum unfairness in this sample
min_unfairness([1,1,1,1,1,1,1,1,1,2,2,2,2,2,2],10)==1 #from max(1,1,1,1,1,1,1,1,1,2)-min(1,1,1,1,1,1,1,1,1,2)==1, minimum unfairness in this sample
min_unfairness([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],10)==0 #from max(1,1,1,1,1,1,1,1,1,1)-min(1,1,1,1,1,1,1,1,1,1)==0, minimum unfairness in this sample
min_unfairness([1,1,-1],2)==0 #from max(1,1)-min(1,1)==0, minimum unfairness in this sample
```

**Note:** shamelessly taken from [here](https://www.hackerrank.com/challenges/angry-children), where it was created and debatably categorized and ranked.

min_unfairness=lambda a,k:a.sort()or k>0<len(a)and min(b-a for a,b in zip(a,a[k-1:]))


Solve in Python:
We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself.

Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not.

Example:

Input: 28
Output: True
Explanation: 28 = 1 + 2 + 4 + 7 + 14

Note:
The input number n will not exceed 100,000,000. (1e8)

class Solution:
     def checkPerfectNumber(self, num):
         """
         :type num: int
         :rtype: bool
         """
         if num <=0:
             return False
         p=1
         n=1
         while n<num:
             n=2**(p-1)*(2**p-1)
             if n==num:
                 return True
             p+=1
         return False


Solve in Python:
We define the function `f1(n,k)`, as the least multiple of `n` that has all its digits less than `k`.

We define the function `f2(n,k)`, as the least multiple of `n` that has all the digits that are less than `k`.

Each digit may occur more than once in both values of `f1(n,k)` and `f2(n,k)`.

The possible values for `n` and `k` according to these ranges for both functions `f1` and `f2` in this kata:
```
1 <= n <= 1.000.000.000.000
3 <= k <= 9
```

For example, let's see the value of both functions for `n = 71` and `k = 4`:
```
f1(71,4) == 213 # all its digits less than 4
f2(71,4) == 2130 # 0,1,2,3 all of them present
```
The integer `76` is the first integer that has the same values of `f1` and `f2` for `k = 4`.
```
f1(76,4) = f2(76,4) = 10032
```
Let's call these kind of numbers, **forgiving numbers**. (Let's continue with the fashion of attributing personality traits to numbers and, of course, an unknown one)
So, `76` is the smallest forgiving number of order `4`.
In the same way, `485` is the smallest forgiving number of order `5`.

Create a function that given an integer `n` and the order `k`, will output the higher and closest forgiving number to `n` of order `k`.

Let's see some examples:
```
find_f1_eq_f2(500,5) == 547
find_f1_eq_f2(1600,6) == 1799
find_f1_eq_f2(14900,7) == 14996
```
If the number `n` is a forgiving itself for a certain order `k`, the function will never output the same value, remember, closest and **higher** than `n`.

For example, `3456`, is a forgiving one of order `4`,
```
find_f1_eq_f2(3456,4) == 3462
```
**Features of the tests:**

* `n` and `k` will be always valid and positive integers.

* A total of 8 fixed tests.

* A total of 150 random tests in the ranges for `n` and `k` given above.

I'll be waiting your awesome solution. :)

def digits_less_than(n,k):
    for i in str(n):
        if int(i) >= k:
            return False
    return True

def all_digits_less_than(n,d):
    for i in d:
        if i not in str(n):
            return False
    return True

def find_f1_eq_f2(n,k):
    d = '012'
    for i in range(3,k):
        d += str(i)
    m = 0
    i = 0
    while not all_digits_less_than((m+n)*i,d):
        m += 1
        i = 1
        while not digits_less_than((m+n)*i,k):
            i += 1
    return m+n


Solve in Python:
We define the score of permutations of combinations, of an integer number (the function to obtain this value:```sc_perm_comb```) as the total sum of all the numbers obtained from the permutations of all the possible combinations of its digits.
For example we have the number 348.
```python
sc_perm_comb(348) = 3 + 4 + 8 + 34 + 38 + 48 + 43 + 83 + 84 + 348 + 384 + 834 + 843 + 438 + 483  = 3675
```
If the number has a digit 0, the numbers formed by a leading 0 should be discarded:
```python
sc_perm_comb(340) = 3 + 4 + 34 + 30 + 40 + 43 + 340 + 304 + 430 + 403 = 1631
```
If the number has digits that occur more than once, the score the adden will not be taken than twice or more:
```python
sc_perm_comb(333) = 3 + 33 + 333 = 369
```
If the number has only one digit its score is the same number:
```python
sc_perm_comb(6) = 6
sc_perm_comb(0) = 0
```

Enjoy it!!

import itertools

#With combinations, we allow leading zeros, e.g. '03' is allowed, because when we permute, '03' becomes '30'
def getAllCombinations(numStr, numDigits):
    combedDigits = []
    for d in range(1, numDigits+1):     #interval [1, numDigits]
        numList = [(''.join(p)) for p in itertools.combinations(numStr, d) ]
        uniqueNumList = set(numList)
        combedDigits.append( uniqueNumList )

    return combedDigits
#-----end function

def sc_perm_comb( n ):
    numStr = str(n)
    numDigits = len(numStr)

    combStrList = getAllCombinations(numStr, numDigits)

    permSet = set()
    for numsOfDigitD in combStrList:
        for num in numsOfDigitD:
            allPerms = [int(''.join(p)) for p in itertools.permutations((num)) if p[0]!='0']
            permSet.update(set(allPerms))    #punch out all repeats

    totalSum  = sum( permSet )

    return totalSum
#---end function


Solve in Python:
We define the sequence ```SF``` in the following way in terms of four previous sequences: ```S1```, ```S2```, ```S3``` and ```ST```

We are interested in collecting the terms of SF that are multiple of ten.

The first term multiple of ten of this sequence is  ```60```

Make the function ```find_mult10_SF()``` that you introduce the ordinal number of a term multiple of 10 of SF and gives us the value of this term.

Let's see some cases:
```python
find_mult10_SF(1) == 60

find_mult10_SF(2) == 70080

find_mult10_SF(3) ==  90700800
```
``` haskell
findMult10SF 1 `shouldBe` 60
findMult10SF 2 `shouldBe` 70080
findMult10SF 3 `shouldBe` 90700800
```
Memoization is advisable to have a more agile code for tests.

Your code will be tested up to the 300-th term, multiple of 10.

Happy coding!!


Solve in Python:
We guessed a permutation $p$ consisting of $n$ integers. The permutation of length $n$ is the array of length $n$ where each element from $1$ to $n$ appears exactly once. This permutation is a secret for you.

For each position $r$ from $2$ to $n$ we chose some other index $l$ ($l < r$) and gave you the segment $p_l, p_{l + 1}, \dots, p_r$ in sorted order (i.e. we rearranged the elements of this segment in a way that the elements of this segment are sorted). Thus, you are given exactly $n-1$ segments of the initial permutation but elements inside each segment are sorted. The segments are given to you in random order.

For example, if the secret permutation is $p=[3, 1, 4, 6, 2, 5]$ then the possible given set of segments can be:  $[2, 5, 6]$  $[4, 6]$  $[1, 3, 4]$  $[1, 3]$  $[1, 2, 4, 6]$

Your task is to find any suitable permutation (i.e. any permutation corresponding to the given input data). It is guaranteed that the input data corresponds to some permutation (i.e. such permutation exists).

You have to answer $t$ independent test cases.

-----Input-----

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

The first line of the test case contains one integer $n$ ($2 \le n \le 200$) — the length of the permutation.

The next $n-1$ lines describe given segments.

The $i$-th line contains the description of the $i$-th segment. The line starts with the integer $k_i$ ($2 \le k_i \le n$) — the length of the $i$-th segment. Then $k_i$ integers follow. All integers in a line are distinct, sorted in ascending order, between $1$ and $n$, inclusive.

It is guaranteed that the required $p$ exists for each test case.

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

-----Output-----

For each test case, print the answer: $n$ integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$, all $p_i$ should be distinct) — any suitable permutation (i.e. any permutation corresponding to the test...

import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LI1(): return list(map(int1, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def main():
    def ok():
        if len(ans)<n:return False
        for r,si in enumerate(sii,2):
            s=ss[si]
            cur=set(ans[r-len(s):r])
            if s!=cur:return False
        return True

    for _ in range(II()):
        n=II()
        ee=[[n**2]*n for _ in range(n)]
        for ei in range(n):ee[ei][ei]=0
        ss=[set(LI()[1:]) for _ in range(n-1)]
        for a0 in range(1,n+1):
            used=set([a0])
            ans=[a0]
            sii=[]
            for _ in range(n-1):
                nxt=[]
                for si,s in enumerate(ss):
                    cur=s-used
                    if len(cur)==1:
                        for a in cur:nxt.append(a)
                        sii.append(si)
                if len(nxt)!=1:break
                ans.append(nxt[0])
                used.add(nxt[0])
            if ok():break
        print(*ans)

main()


Solve in Python:
We have 3 equations with 3 unknowns x, y, and z and we are to solve for these unknowns.
Equations 4x -3y +z = -10, 2x +y +3z = 0, and -x +2y -5z = 17 will be passed in as an array of [[4, -3, 1, -10], [2, 1, 3, 0], [-1, 2, -5, 17]] and the result should be returned as an array like [1, 4, -2] (i.e. [x, y, z]).

Note: In C++ do not use new or malloc to allocate memory for the returned variable as allocated memory will not be freed in the Test Cases. Setting the variable as static will do.

import numpy as np

def solve_eq(eq):
    a = np.array([arr[:3] for arr in eq])
    b = np.array([arr[-1] for arr in eq])
    return [round(x) for x in np.linalg.solve(a,b)]


Solve in Python:
We have a board with an H \times W grid.
Each square in the grid is painted in black or white. The square at the i-th row from the top and j-th column from the left is black if the j-th character in S_i is #, and white if that character is ..
Snuke can perform the following operation on the grid any number of times:
 - Select a row or column in the grid, and invert the color of all the squares in that row or column (that is, black squares become white and vice versa).
Then, Snuke draws a rectangle along grid lines. Here, all the squares contained in the rectangle must be painted in black.
Find the maximum possible area of Snuke's rectangle when the operation is performed optimally.

-----Constraints-----
 - 2 \leq H \leq 2000
 - 2 \leq W \leq 2000
 - |S_i| = W
 - S_i consists of # and ..

-----Input-----
Input is given from Standard Input in the following format:
H W
S_1
S_2
:
S_H

-----Output-----
Print the maximum possible area of Snuke's rectangle.

-----Sample Input-----
3 3
..#
##.
.#.

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

If the first row from the top and the third column from the left are inverted, a 2 \times 3 rectangle can be drawn, as shown below:

import sys
def input():
	return sys.stdin.readline()[:-1]

H, W = map(int, input().split())
s = [input() for _ in range(H)]
ans = max(H, W)

def max_rect(a):
	res = 0
	stack = [a[0]]
	for i in range(1, W-1):
		new_pos = i
		while stack and stack[-1] % 10000 >= a[i]:
			pos, hght = stack[-1] // 10000, stack[-1] % 10000
			res = max(res, (i - pos + 1) * (hght + 1))
			new_pos = pos
			stack.pop()
		stack.append(new_pos * 10000 + a[i])
	while stack:
		pos, hght = stack[-1] // 10000, stack[-1] % 10000
		res = max(res, (W - pos) * (hght + 1))
		stack.pop()
	return res

dp = [[0 for _ in range(W-1)] for _ in range(H-1)]

for j in range(W-1):
	if not ((s[0][j] == s[1][j]) ^ (s[0][j+1] == s[1][j+1])):
		dp[0][j] = 1
ans = max(ans, max_rect(dp[0]))

for i in range(1, H-1):
	for j in range(W-1):
		if not ((s[i][j] == s[i+1][j]) ^ (s[i][j+1] == s[i+1][j+1])):
			dp[i][j] = dp[i-1][j] + 1
	ans = max(ans, max_rect(dp[i]))

print(ans)


Solve in Python:
We have a collection of rocks, each rock has a positive integer weight.
Each turn, we choose any two rocks and smash them together.  Suppose the stones have weights x and y with x <= y.  The result of this smash is:

If x == y, both stones are totally destroyed;
If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x.

At the end, there is at most 1 stone left.  Return the smallest possible weight of this stone (the weight is 0 if there are no stones left.)

Example 1:
Input: [2,7,4,1,8,1]
Output: 1
Explanation:
We can combine 2 and 4 to get 2 so the array converts to [2,7,1,8,1] then,
we can combine 7 and 8 to get 1 so the array converts to [2,1,1,1] then,
we can combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
we can combine 1 and 1 to get 0 so the array converts to [1] then that's the optimal value.

Note:

1 <= stones.length <= 30
1 <= stones[i] <= 100

from heapq import heapify,heappush,heappop
class Solution:
    def lastStoneWeightII(self, stones: List[int]) -> int:
        arr = stones
        n = len(stones)
        su = sum(arr)
        dp = [[0 for i in range(su+1)] for j in range(n+1)]
        for i in range(n + 1):
            dp[i][0] = 1

        for j in range(1,n+1):
            for i in range(1,su+1):
                dp[j][i] = dp[j-1][i]
                if i-arr[j-1]>=0:
                    dp[j][i] |= dp[j-1][i-arr[j-1]]

        diff = sys.maxsize

        # Find the largest j such that dp[n][j]
        # is true where j loops from sum/2 t0 0
        for j in range(su // 2, -1, -1):
            if dp[n][j] == True:
                diff = su - (2 * j)
                break

        return diff


Solve in Python:
We have a collection of stones, each stone has a positive integer weight.
Each turn, we choose the two heaviest stones and smash them together.  Suppose the stones have weights x and y with x <= y.  The result of this smash is:

If x == y, both stones are totally destroyed;
If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x.

At the end, there is at most 1 stone left.  Return the weight of this stone (or 0 if there are no stones left.)

Example 1:
Input: [2,7,4,1,8,1]
Output: 1
Explanation:
We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,
we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,
we combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of last stone.

Note:

1 <= stones.length <= 30
1 <= stones[i] <= 1000

class Solution:
    def lastStoneWeight(self, stones: List[int]) -> int:

        while(len(stones) > 1):
            stones.sort(reverse=True)
            stones[0] = stones[0] - stones[1]
            del stones[1]

        if(len(stones) == 1):
            return stones[0]
        return 0


Solve in Python:
We have a distribution of probability of a discrete variable (it may have only integer values)
```
x       P(x)
0       0.125
1       0.375
2       0.375
3       0.125
Total = 1.000   # The sum of the probabilities for all the possible values should be one (=1)
```
The mean, ```μ```,  of the values of x is:

For our example
```
μ = 0*0.125 + 1*0.375 + 2*0.375 + 3*0.125 = 1.5
```

The variance, ```σ²``` is:

For our example :
```
σ² = 0.75
```

The standard deviation, ```σ``` is:

Finally, for our example:
```
σ = 0.8660254037844386
```
Make the function ```stats_disc_distr()``` that receives a 2D array. Each internal array will have a pair of values: the first one, the value of the variable ```x``` and the second one its correspondent probability, ```P(x)```.

For the example given above:
```python
stats_disc_distr([[0, 0.125], [1, 0.375], [2, 0.375], [3, 0.125]]) == [1.5, 0.75, 0.8660254037844386]
```
The function should check also if it is a valid distribution.

If the sum of the probabilities is different than ```1```, the function should output an alert.
```python
stats_disc_distr([[0, 0.425], [1, 0.375], [2, 0.375], [3, 0.125]]) == "It's not a valid distribution"
```
If one of the values of ```x``` is not an integer, the function will give a specific alert:
```python
stats_disc_distr([[0.1, 0.425], [1.1, 0.375], [2, 0.375], [3, 0.125]]) == "All the variable values should be integers"
```

If the distribution has both problems will output another specific alert:
```python
stats_disc_distr([[0.1, 0.425], [1.1, 0.375], [2, 0.375], [3, 0.125]]) == "It's not a valid distribution and furthermore, one or more variable value are not integers"
```
But if a value is a float with its decimal part equals to 0 will proceed without inconveniences, (if the sum of probabilities is ```1```:
```python
stats_disc_distr([[0.0, 0.125], [1.0, 0.375], [2.0, 0.375], [3, 0.125]]) == [1.5, 0.75, 0.8660254037844386]
```

The 2Darray will not have any strings.

Enjoy it!!

from math import sqrt

def stats_disc_distr(distrib):
    if round(sum(count[1] for count in distrib), 3) != 1:
        if not all(isinstance(count[0], int) for count in distrib):
            return "It's not a valid distribution and furthermore, one or more variable value are not integers"
        else:
            return "It's not a valid distribution"

    if not all(isinstance(count[0], int) for count in distrib):
        return "All the variable values should be integers"

    expected = sum(event * prob for event, prob in distrib)
    variance = sum((event - expected)**2 * prob for event, prob in distrib)
    standard = sqrt(variance)

    return [expected, variance, standard]


Solve in Python:
We have a graph with N vertices and M edges, and there are two people on the graph: Takahashi and Aoki.
The i-th edge connects Vertex U_i and Vertex V_i.
The time it takes to traverse this edge is D_i minutes, regardless of direction and who traverses the edge (Takahashi or Aoki).
Takahashi departs Vertex S and Aoki departs Vertex T at the same time. Takahashi travels to Vertex T and Aoki travels to Vertex S, both in the shortest time possible.
Find the number of the pairs of ways for Takahashi and Aoki to choose their shortest paths such that they never meet (at a vertex or on an edge) during the travel, modulo 10^9 + 7.

-----Constraints-----
 - 1 \leq N \leq 100 000
 - 1 \leq M \leq 200 000
 - 1 \leq S, T \leq N
 - S \neq T
 - 1 \leq U_i, V_i \leq N (1 \leq i \leq M)
 - 1 \leq D_i \leq 10^9 (1 \leq i \leq M)
 - If i \neq j, then (U_i, V_i) \neq (U_j, V_j) and (U_i, V_i) \neq (V_j, U_j).
 - U_i \neq V_i (1 \leq i \leq M)
 - D_i are integers.
 - The given graph is connected.

-----Input-----
Input is given from Standard Input in the following format:
N M
S T
U_1 V_1 D_1
U_2 V_2 D_2
:
U_M V_M D_M

-----Output-----
Print the answer.

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

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

There are two ways to choose shortest paths that satisfies the condition:
 - Takahashi chooses the path 1 \rightarrow 2 \rightarrow 3, and Aoki chooses the path 3 \rightarrow 4 \rightarrow 1.
 - Takahashi chooses the path 1 \rightarrow 4 \rightarrow 3, and Aoki chooses the path 3 \rightarrow 2 \rightarrow 1.

from heapq import *
def dijkstra(g,start):
    n = len(g)
    INF = 1<<61
    dist = [INF]*(n) #startからの最短距離
    num = [0]*n
    dist[start] = 0
    num[start] = 1
    q = [(0,start)] #(そこまでの距離、点)
    while q:
        dv,v = heappop(q)
        if dist[v] < dv: continue
        for to, cost in g[v]:
            if dv + cost < dist[to]:
                dist[to] = dv + cost
                num[to] = num[v]
                heappush(q, (dist[to], to))
            elif dv + cost == dist[to]:
                num[to] += num[v]
                num[to] %= MOD
    return dist,num

# coding: utf-8
# Your code here!
import sys
readline = sys.stdin.readline
read = sys.stdin.read

n,m = list(map(int,readline().split()))
s,t = list(map(int,readline().split()))
s -= 1
t -= 1

g = [[] for _ in range(n)]
edges = []
for _ in range(m):
    a,b,c = list(map(int,readline().split()))
    g[a-1].append((b-1,c))
    g[b-1].append((a-1,c))
    edges.append((a-1,b-1,c))

MOD = 10**9+7
dist,num = dijkstra(g,s)
dt,nt = dijkstra(g,t)

#print(dist,dt)
#print(num,nt)

ans = num[t]**2
#print(ans,"original")

D = dist[t]
for i in range(n):
    if dist[i]*2 == D and dist[i] + dt[i] == dist[t]:
        ans -= ((num[i]*nt[i]%MOD)**2)%MOD

#print(ans,"remove-pt")

for a,b,c in edges:
    da = dist[a]
    db = dist[b]
    if da > db:
        a,b = b,a
        da,db = db,da
    if da*2 < D and db*2 > D and dist[a] + dt[b] + c == dist[t]:
        ans -= ((num[a]*nt[b]%MOD)**2)%MOD

print((ans%MOD))


Solve in Python:
We have a list of bus routes. Each routes[i] is a bus route that the i-th bus repeats forever. For example if routes[0] = [1, 5, 7], this means that the first bus (0-th indexed) travels in the sequence 1->5->7->1->5->7->1->... forever.
We start at bus stop S (initially not on a bus), and we want to go to bus stop T. Travelling by buses only, what is the least number of buses we must take to reach our destination? Return -1 if it is not possible.
Example:
Input:
routes = [[1, 2, 7], [3, 6, 7]]
S = 1
T = 6
Output: 2
Explanation:
The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.

Constraints:

1 <= routes.length <= 500.
1 <= routes[i].length <= 10^5.
0 <= routes[i][j] < 10 ^ 6.

class Solution:
    def numBusesToDestination(self, routes: List[List[int]], S: int, T: int) -> int:
        graph = collections.defaultdict(list)
        if S == T: return 0
        nodeS, nodeT = set(), set()
        for i in range(len(routes)):
            if S in routes[i]: nodeS.add(i)
            if T in routes[i]: nodeT.add(i)
            if i < len(routes) - 1:
                for j in range(1, len(routes)):
                    if set(routes[i]) & set(routes[j]):
                        graph[i].append(j)
                        graph[j].append(i)

        # print(graph)
        if nodeS & nodeT: return 1
        if not nodeS or not nodeT: return -1

        queue, visited = collections.deque(), set()
        for s in nodeS:
            queue.append((s, 1))

        while queue:
            # print(queue)
            node, step = queue.popleft()
            if node in nodeT: return step
            for nbr in graph[node]:
                if nbr not in visited:
                    queue.append((nbr, step + 1))
                    visited.add(nbr)

        return -1


Solve in Python:
We have a list of points on the plane.  Find the K closest points to the origin (0, 0).
(Here, the distance between two points on a plane is the Euclidean distance.)
You may return the answer in any order.  The answer is guaranteed to be unique (except for the order that it is in.)

Example 1:
Input: points = [[1,3],[-2,2]], K = 1
Output: [[-2,2]]
Explanation:
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]].

Example 2:
Input: points = [[3,3],[5,-1],[-2,4]], K = 2
Output: [[3,3],[-2,4]]
(The answer [[-2,4],[3,3]] would also be accepted.)

Note:

1 <= K <= points.length <= 10000
-10000 < points[i][0] < 10000
-10000 < points[i][1] < 10000

class Solution:
    def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
        from queue import PriorityQueue as pq
        distance_points = [(-1 * ((x**2 + y**2) ** .5), [x,y]) for x,y in points]
        q = pq()
        for item in distance_points:
            if q.qsize() < k:
                q.put(item)
            else:
                distance, _ = item
                popped = q.get()
                popped_distance, _ = popped
                if distance > popped_distance:
                    q.put(item)
                else:
                    q.put(popped)
        return [q.get()[1] for _ in range(k)]


Solve in Python:
We have a matrix of integers with m rows and n columns.

We want to calculate the total sum for the matrix:

As you can see, the name "alternating sum" of the title is due to the sign of the terms that changes from one term to its contiguous one and so on.

Let's see an example:
```
matrix = [[1, 2, 3], [-3, -2, 1], [3, - 1, 2]]

total_sum = (1 - 2 + 3) + [-(-3) + (-2) - 1] + [3 - (-1) + 2] = 2 + 0 + 6 = 8
```
You may be given matrixes with their dimensions between these values:```10 < m < 300``` and ```10 < n < 300```.

More example cases in the Example Test Cases.
Enjoy it!!

e,score_matrix=enumerate,lambda m:sum(c*(-1)**(i+j)for i,l in e(m)for j,c in e(l))


Solve in Python:
We have a permutation of the integers from 1 through N, p_1, p_2, .., p_N.
We also have M pairs of two integers between 1 and N (inclusive), represented as (x_1,y_1), (x_2,y_2), .., (x_M,y_M).
AtCoDeer the deer is going to perform the following operation on p as many times as desired so that the number of i (1 ≤ i ≤ N) such that p_i = i is maximized:
 - Choose j such that 1 ≤ j ≤ M, and swap p_{x_j} and p_{y_j}.
Find the maximum possible number of i such that p_i = i after operations.

-----Constraints-----
 - 2 ≤ N ≤ 10^5
 - 1 ≤ M ≤ 10^5
 - p is a permutation of integers from 1 through N.
 - 1 ≤ x_j,y_j ≤ N
 - x_j ≠ y_j
 - If i ≠ j, \{x_i,y_i\} ≠ \{x_j,y_j\}.
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N M
p_1 p_2 .. p_N
x_1 y_1
x_2 y_2
:
x_M y_M

-----Output-----
Print the maximum possible number of i such that p_i = i after operations.

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

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

If we perform the operation by choosing j=1, p becomes 1 3 5 4 2, which is optimal, so the answer is 2.

import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
# def LF(): return [float(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

# Union-Find -- START --
class UnionFind():
  def __init__(self,sz):
    self.sz=sz
    self.data=[-1]*sz
    self.amount=[0]*sz

  def unite(self,x,y):
    x=self.find(x)
    y=self.find(y)
    if x==y:
      return False
    self.amount[x]+=self.amount[y]
    self.amount[y]+=self.amount[x]
    if self.data[x]>self.data[y]:
      x,y=y,x
    self.data[x]+=self.data[y]
    self.data[y]=x
    return True

  def find(self,k):
    if self.data[k]<0:
      return k
    self.data[k]=self.find(self.data[k])
    return self.data[k]

  def size(self,k):
    return -self.data[self.find(k)]

  def set_amount(self,k,k_amount):
    self.amount[k]=k_amount

  def get_amount(self,k):
    return self.amount[k]
# Union-Find --- END ---

def main():
  n,k=LI()
  l=LI()
  d={}
  uf=UnionFind(n)
  for i,x in enumerate(l):
    x-=1
    d[i]=x

  for _ in range(k):
    a,b=LI()
    uf.unite(a-1,b-1)

  ans=0
  for x in l:
    x-=1
    if uf.find(x)==uf.find(d[x]):
      ans+=1

  return ans

# main()
print((main()))


Solve in Python:
We have a sandglass consisting of two bulbs, bulb A and bulb B. These bulbs contain some amount of sand.
When we put the sandglass, either bulb A or B lies on top of the other and becomes the upper bulb. The other bulb becomes the lower bulb.
The sand drops from the upper bulb to the lower bulb at a rate of 1 gram per second.
When the upper bulb no longer contains any sand, nothing happens.
Initially at time 0, bulb A is the upper bulb and contains a grams of sand; bulb B contains X-a grams of sand (for a total of X grams).
We will turn over the sandglass at time r_1,r_2,..,r_K. Assume that this is an instantaneous action and takes no time. Here, time t refer to the time t seconds after time 0.
You are given Q queries.
Each query is in the form of (t_i,a_i).
For each query, assume that a=a_i and find the amount of sand that would be contained in bulb A at time t_i.

-----Constraints-----
 - 1≤X≤10^9
 - 1≤K≤10^5
 - 1≤r_1<r_2< .. <r_K≤10^9
 - 1≤Q≤10^5
 - 0≤t_1<t_2< .. <t_Q≤10^9
 - 0≤a_i≤X (1≤i≤Q)
 - All input values are integers.

-----Input-----
The input is given from Standard Input in the following format:
X
K
r_1 r_2 .. r_K
Q
t_1 a_1
t_2 a_2
:
t_Q a_Q

-----Output-----
For each query, print the answer in its own line.

-----Sample Input-----
180
3
60 120 180
3
30 90
61 1
180 180

-----Sample Output-----
60
1
120

In the first query, 30 out of the initial 90 grams of sand will drop from bulb A, resulting in 60 grams.
In the second query, the initial 1 gram of sand will drop from bulb A, and nothing will happen for the next 59 seconds. Then, we will turn over the sandglass, and 1 second after this, bulb A contains 1 gram of sand at the time in question.

from bisect import bisect
X=int(input())
K=int(input())
rs=[0]
for r in input().split():
  rs.append(int(r))
A=[[(0,0),(X,X)]]
min_sup=0
max_inf=X
pre_r=0
for i,r in enumerate(rs[1:]):
  d=r-pre_r
  pre_r=r
  m,M=A[-1][0][0],A[-1][1][0]
  if i%2==0:
    if m-d>=0:
      new_m=m-d
    else:
      new_m=0
      min_sup=min_sup+d-m
    if M-d>0:
      new_M=M-d
    else:
      new_M=0
      max_inf=0
  else:
    if M+d<=X:
      new_M=M+d
    else:
      new_M=X
      max_inf=max_inf-(d-(X-M))
    if m+d<X:
      new_m=m+d
    else:
      new_m=X
      min_sup=X
  if new_m==new_M:
    min_sup=X
    max_inf=0
  A.append([(new_m,min_sup),(new_M,max_inf)])
Q=int(input())
for q in range(Q):
  t,a=list(map(int,input().split()))
  r_num=bisect(rs,t)-1
  m,min_sup=A[r_num][0]
  M,max_inf=A[r_num][1]
  r=rs[r_num]
  if r_num%2==0:
    if a<=min_sup:
      print((max(m-(t-r),0)))
    elif min_sup<a<max_inf:
      print((max(m+(a-min_sup)-(t-r),0)))
    else:
      print((max(M-(t-r),0)))
  else:
    if a<=min_sup:
      print((min(m+(t-r),X)))
    elif min_sup<a<max_inf:
      print((min(m+(a-min_sup)+(t-r),X)))
    else:
      print((min(M+(t-r),X)))


Solve in Python:
We have a sequence A of N non-negative integers.
Compute the sum of \prod _{i = 1} ^N \dbinom{B_i}{A_i} over all sequences B of N non-negative integers whose sum is at most M, and print it modulo (10^9 + 7).
Here, \dbinom{B_i}{A_i}, the binomial coefficient, denotes the number of ways to choose A_i objects from B_i objects, and is 0 when B_i < A_i.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq N \leq 2000
 - 1 \leq M \leq 10^9
 - 0 \leq A_i \leq 2000

-----Input-----
Input is given from Standard Input in the following format:
N M
A_1 A_2 \ldots A_N

-----Output-----
Print the sum of \prod _{i = 1} ^N \dbinom{B_i}{A_i}, modulo (10^9 + 7).

-----Sample Input-----
3 5
1 2 1

-----Sample Output-----
8

There are four sequences B such that \prod _{i = 1} ^N \dbinom{B_i}{A_i} is at least 1:
 - B = \{1, 2, 1\}, where \prod _{i = 1} ^N \dbinom{B_i}{A_i} = \dbinom{1}{1} \times \dbinom{2}{2} \times \dbinom{1}{1} = 1;
 - B = \{2, 2, 1\}, where \prod _{i = 1} ^N \dbinom{B_i}{A_i} = \dbinom{2}{1} \times \dbinom{2}{2} \times \dbinom{1}{1} = 2;
 - B = \{1, 3, 1\}, where \prod _{i = 1} ^N \dbinom{B_i}{A_i} = \dbinom{1}{1} \times \dbinom{3}{2} \times \dbinom{1}{1} = 3;
 - B = \{1, 2, 2\}, where \prod _{i = 1} ^N \dbinom{B_i}{A_i} = \dbinom{1}{1} \times \dbinom{2}{2} \times \dbinom{2}{1} = 2.
The sum of these is 1 + 2 + 3 + 2 = 8.

import sys

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline

def modInverse(a, p):
    return pow(a, p - 2, p)

def modBinomial(n, k, p):
    numerator = 1
    for i in range(k):
        numerator = (numerator * (n - i)) % p

    denominator = 1
    for i in range(1, k + 1):
        denominator = (denominator * i) % p

    return (numerator * modInverse(denominator, p)) % p

def main():
    N, M = [int(x) for x in input().split()]
    A = [int(x) for x in input().split()]

    MOD = 10 ** 9 + 7

    if sum(A) > M:
        print((0))
        return

    x = sum(A) + N + 1
    sa = (M - sum(A))

    nn = (x - 1 + sa)
    rr = sa

    print((modBinomial(nn, min(rr, nn - rr), MOD)))

def __starting_point():
    main()

__starting_point()


Solve in Python:
We have a sequence of books: the i-th book has thickness books[i][0] and height books[i][1].
We want to place these books in order onto bookcase shelves that have total width shelf_width.
We choose some of the books to place on this shelf (such that the sum of their thickness is <= shelf_width), then build another level of shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down.  We repeat this process until there are no more books to place.
Note again that at each step of the above process, the order of the books we place is the same order as the given sequence of books.  For example, if we have an ordered list of 5 books, we might place the first and second book onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the last shelf.
Return the minimum possible height that the total bookshelf can be after placing shelves in this manner.

Example 1:

Input: books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelf_width = 4
Output: 6
Explanation:
The sum of the heights of the 3 shelves are 1 + 3 + 2 = 6.
Notice that book number 2 does not have to be on the first shelf.

Constraints:

1 <= books.length <= 1000
1 <= books[i][0] <= shelf_width <= 1000
1 <= books[i][1] <= 1000

def go_bf(i, books, curr_width, ch, shelf_width):
    if i == len(books):
        return 0

    w,h = books[i][0], books[i][1]
    best_h = float(\"inf\")
    if curr_width + w <= shelf_width:
        # if we add higher then we pay, is smaller then it's for free
        diff = max(h - ch, 0)
        best_h = diff + go_bf(i+1, books, curr_width + w, ch, shelf_width)
    best_h = min(best_h, h + min(best_h, go_bf(i+1, books, w, h, shelf_width)))
    return best_h

def go_memo(i, books, curr_width, ch, shelf_width, memo):
    if i == len(books):
        return 0

    if memo[i][curr_width] == -1:
        w,h = books[i][0], books[i][1]
        best_h = float(\"inf\")
        if curr_width + w <= shelf_width:
            # if we add higher then we pay, is smaller then it's for free
            diff = max(h - ch, 0)
            best_h = diff + go_memo(i+1, books, curr_width + w, ch + diff, shelf_width, memo)
        best_h = min(best_h, h + min(best_h, go_memo(i+1, books, w, h, shelf_width, memo)))
        memo[i][curr_width] = best_h
    return memo[i][curr_width]

class Solution:
    def minHeightShelves(self, books: List[List[int]], shelf_width: int) -> int:
        memo = [[-1] * (shelf_width + 1) for _ in range(len(books))]
        return go_memo(0, books, 0, 0, shelf_width, memo)


Solve in Python:
We have a set of consecutive numbers from ```1``` to ```n```.
We want to count all the subsets that do not contain consecutive numbers.
E.g.

If our set ```S1``` is equal to ```[1,2,3,4,5]```
The subsets that fulfill these property are:
```
[1],[2],[3],[4],[5],[1,3],[1,4],[1,5],[2,4],[2,5],[3,5],[1,3,5]
```
A total of      ```12   ``` subsets.

From the set ```S2``` equals to```[1,2,3]```, it is obvious that we have only ```4``` subsets and are:
```
[1],[2],[3],[1,3]
```
Make a code that may give the amount of all these subsets for any integer       ```n >= 2       ```.

Features of the random tests:
```
number of tests = 100
10 <= n <= 120
```

def f(n):
    n=n+2
    a, b = 0, 1
    while n > 0:
        a, b = b, a + b
        n -= 1
    return a-1


Solve in Python:
We have a set of items: the i-th item has value values[i] and label labels[i].
Then, we choose a subset S of these items, such that:

|S| <= num_wanted
For every label L, the number of items in S with label L is <= use_limit.

Return the largest possible sum of the subset S.

Example 1:
Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1
Output: 9
Explanation: The subset chosen is the first, third, and fifth item.

Example 2:
Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2
Output: 12
Explanation: The subset chosen is the first, second, and third item.

Example 3:
Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1
Output: 16
Explanation: The subset chosen is the first and fourth item.

Example 4:
Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2
Output: 24
Explanation: The subset chosen is the first, second, and fourth item.

Note:

1 <= values.length == labels.length <= 20000
0 <= values[i], labels[i] <= 20000
1 <= num_wanted, use_limit <= values.length

class Solution:
    def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int:
        res = 0
        heap = [[-v, i] for v, i in zip(values, labels)]
        heapq.heapify(heap)
        counter = Counter()

        while heap and num_wanted:
            v, i = heapq.heappop(heap)
            if counter[i] == use_limit:
                continue

            counter[i] += 1
            res += -v
            num_wanted -= 1

        return res


Solve in Python:
We have a string S of lowercase letters, and an integer array shifts.
Call the shift of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a').
For example, shift('a') = 'b', shift('t') = 'u', and shift('z') = 'a'.
Now for each shifts[i] = x, we want to shift the first i+1 letters of S, x times.
Return the final string after all such shifts to S are applied.
Example 1:
Input: S = "abc", shifts = [3,5,9]
Output: "rpl"
Explanation:
We start with "abc".
After shifting the first 1 letters of S by 3, we have "dbc".
After shifting the first 2 letters of S by 5, we have "igc".
After shifting the first 3 letters of S by 9, we have "rpl", the answer.

Note:

1 <= S.length = shifts.length <= 20000
0 <= shifts[i] <= 10 ^ 9

class Solution:
    def shiftingLetters(self, S: str, shifts: List[int]) -> str:
        add=0
        arr=list(S)
        i=len(S)-1
        while i>=0:
            add+=shifts[i]
            arr[i] = chr((((ord(arr[i]) - 97) + add) % 26) + 97)
            i-=1
        return ''.join(arr)


Solve in Python:
We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 10^9 + 7.

The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string.

-----Input-----

The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 10^6.

-----Output-----

Print the minimum number of steps modulo 10^9 + 7.

-----Examples-----
Input
ab

Output
1

Input
aab

Output
3

-----Note-----

The first example: "ab"  →  "bba".

The second example: "aab"  →  "abba"  →  "bbaba"  →  "bbbbaa".

import sys
#sys.stdin=open("data.txt")
input=sys.stdin.readline

# so the ending sequence is b...ba...a

# find length of ending sequence

extra=0
need=0
for ch in input().strip():
    if ch=='a':
        need=(need*2+1)%1000000007
    else:
        extra=(extra+need)%1000000007

print(extra)


Solve in Python:
We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i.
Vertex i has an integer a_i written on it.
For every integer k from 1 through N, solve the following problem:
 - We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k, in the order they appear. Find the length of the longest increasing subsequence of this sequence.
Here, the longest increasing subsequence of a sequence A of length L is the subsequence A_{i_1} , A_{i_2} , ... , A_{i_M} with the greatest possible value of M such that 1 \leq i_1 < i_2 < ... < i_M \leq L and A_{i_1} < A_{i_2} < ... < A_{i_M}.

-----Constraints-----
 - 2 \leq N \leq 2 \times 10^5
 - 1 \leq a_i \leq 10^9
 - 1 \leq u_i , v_i \leq N
 - u_i \neq v_i
 - The given graph is a tree.
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}

-----Output-----
Print N lines. The k-th line, print the length of the longest increasing subsequence of the sequence obtained from the shortest path from Vertex 1 to Vertex k.

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

-----Sample Output-----
1
2
3
3
4
4
5
2
2
3

For example, the sequence A obtained from the shortest path from Vertex 1 to Vertex 5 is 1,2,5,3,4. Its longest increasing subsequence is A_1, A_2, A_4, A_5, with the length of 4.

# 写経
# https://atcoder.jp/contests/abc165/submissions/12655073
from bisect import bisect_left, bisect_right
import sys

def resolve():
    input = sys.stdin.readline
    sys.setrecursionlimit(10**9)
    INF = float('inf')
    N = int(input())
    As = list(map(int, input().split()))
    adjL = [[] for _ in range(N)]
    for _ in range(N-1):
        u, v = map(int, input().split())
        u, v = u-1, v-1
        adjL[u].append(v)
        adjL[v].append(u)

    dp = [-INF]
    anss = [0] * N
    def dfs(vNow, vPar):
        A = As[vNow]
        if dp[-1] < A:
            dp.append(A)
            tp = 0
        else:
            i = bisect_left(dp, A)
            tp = 1
            iOld, AOld, = i, dp[i]
            dp[i] = A
        anss[vNow] = len(dp) - 1

        for v2 in adjL[vNow]:
            if v2 == vPar: continue
            dfs(v2, vNow)

        if tp == 0:
            dp.pop()
        else:
            dp[iOld] = AOld

    dfs(0, -1)

    print('\n'.join(map(str, anss)))
resolve()


Solve in Python:
We have a tree with N vertices. The vertices are numbered 1, 2, ..., N. The i-th (1 ≦ i ≦ N - 1) edge connects the two vertices A_i and B_i.
Takahashi wrote integers into K of the vertices. Specifically, for each 1 ≦ j ≦ K, he wrote the integer P_j into vertex V_j. The remaining vertices are left empty. After that, he got tired and fell asleep.
Then, Aoki appeared. He is trying to surprise Takahashi by writing integers into all empty vertices so that the following condition is satisfied:
 - Condition: For any two vertices directly connected by an edge, the integers written into these vertices differ by exactly 1.
Determine if it is possible to write integers into all empty vertices so that the condition is satisfied. If the answer is positive, find one specific way to satisfy the condition.

-----Constraints-----
 - 1 ≦ N ≦ 10^5
 - 1 ≦ K ≦ N
 - 1 ≦ A_i, B_i ≦ N (1 ≦ i ≦ N - 1)
 - 1 ≦ V_j ≦ N (1 ≦ j ≦ K) (21:18, a mistake in this constraint was corrected)
 - 0 ≦ P_j ≦ 10^5 (1 ≦ j ≦ K)
 - The given graph is a tree.
 - All v_j are distinct.

-----Input-----
The input is given from Standard Input in the following format:
N
A_1 B_1
A_2 B_2
:
A_{N-1} B_{N-1}
K
V_1 P_1
V_2 P_2
:
V_K P_K

-----Output-----
If it is possible to write integers into all empty vertices so that the condition is satisfied, print Yes. Otherwise, print No.
If it is possible to satisfy the condition, print N lines in addition. The v-th (1 ≦ v ≦ N) of these N lines should contain the integer that should be written into vertex v. If there are multiple ways to satisfy the condition, any of those is accepted.

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

-----Sample Output-----
Yes
5
6
6
5
7

The figure below shows the tree when Takahashi fell asleep. For each vertex, the integer written beside it represents the index of the vertex, and the integer written into the vertex is the integer written by Takahashi.
Aoki can, for example, satisfy the condition by writing integers into the remaining vertices as follows:
This corresponds to Sample...

import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)

N = int(input())
G = [[] for _ in range(N+1)]
for _ in range(N-1):
    A, B = map(int, input().split())
    G[A].append(B)
    G[B].append(A)
K = int(input())
num = [-1] * (N+1)
for _ in range(K):
    V, P = map(int, input().split())
    num[V] = P

# check parity
stack = [1]
depth = [-1] * (N+1)
depth[1] = 0
while stack:
    v = stack.pop()
    for c in G[v]:
        if depth[c] == -1:
            depth[c] = depth[v] + 1
            stack.append(c)
parity = [set(), set()]
for i in range(1, N+1):
    if num[i] != -1:
        parity[depth[i] % 2].add(num[i] % 2)
if len(parity[0]) == 2 or len(parity[1]) == 2:
    print('No')
    return

INF = 10**9
lb = [-INF] * (N+1)
ub = [INF] * (N+1)

def dfs1(v, p):
    for c in G[v]:
        if c == p:
            continue
        dfs1(c, v)
        lb[v] = max(lb[v], lb[c] - 1)
        ub[v] = min(ub[v], ub[c] + 1)
    if num[v] != -1:
        lb[v] = ub[v] = num[v]

dfs1(1, 0)

def dfs2(v, p):
    for c in G[v]:
        if c == p:
            continue
    for c in G[v]:
        if c == p:
            continue
        lb[c] = max(lb[c], lb[v] - 1)
        ub[c] = min(ub[c], ub[v] + 1)
        dfs2(c, v)

dfs2(1, 0)

for i in range(1, N+1):
    if lb[i] > ub[i]:
        print('No')
        return

print('Yes')

def dfs3(v, p):
    for c in G[v]:
        if c == p:
            continue
        if lb[c] <= num[v] - 1:
            num[c] = num[v] - 1
        else:
            num[c] = num[v] + 1
        dfs3(c, v)

num[1] = lb[1]
dfs3(1, 0)

print(*num[1:], sep='\n')


Solve in Python:
We have a two dimensional matrix A where each value is 0 or 1.
A move consists of choosing any row or column, and toggling each value in that row or column: changing all 0s to 1s, and all 1s to 0s.
After making any number of moves, every row of this matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers.
Return the highest possible score.

Example 1:
Input: [[0,0,1,1],[1,0,1,0],[1,1,0,0]]
Output: 39
Explanation:
Toggled to [[1,1,1,1],[1,0,0,1],[1,1,1,1]].
0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39

Note:

1 <= A.length <= 20
1 <= A[0].length <= 20
A[i][j] is 0 or 1.

class Solution:
    def matrixScore(self, A: List[List[int]]) -> int:
        M, N = len(A), len(A[0])
        ans = (1<<N-1)*M
        for j in range(1, N):
            count = sum(A[i][j]==A[i][0] for i in range(M))
            ans += max(count, M-count)<<N-j-1
        return ans


Solve in Python:
We have an array A of non-negative integers.
For every (contiguous) subarray B = [A[i], A[i+1], ..., A[j]] (with i <= j), we take the bitwise OR of all the elements in B, obtaining a result A[i] | A[i+1] | ... | A[j].
Return the number of possible results.  (Results that occur more than once are only counted once in the final answer.)

Example 1:
Input: [0]
Output: 1
Explanation:
There is only one possible result: 0.

Example 2:
Input: [1,1,2]
Output: 3
Explanation:
The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2].
These yield the results 1, 1, 2, 1, 3, 3.
There are 3 unique values, so the answer is 3.

Example 3:
Input: [1,2,4]
Output: 6
Explanation:
The possible results are 1, 2, 3, 4, 6, and 7.

Note:

1 <= A.length <= 50000
0 <= A[i] <= 10^9

class Solution:
    def subarrayBitwiseORs(self, A: List[int]) -> int:
        s, ans = set(), set()
        for a in A:
            s = {a} | {a | b for b in s}
            ans |= s
        return len(ans)


Solve in Python:
We have an array of integers, nums, and an array of requests where requests[i] = [starti, endi]. The ith request asks for the sum of nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi]. Both starti and endi are 0-indexed.
Return the maximum total sum of all requests among all permutations of nums.
Since the answer may be too large, return it modulo 109 + 7.

Example 1:
Input: nums = [1,2,3,4,5], requests = [[1,3],[0,1]]
Output: 19
Explanation: One permutation of nums is [2,1,3,4,5] with the following result:
requests[0] -> nums[1] + nums[2] + nums[3] = 1 + 3 + 4 = 8
requests[1] -> nums[0] + nums[1] = 2 + 1 = 3
Total sum: 8 + 3 = 11.
A permutation with a higher total sum is [3,5,4,2,1] with the following result:
requests[0] -> nums[1] + nums[2] + nums[3] = 5 + 4 + 2 = 11
requests[1] -> nums[0] + nums[1] = 3 + 5  = 8
Total sum: 11 + 8 = 19, which is the best that you can do.

Example 2:
Input: nums = [1,2,3,4,5,6], requests = [[0,1]]
Output: 11
Explanation: A permutation with the max total sum is [6,5,4,3,2,1] with request sums [11].
Example 3:
Input: nums = [1,2,3,4,5,10], requests = [[0,2],[1,3],[1,1]]
Output: 47
Explanation: A permutation with the max total sum is [4,10,5,3,2,1] with request sums [19,18,10].

Constraints:

n == nums.length
1 <= n <= 105
0 <= nums[i] <= 105
1 <= requests.length <= 105
requests[i].length == 2
0 <= starti <= endi < n

class Solution:
    def maxSumRangeQuery(self, nums: List[int], requests: List[List[int]]) -> int:

        frequency = [0 for i in range(len(nums))]

        for u, v in requests:

            frequency[u] += 1
            if v + 1 < len(nums): frequency[v + 1] -= 1

        for i in range(1, len(frequency)):

            frequency[i] += frequency[i - 1]

        frequency.sort()
        nums.sort()

        Sum = 0
        while nums:

            Sum += nums.pop()*frequency.pop()

        return Sum%(10**9 + 7)


Solve in Python:
We have an array of unique elements. A special kind of permutation is the one that has all of its elements in a different position than the original.

Let's see how many of these permutations may be generated from an array of four elements. We put the original array with square brackets and the wanted permutations with parentheses.
```
arr = [1, 2, 3, 4]
      (2, 1, 4, 3)
      (2, 3, 4, 1)
      (2, 4, 1, 3)
      (3, 1, 4, 2)
      (3, 4, 1, 2)
      (3, 4, 2, 1)
      (4, 1, 2, 3)
      (4, 3, 1, 2)
      (4, 3, 2, 1)
      _____________
A total of 9 permutations with all their elements in different positions than arr
```

The task for this kata would be to create a code to count all these permutations for an array of certain length.

Features of the random tests:
```
l = length of the array
10 ≤ l ≤ 5000
```

See the example tests.

Enjoy it!

from itertools import islice

def A000166():
    # https://oeis.org/A000166
    a, b, n = 1, 0, 1
    while True:
        yield a
        a, b = b, n * (a + b)
        n += 1

all_permuted = dict(enumerate(islice(A000166(), 5000))).get


Solve in Python:
We have an array with string digits that occurrs more than once, for example, ```arr = ['1', '2', '2', '2', '3', '3']```. How many different string numbers can be generated taking the 6 elements at a time?

We present the list of them below in an unsorted way:
```
['223213', '312322', '223312', '222133', '312223', '223321', '223231', '132223', '132322', '223132', '322321', '322312', '231322', '222313', '221233', '213322', '122323', '321322', '221332', '133222', '123232', '323221', '222331', '132232', '321232', '212323', '232213', '232132', '331222', '232312', '332212', '213223', '123322', '322231', '321223', '231232', '233221', '231223', '213232', '312232', '233122', '322132', '223123', '322123', '232231', '323122', '323212', '122233', '212233', '123223', '332221', '122332', '221323', '332122', '232123', '212332', '232321', '322213', '233212', '313222']
```
There are ```60``` different numbers and ```122233``` is the lowest one and ```332221``` the highest of all of them.

Given an array, ```arr```, with string digits (from '0' to '9'), you should give the exact amount of different numbers that may be generated with the lowest and highest value but both converted into integer values, using all the digits given in the array for each generated string number.

The function will be called as ```proc_arr()```.
```python
proc_arr(['1', '2', '2', '3', '2', '3']) == [60, 122233, 332221]
```

If the digit '0' is present in the given array will produce string numbers with leading zeroes, that will not be not taken in account when they are converted to integers.
```python
proc_arr(['1','2','3','0','5','1','1','3']) == [3360, 1112335, 53321110]
```
You will never receive an array with only one digit repeated n times.

Features of the random tests:
```
Low performance tests:
Number of tests: 100
Arrays of length between 6 and 10

Higher performance tests:
Number of tests: 100
Arrays of length between 30 and 100
```

from collections import Counter
from math import factorial
from operator import mul
from functools import reduce

def proc_arr(arr):
    c = Counter(arr)
    xs = sorted(arr)
    n = factorial(len(arr)) // reduce(mul, list(map(factorial, list(c.values()))))
    return [n, int(''.join(xs)), int(''.join(xs[::-1]))]


Solve in Python:
We have an integer array with unique elements and we want to do the permutations that have an element fixed, in other words, these permutations should have a certain element at the same position than the original.

These permutations will be called: **permutations with one fixed point**.

Let's see an example with an array of four elements and we want the permutations that have a coincidence **only at  index 0**, so these permutations are (the permutations between parenthesis):
```
arr = [1, 2, 3, 4]
      (1, 3, 4, 2)
      (1, 4, 2, 3)
Two permutations matching with arr only at index 0
```

Let's see the permutations of the same array with only one coincidence at index **1**:
```
arr = [1, 2, 3, 4]
      (3, 2, 4, 1)
      (4, 2, 1, 3)
Two permutations matching with arr only at index 1
```
Once again, let's see the permutations of the same array with only one coincidence at index **2**:
```
arr = [1, 2, 3, 4]
      (2, 4, 3, 1)
      (4, 1, 3, 2)
Two permutations matching with arr only at index 2
```
Finally, let's see the permutations of the same array with only one coincidence at index **3**:
```
arr = [1, 2, 3, 4]
      (2, 3, 1, 4)
      (3, 1, 2, 4)
Two permutations matching with arr only at index 3
```
For this array given above (arr) :

- We conclude that we have 8 permutations with one fixed point (two at each index of arr).

- We may do the same development for our array, `arr`, with two fixed points and we will get `6` permutations.

- There are no permutations with coincidences only at three indexes.

- It's good to know that the amount of permutations with no coincidences at all are `9`. See the kata Shuffle It Up!!

In general:

- When the amount of fixed points is equal to the array length, there is only one permutation, the original array.

- When the amount of fixed points surpasses the length of the array, obvously, there are no permutations at all.

Create a function that receives the length of the array and the number of fixed points and may output the total amount of permutations...

subfactorial, factorial = [1, 0], [1]
for n in range(1, 10 ** 4):
    subfactorial.append(n * (subfactorial[-1] + subfactorial[-2]))
    factorial.append(n * factorial[-1])

def fixed_points_perms(n, k):
    return factorial[n] // factorial[n-k] // factorial[k] * subfactorial[n-k]


Solve in Python:
We have jobs: difficulty[i] is the difficulty of the ith job, and profit[i] is the profit of the ith job.
Now we have some workers. worker[i] is the ability of the ith worker, which means that this worker can only complete a job with difficulty at most worker[i].
Every worker can be assigned at most one job, but one job can be completed multiple times.
For example, if 3 people attempt the same job that pays $1, then the total profit will be $3.  If a worker cannot complete any job, his profit is $0.
What is the most profit we can make?
Example 1:
Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
Output: 100
Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get profit of [20,20,30,30] seperately.
Notes:

1 <= difficulty.length = profit.length <= 10000
1 <= worker.length <= 10000
difficulty[i], profit[i], worker[i]  are in range [1, 10^5]

class Solution:
    def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:
        jobs = sorted(zip(difficulty, profit))
        res = i = best = 0
        for ability in sorted(worker):
            while i < len(jobs) and ability >= jobs[i][0]:
                best = max(jobs[i][1], best)
                i += 1
            res += best
        return res


Solve in Python:
We have n chips, where the position of the ith chip is position[i].
We need to move all the chips to the same position. In one step, we can change the position of the ith chip from position[i] to:

position[i] + 2 or position[i] - 2 with cost = 0.
position[i] + 1 or position[i] - 1 with cost = 1.

Return the minimum cost needed to move all the chips to the same position.

Example 1:

Input: position = [1,2,3]
Output: 1
Explanation: First step: Move the chip at position 3 to position 1 with cost = 0.
Second step: Move the chip at position 2 to position 1 with cost = 1.
Total cost is 1.

Example 2:

Input: position = [2,2,2,3,3]
Output: 2
Explanation: We can move the two chips at poistion 3 to position 2. Each move has cost = 1. The total cost = 2.

Example 3:
Input: position = [1,1000000000]
Output: 1

Constraints:

1 <= position.length <= 100
1 <= position[i] <= 10^9

class Solution:
    def minCostToMoveChips(self, position: List[int]) -> int:
        oddc = evenc = 0
        for i in position:
            if i%2 == 0:
                evenc+=1
            else:
                oddc+=1
        return oddc if oddc <= evenc else evenc


Solve in Python:
We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i].
You're given the startTime , endTime and profit arrays, you need to output the maximum profit you can take such that there are no 2 jobs in the subset with overlapping time range.
If you choose a job that ends at time X you will be able to start another job that starts at time X.

Example 1:

Input: startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]
Output: 120
Explanation: The subset chosen is the first and fourth job.
Time range [1-3]+[3-6] , we get profit of 120 = 50 + 70.

Example 2:

Input: startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60]
Output: 150
Explanation: The subset chosen is the first, fourth and fifth job.
Profit obtained 150 = 20 + 70 + 60.

Example 3:

Input: startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4]
Output: 6

Constraints:

1 <= startTime.length == endTime.length == profit.length <= 5 * 10^4
1 <= startTime[i] < endTime[i] <= 10^9
1 <= profit[i] <= 10^4

class Solution:
    def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:
        line=list(set(startTime)|set(endTime))
        line.sort()
        dp=dict()
        d=dict()
        v=dict()
        for i in range(len(endTime)):
            if endTime[i] not in d:
                d[endTime[i]]=[]
            d[endTime[i]].append(startTime[i])
            v[(startTime[i],endTime[i])]=profit[i]
        m=0
        for n in line:
            if n not in d:
                dp[n]=m
            else:
                dp[n]=max([m]+[dp[i]+v[(i,n)]  for i in d[n]])
                m=max(dp[n],m)
        return dp[line[-1]]


Solve in Python:
We have the first value of a certain sequence, we will name it ```initVal```.
We define  pattern list, ```patternL```, an array that has the differences between contiguous terms of the sequence.
``` E.g: patternL = [k1, k2, k3, k4]```

The terms of the sequence will be such values that:
```python
term1 = initVal
term2 - term1 = k1
term3 - term2 = k2
term4 - term3 = k3
term5 - term4 = k4
term6 - term5 = k1
term7 - term6 = k2
term8 - term7 = k3
term9 - term8 = k4
....  - ..... = ...
....  - ..... = ...
 ```
So the values of the differences between contiguous terms are cyclical and are  repeated as the differences values of the pattern list stablishes.

Let's see an example with numbers:
```python
initVal = 10
patternL = [2, 1, 3]
term1 = 10
term2 = 12
term3 = 13
term4 = 16
term5 = 18
term6 = 19
term7 = 22  # and so on...
```
We can easily obtain the next terms of the sequence following the values in the pattern list.
We see that the sixth term of the sequence, ```19```, has the sum of its digits ```10```.

Make a function ```sumDig_nthTerm()```, that receives three arguments in this order

 ```sumDig_nthTerm(initVal, patternL, nthTerm(ordinal number of the term in the sequence)) ```

This function will output the sum of the digits of the n-th term of the sequence.

Let's see some cases for this function:
```python
sumDig_nthTerm(10, [2, 1, 3], 6) -----> 10 # because the sixth term is 19 sum of Dig = 1 + 9 = 10. The sequence up to the sixth-Term is: 10, 12, 13, 16, 18, 19

sumDig_nthTerm(10, [1, 2, 3], 15) ----> 10 # 37 is the 15-th term, and 3 + 7 = 10
```
Enjoy it and happy coding!!

def sumDig_nthTerm(initVal, patternL, nthTerm):
    n=initVal
    for i in range(nthTerm-1):
        n+=patternL[i%len(patternL)]
    return sum(int(d) for d in str(n))


Solve in Python:
We have the following recursive function:

The 15-th term; ```f(14)``` is the first term in having more that 100 digits.

In fact,
```
f(14) = 2596253046576879973769082409566059879570061514363339324718953988724415850732046186170181072783243503881471037546575506836249417271830960970629933033088

It has 151 digits.
```
Make the function ```something_acci()```, that receives ```num_dig``` (number of digits of the value) as unique argument.

```something_acci()``` will output a tuple/array with the ordinal number in the sequence for the least value in having equal or more than the given number of digits.

Let's see some cases:
```python
something_acci(20) == (12, 25)
# f(11) = 1422313222839141753028416

something_acci(100) == (15, 151)
```
The number of digits given will be always more than 5. ```num_dig > 5```.

Happy coding!!!

And the name for this kata? You have three words of the same meaning in Asian Languages.

from functools import reduce
from operator import mul
def something_acci(n):
    li = [1, 1, 2, 2, 3, 3]
    while True:
        li.append(reduce(mul, li[-3:]) - reduce(mul, li[-6:-3]))
        if len(str(li[-1])) >= n : return len(li),len(str(li[-1]))


Solve in Python:
We have the following sequence:
```python
f(0) = 0
f(1) = 1
f(2) = 1
f(3) = 2
f(4) = 4;
f(n) = f(n-1) + f(n-2) + f(n-3) + f(n-4) + f(n-5);
```

Your task is to give the number of total values for the odd terms of the sequence  up to the n-th term (included). (The number n (of n-th term) will be given as a positive integer)

The values 1 (one) is the only that is duplicated in the sequence and should be counted only once.

E.g.
```
count_odd_pentaFib(5) -----> 1 # because the terms up to 5 are: 0, 1, 1, 2, 4, 8 (only 1 is odd and counted once)
```
Other examples:
```
 count_odd_pentaFib(10) ------> 3 #because the odds terms are: [1, 1, 31, 61] (three different values)

count_odd_pentaFib(15) ------> 5 # beacause the odd terms are: [1, 1, 31, 61, 1793, 3525] (five different values)
```
Good luck !!

(Your code should be fast. Many moderate high values will be waiting to test it.)

from collections import deque
from itertools import islice, groupby

def odd_penta_fib():
    q = deque([0, 1, 1, 2, 4, 8], maxlen=6)
    while True:
        yield q[0]
        q.append(q[-1] * 2 - q[0])

def count_odd_pentaFib(n):
    return sum(1 for key, grp in groupby(islice(odd_penta_fib(), n+1)) if key % 2 == 1)


Solve in Python:
We have the integer `9457`.

We distribute its digits in two buckets having the following possible distributions (we put the generated numbers as strings and we add the corresponding formed integers for each partition):
```
- one bucket with one digit and the other with three digits
[['9'], ['4','5','7']] --> ['9','457'] --> 9 + 457 = 466
[['9','5','7'], ['4']] --> ['957','4'] --> 957 + 4 = 961
[['9','4','7'], ['5']] --> ['947','5'] --> 947 + 5 = 952
[['9','4','5'], ['7']] --> ['945','7'] --> 945 + 7 = 952

- two buckets with 2 digits each:
[['9','4'], ['5','7']] --> ['94','57'] --> 94 + 57 = 151
[['9','5'], ['4','7']] --> ['95','47'] --> 95 + 47 = 142
[['9','7'], ['4','5']] --> ['97','45'] --> 97 + 45 = 142
```

Now we distribute the digits of that integer in three buckets, and we do the same presentation as above:
```
one bucket of two digits and two buckets with one digit each:
[['9'], ['4'], ['5','7']] --> ['9','4','57'] --> 9 + 4 + 57 = 70
[['9','4'], ['5'], ['7']] --> ['94','5','7'] --> 94 + 5 + 7 = 106
[['9'], ['4', '5'], ['7']] --> ['9','45','7'] --> 9 + 45 + 7 = 61
[['9'], ['5'], ['4','7']] --> ['9','5','47'] --> 9 + 5 + 47 = 61
[['9','5'], ['4'], ['7']] --> ['95','4','7'] --> 95 + 4 + 7 = 106
[['9','7'], ['4'], ['5']] --> ['97','4','5'] --> 97 + 4 + 5 = 106
```
Finally we distribute the digits in the maximum possible amount of buckets for this integer, four buckets, with an unique distribution:
```
One digit in each bucket.
[['9'], ['4'], ['5'], ['7']] --> ['9','4','5','7'] --> 9 + 4 + 5 + 7 = 25
```
In the distribution we can observe the following aspects:

- the order of the buckets does not matter

- the order of the digits in each bucket matters; the available digits have the same order than in the original number.

- the amount of buckets varies from two up to the amount of digits

The function, `f =` `bucket_digit_distributions_total_sum`, gives for each integer, the result of the big sum of the total addition of generated numbers for each distribution of...

#def find(n,z):

#    s = [i for i in str(n)]
#    print (s)
#    k = []
#    for i in range(len(s)):
#        s_n = s[:i]+s[i+1:]
#        b = [s[i]]
#        k = [s[i]] + [s_n]
#        print (k)
#        for i in range(len(s_n)):
def subsets(collection):
    if len(collection) == 1:
        yield [collection]
        return

    first = collection[0]

    for smaller in subsets(collection[1:]):
        yield [first] + smaller
        for n, subset in enumerate(smaller):
            yield smaller[:n] + [first + subset]  + smaller[n+1:]

def bucket_digit_distributions_total_sum(n):
    return sum(sum(map(int, sub)) for sub in subsets(str(n))) - n

def find(n, z):
    f_nf = bucket_digit_distributions_total_sum(n) + z
    while 1:
        n += 1
        if bucket_digit_distributions_total_sum(n) > f_nf:
            return n


Solve in Python:
We have the number ```12385```. We want to know the value of the closest cube but higher than 12385. The answer will be ```13824```.

Now, another case. We have the number ```1245678```. We want to know the 5th power, closest and higher than that number. The value will be ```1419857```.

We need a function ```find_next_power``` ( ```findNextPower``` in JavaScript, CoffeeScript and Haskell), that receives two arguments, a value ```val```, and the exponent of the power,``` pow_```, and outputs the value that we want to find.

Let'see some cases:
```python
find_next_power(12385, 3) == 13824

find_next_power(1245678, 5) == 1419857
```
The value, ```val``` will be always a positive integer.

The power, ```pow_```, always higher than ```1```.

Happy coding!!

def find_next_power(val, power):

  return int((val ** (1.0 / power)) + 1) ** power


Solve in Python:
We have the numbers with different colours with the sequence: ['red', 'yellow', 'blue'].

That sequence colours the numbers in the following way:

 1   2   3    4    5   6  7   8   9   10   11  12   13 .....

We have got the following recursive function:

  ```
f(1) = 1
f(n) = f(n - 1) + n
```

Some terms of this sequence with their corresponding colour are:

```
term   value   colour
1        1     "red"
2        3     "blue"
3        6     "blue"
4       10     "red"
5       15     "blue"
6       21     "blue"
7       28     "red"
```

The three terms of the same colour "blue", higher than 3, are: `[6, 15, 21]`

We need a function `same_col_seq(), that may receive three arguments:

- `val`, an integer number
- `k`, an integer number
- `colour`, the name of one of the three colours(red, yellow or blue), as a string.

The function will output a sorted array with the smallest `k` terms, having the same marked colour, but higher than `val`.

Let's see some examples:

```python
same_col_seq(3, 3, 'blue') == [6, 15, 21]
same_col_seq(100, 4, 'red') == [136, 190, 253, 325]
```

The function may output an empty list if it does not find terms of the sequence with the wanted colour in the range [val, 2* k * val]

```python
same_col_seq(250, 6, 'yellow') == []
```

That means that the function did not find any "yellow" term in the range `[250, 3000]`

Tests will be with the following features:

* Nmber of tests: `100`
* `100 < val < 1000000`
* `3 < k < 20`

def same_col_seq(val, k, col):
    n_start = int(((1 + 8 * val)**0.5 - 1) / 2) + 1
    def f(n):
        return (1 + n) * n // 2
    def get_col(n):
        return 'red' if n % 3 == 1 else 'blue'
    return [f(n) for n in range(n_start, n_start + 62) if col==get_col(n)][:k]


Solve in Python:
We have three numbers: ```123489, 5, and 67```.
With these numbers we form the list from their digits in this order ```[1, 5, 6, 2, 7, 3, 4, 8, 9]```.  It shouldn't take you long to figure out what to do to achieve this ordering.

Furthermore, we want to put a limit to the number of terms of the above list.

Instead of having 9 numbers, we only want 7, so we discard the two last numbers.

So, our list will be reduced to ```[1, 5, 6, 2, 7, 3, 4]``` (base list)

We form all the possible arrays, from the list above, and we calculate, for each array, the addition of their respective digits.

See the table below: we will put only some of them
```
array for the list      sum (terms of arrays)
[1]                      1 # arrays with only one term (7 different arrays)
[5]                      5
[6]                      6
[2]                      2
[7]                      7
[3]                      3
[4]                      4

[1, 5]                   6 # arrays with two terms (42 different arrays)
[1, 6]                   7
[1, 2]                   3
[1, 7]                   8
[1, 3]                   4
[1, 4]                   5

.....                   ...
[1, 5, 6]               12 # arrays with three terms(210 different arrays)
[1, 5, 2]                8
[1, 5, 7]               13
[1, 5, 3]                9
........                ...
[1, 5, 6, 2]            14 # arrays with four terms(840 different arrays)
[1, 5, 6, 7]            19
[1, 5, 6, 3]            15
[1, 5, 6, 4]            16
............            ..
[1, 5, 6, 2, 7]         21 # arrays with five terms(2520 different arrays)
[1, 5, 6, 2, 3]         17
[1, 5, 6, 2, 4]         18
[1, 5, 6, 7, 2]         21
...............         ..
[1, 5, 6, 2, 7, 3]      24 # arrays with six terms(5040 different arrays)
[1, 5, 6, 2, 7, 4]      25
[1, 5, 6, 2, 3, 7]      24
[1, 5, 6, 2, 3, 4]      21
..................      ..
[1, 5, 6, 2, 7, 3, 4]   28 # arrays with seven terms(5040 different arrays)
[1, 5, 6, 2, 7, 4, 3]   28   # arrays of max length...

from math import e, factorial

def gta(limit, *nums):
    iternums, l, i, base= [(int(d) for d in str(n)) for n in nums], len(nums), 0, []
    while len(base) < limit:
        d, i = next(iternums[i % l], None), i+1
        if d is not None and d not in base:
            base.append(d)
    return (int(e * factorial(limit)) * (limit - 1) + 1) * sum(base) // limit


Solve in Python:
We have three stones at points (0, 0), (1,0), and (0,1) on a two-dimensional plane.
These three stones are said to form an L when they satisfy the following conditions:
 - Each of the stones is at integer coordinates.
 - Each of the stones is adjacent to another stone. (That is, for each stone, there is another stone whose distance from that stone is 1.)
 - The three stones do not lie on the same line.
Particularly, the initial arrangement of the stone - (0, 0), (1,0), and (0,1) - forms an L.
You can do the following operation any number of times: choose one of the stones and move it to any position. However, after each operation, the stones must form an L.
You want to do as few operations as possible to put stones at points (ax, ay), (bx, by), and (cx, cy). How many operations do you need to do this?
It is guaranteed that the desired arrangement of stones - (ax, ay), (bx, by), and (cx, cy) - forms an L. Under this condition, it is always possible to achieve the objective with a finite number of operations.
You will be given T cases of this problem. Solve each of them.

-----Notes-----
We assume that the three stones are indistinguishable. For example, the stone that is initially at point (0,0) may be at any of the points (ax, ay), (bx, by), and (cx, cy) in the end.

-----Constraints-----
 - 1 \leq T \leq 10^3
 - |ax|,|ay|,|bx|,|by|,|cx|,|cy| \leq 10^9
 - The desired arrangement of stones - (ax, ay), (bx, by), and (cx, cy) - forms an L.

-----Input-----
Input is given from Standard Input in the following format:
T
\text{case}_1
\vdots
\text{case}_T

Each case is in the following format:
ax ay bx by cx cy

-----Output-----
Print T values. The i-th value should be the minimum number of operations for \text{case}_i.

-----Sample Input-----
1
3 2 2 2 2 1

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

Let us use # to represent a stone.
You can move the stones to the specified positions with four operations, as follows:
....    ....    ....    ..#.    ..##
#... -> ##.. -> .##. -> .##. -> ..#.
##..    .#..    .#..    ....    ....

import sys
from collections import deque

T = int(input())
# 0 L
# 1 |-
# 2 -|
# 3 _|
def ku_state(p1, p2, p3):
    xb = min([p[0] for p in [p1, p2, p3]])
    yb = min([p[1] for p in [p1, p2, p3]])
    s = set([(p[0] - xb, p[1] - yb) for p in [p1, p2, p3]])
    if len(s) != 3 or max([x[0] for x in s]) != 1 or max([x[1] for x in s]) != 1:
        return None
    if (1, 1) not in s:
        return 0
    elif (1, 0) not in s:
        return 1
    elif (0, 0) not in s:
        return 2
    elif (0, 1) not in s:
        return 3
    else:
        return None

for _ in range(T):
    ax, ay, bx, by, cx, cy = list(map(int, input().split()))
    ps = [(ax, ay), (bx, by), (cx, cy)]
    ku = (ku_state(*ps))
    xb = min(ax, bx, cx)
    yb = min(ay, by, cy)
    xd = int(abs(xb + 0.5))
    yd = int(abs(yb + 0.5))
    if xb == 0 and yb == 0:
        print((int(ku != 0)))
        continue
    if ku == 0:
        ans = max(abs(xb), abs(yb)) * 2
        if xb == yb:
            ans += 1
    elif ku == 1:
        ans = max(abs(xb) * 2, 2 * yd + 1)
        ans = max(1, ans)
    elif ku == 2:
        if xb == 0 and yb == 0:
            ans = 1
        else:
            ans = max(xd, yd)*2+1
            if xb == yb:
                ans += 1
    elif ku == 3:
        ans = max(abs(yb) * 2, 2 * xd + 1)
        ans = max(1, ans)
    print(ans)


Solve in Python:
We have two consecutive integers k1 and k2, k2 = k1 + 1

We need to calculate the lowest integer `n`, such that:
the values nk1 and nk2 have the same digits but in different order.

E.g.# 1:
```
k1 = 100
k2 = 101
n = 8919
#Because 8919 * 100 = 891900
and      8919 * 101 = 900819
```

E.g.# 2:
```
k1 = 325
k2 = 326
n = 477
#Because 477 * 325 = 155025
and      477 * 326 = 155502
```

Your task is to prepare a function that will receive the value of `k` and outputs the value of `n`.

The examples given above will be:
```python
find_lowest_int(100) === 8919
find_lowest_int(325) ===  477
```
Features of the random tests
```
10 < k < 10.000.000.000.000.000 (For Python, Ruby and Haskell)
10 < k < 1.000.000.000  (For Javascript 1e9)
```
Enjoy it!!

Ruby and Javascript versions will be released soon.

def find_lowest_int(k):
    n=2
    while True:
        if sorted(str(n*k))==sorted(str(n*(k+1))):return n
        n+=1


Solve in Python:
We have two integer sequences A and B of the same non-zero length.
We are allowed to swap elements A[i] and B[i].  Note that both elements are in the same index position in their respective sequences.
At the end of some number of swaps, A and B are both strictly increasing.  (A sequence is strictly increasing if and only if A[0] < A[1] < A[2] < ... < A[A.length - 1].)
Given A and B, return the minimum number of swaps to make both sequences strictly increasing.  It is guaranteed that the given input always makes it possible.
Example:
Input: A = [1,3,5,4], B = [1,2,3,7]
Output: 1
Explanation:
Swap A[3] and B[3].  Then the sequences are:
A = [1, 3, 5, 7] and B = [1, 2, 3, 4]
which are both strictly increasing.

Note:

A, B are arrays with the same length, and that length will be in the range [1, 1000].
A[i], B[i] are integer values in the range [0, 2000].

class Solution:
    def minSwap(self, A: List[int], B: List[int]) -> int:
        n=len(A)
        mem = {}
        def rec(index,ifSwapped):
            if index==n:
                return 0
            elif (index,ifSwapped) in mem:
                return mem[(index,ifSwapped)]
            else:
                ans=float('inf')
                #Don't swap if possible
                if A[index]>A[index-1] and B[index]>B[index-1]:
                    ans=min(ans,rec(index+1,0))
                #Swap if possible
                if A[index]>B[index-1] and B[index]>A[index-1]:
                    A[index],B[index]=B[index],A[index] #Swap
                    ans=min(ans,1+rec(index+1,1))
                    A[index],B[index]=B[index],A[index] #Swap them back
                mem[(index,ifSwapped)]=ans
                return ans

        ans=float('inf')
        ans=min(ans,rec(1,0))
        A[0],B[0]=B[0],A[0]
        ans=min(ans,1+rec(1,1))
        A[0],B[0]=B[0],A[0]

        return ans


Solve in Python:
We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11).

Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero.

Example 1:

Input:
bits = [1, 0, 0]
Output: True
Explanation:
The only way to decode it is two-bit character and one-bit character. So the last character is one-bit character.

Example 2:

Input:
bits = [1, 1, 1, 0]
Output: False
Explanation:
The only way to decode it is two-bit character and two-bit character. So the last character is NOT one-bit character.

Note:
1 .
bits[i] is always 0 or 1.

class Solution:
     def isOneBitCharacter(self, bits):
         """
         :type bits: List[int]
         :rtype: bool
         """
         n = 0
         for i in range(-2, -len(bits)-1, -1):
             if bits[i] == 1:
                 n += 1
             else:
                 break
         return n % 2 == 0


Solve in Python:
We have two types of tiles: a 2x1 domino shape, and an "L" tromino shape. These shapes may be rotated.

XX  <- domino

XX  <- "L" tromino
X

Given N, how many ways are there to tile a 2 x N board? Return your answer modulo 10^9 + 7.

(In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.)

Example:
Input: 3
Output: 5
Explanation:
The five different ways are listed below, different letters indicates different tiles:
XYZ XXZ XYY XXY XYY
XYZ YYZ XZZ XYY XXY

Note:

       N  will be in range [1, 1000].

class Solution:
     def isIdealPermutation(self, A):
         """
         :type A: List[int]
         :rtype: bool
         """
         max_value = A[0]
         for i in range(1,len(A)-1):
             if A[i+1] < max_value:
                 return False
             if A[i] > max_value:
                 max_value = A[i]
         else:
             return True
         # local_count = 0
         # global_count = 0
         # for i in range(len(A)-1):
         #     if A[i] > A[i+1]:
         #         local_count += 1
         #     for j in range(len(A)):
         #         if A[i] > A[j] and i < j:
         #             global_count += 1
         # return local_count == global_count


Solve in Python:
We like parsed SQL or PL/SQL blocks...

You need to write function that return list of literals indices from source block, excluding "in" comments, OR return empty list if no literals found.

input:
some fragment of sql or pl/sql code

output:
list of literals indices [(start, end), ...] OR empty list

Sample:
```
get_textliterals("'this' is sample") -> [(0,6)]
get_textliterals("'this' is sample 'too'") -> [(0, 6), (15, 20)]
```

Text literal: any text between single quotes
Sample:
```
  s := 'i am literal'
```
Single-line comment: any text started with "--"
Sample:
```
  a := 1;
  -- this is single-line comment
```
Multy-line comment: any text between /* */
```
  a := 1;
  /*
  this is long multy-line comment
  */
```

Note:
1) handle single quote inside literal
```
  s := 'we can use quote '' in literal'
```
2) multy-line literal
```
 s := '
 this is literal too
 ';
```
3) skip literal inside comment
```
s := 'test'; --when comment started - this is not 'literal'
```
4) any unclosed literal should be closed with last symbol of the source fragment
```
s := 'test
```
There is one literal in this code: "'test"

def get_textliterals(pv_code):
    start_index = None
    all_index_store = []
    a_comment = False
    b_comment = False
    for index, char in enumerate(pv_code):
        if char == '*' and pv_code[index - 1] == '/':
            a_comment = True
        elif a_comment == True and char == '/' and pv_code[index - 1] == '*':
            a_comment = False
        elif char == '-' and pv_code[index - 1] == '-':
            b_comment = True
        elif b_comment == True and char == '\n':
            b_comment = False
        elif (char == '\'' or len(pv_code) - 1 == index) and a_comment == False and b_comment == False:
            if start_index != None:
                if (index > 0 and pv_code[index - 1] == '\'') or (len(pv_code) > index + 1 and pv_code[index + 1] == '\''):
                    continue
                all_index_store.append((start_index, index + 1))
                start_index = None
            else:
                start_index = index
    return all_index_store


Solve in Python:
We need a function (for commercial purposes) that may perform integer partitions with some constraints.
The function should select how many elements each partition should have.
The function should discard some "forbidden" values in each partition.
So, create ```part_const()```, that receives three arguments.
```part_const((1), (2), (3))```
```
(1) - The integer to be partitioned

(2) - The number of elements that each partition should have

(3) - The "forbidden" element that cannot appear in any partition
```
```part_const()``` should output the amount of different integer partitions with the constraints required.

Let's see some cases:
```python
part_const(10, 3, 2) ------> 4

/// we may have a total of 8 partitions of three elements (of course, the sum of the elements of each partition should be equal 10) :
[1, 1, 8], [1, 2, 7], [1, 3, 6], [1, 4, 5], [2, 2, 6], [2, 3, 5], [2, 4, 4], [3, 3, 4]

but 2 is the forbidden element, so we have to discard [1, 2, 7], [2, 2, 6], [2, 3, 5] and [2, 4, 4]

So the obtained partitions of three elements without having 2 in them are:
[1, 1, 8], [1, 3, 6], [1, 4, 5] and [3, 3, 4] (4 partitions)///
```

```part_const()``` should have a particular feature:

 if we introduce ```0``` as the forbidden element, we will obtain the total amount of partitions with the constrained number of elements.

In fact,
```python
part_const(10, 3, 0) ------> 8 # The same eight partitions that we saw above.
```

Enjoy it and happy coding!!

def get_addends(num, x=1):
  yield (num,)
  for i in range(x, num//2 + 1):
    for p in get_addends(num-i, i):
      yield (i,) + p

def part_const(n, k, num):
  return len([el for el in get_addends(n) if len(el) == k and num not in el])