Solve in Python:
You are given two positive integers ```a``` and ```b```.

You can perform the following operations on ```a``` so as to obtain ```b``` :
```
(a-1)/2   (if (a-1) is divisible by 2)
a/2       (if a is divisible by 2)
a*2
```
```b``` will always be a power of 2.

You are to write a function ```operation(a,b)``` that efficiently returns the minimum number of operations required to transform ```a``` into ```b```.

For example :
```
operation(2,8) -> 2
2*2 = 4
4*2 = 8

operation(9,2) -> 2
(9-1)/2 = 4
4/2 = 2

operation(1024,1024) -> 0
```

def operation(a,b):
  return 0 if a==b else 1 + (operation(a//2, b) if a>b else operation(a, b//2))


Solve in Python:
You are given two positive integers `a` and `b` (`a < b <= 20000`). Complete the function which returns a list of all those numbers in the interval `[a, b)` whose digits are made up of prime numbers (`2, 3, 5, 7`) but which are not primes themselves.

Be careful about your timing!

Good luck :)

ok = {i for i in range(22, 7778)
      if set(str(i)) <= set('2357')
      and not all(i%d for d in range(2, i))}

def not_primes(*a):
    return sorted(set(range(*a)) & ok)


Solve in Python:
You are given two sorted arrays of distinct integers nums1 and nums2.
A valid path is defined as follows:

Choose array nums1 or nums2 to traverse (from index-0).
Traverse the current array from left to right.
If you are reading any value that is present in nums1 and nums2 you are allowed to change your path to the other array. (Only one repeated value is considered in the valid path).

Score is defined as the sum of uniques values in a valid path.
Return the maximum score you can obtain of all possible valid paths.
Since the answer may be too large, return it modulo 10^9 + 7.

Example 1:

Input: nums1 = [2,4,5,8,10], nums2 = [4,6,8,9]
Output: 30
Explanation: Valid paths:
[2,4,5,8,10], [2,4,5,8,9], [2,4,6,8,9], [2,4,6,8,10],  (starting from nums1)
[4,6,8,9], [4,5,8,10], [4,5,8,9], [4,6,8,10]    (starting from nums2)
The maximum is obtained with the path in green [2,4,6,8,10].

Example 2:
Input: nums1 = [1,3,5,7,9], nums2 = [3,5,100]
Output: 109
Explanation: Maximum sum is obtained with the path [1,3,5,100].

Example 3:
Input: nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10]
Output: 40
Explanation: There are no common elements between nums1 and nums2.
Maximum sum is obtained with the path [6,7,8,9,10].

Example 4:
Input: nums1 = [1,4,5,8,9,11,19], nums2 = [2,3,4,11,12]
Output: 61

Constraints:

1 <= nums1.length <= 10^5
1 <= nums2.length <= 10^5
1 <= nums1[i], nums2[i] <= 10^7
nums1 and nums2 are strictly increasing.

class Solution:
    def maxSum(self, nums1: List[int], nums2: List[int]) -> int:
        # graph = [[] for _ in range(10000007)]
        graph = {}
        u1, u2 = nums1[0], nums2[0]

        for n in range(len(nums1) - 1):
            u, v = nums1[n], nums1[n + 1]
            if u in graph:
                graph[u].append(v)
            else:
                graph[u] = [v]

        for n in range(len(nums2) - 1):
            u, v = nums2[n], nums2[n + 1]
            if u in graph:
                graph[u].append(v)
            else:
                graph[u] = [v]

        DP = {}
        MODN = 1000000007

        def solve(u):
            if u in DP:
                return DP[u]

            ans = u
            if u in graph:
                for v in graph[u]:
                    ans = max(ans, u + solve(v))
            DP[u] = ans
            return DP[u]

        ans = max(solve(u1), solve(u2)) % MODN
        return ans


Solve in Python:
You are given two sorted arrays that contain only integers. Your task is to find a way to merge them into a single one, sorted in **ascending order**. Complete the function `mergeArrays(arr1, arr2)`, where `arr1` and `arr2` are the original sorted arrays.

You don't need to worry about validation, since `arr1` and `arr2` must be arrays with 0 or more Integers. If both `arr1` and `arr2` are empty, then just return an empty array.

**Note:** `arr1` and `arr2` may be sorted in different orders. Also `arr1` and `arr2` may have same integers. Remove duplicated in the returned result.

## Examples

Happy coding!

def merge_arrays(arr1, arr2):

    arr3 = sorted(arr1+arr2)

    for i in range(len(arr3)):
        for j in range(0,len(arr3) - 1 - i):
            if arr3[i] == arr3[i+1]:
                del arr3[i]
            else:
                continue
    return arr3


Solve in Python:
You are given two strings $S$ and $R$. Each of these strings has length $N$. We want to make $S$ equal to $R$ by performing the following operation some number of times (possibly zero):
- Choose two integers $a$ and $b$ such that $1 \le a \le b \le N$.
- For each $i$ such that $a \le i \le b$, replace the $i$-th character of $S$ by the $i$-th character of $R$.
Suppose that we make $S$ equal to $R$ by performing this operation $k$ times, in such a way that the total number of replaced characters (i.e. the sum of all $k$ values of $b-a+1$) is $l$. Then, the cost of this process is defined as $k \cdot l$.
Find the minimum cost with which we can make $S$ equal to $R$.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single string $S$.
- The second line contains a single string $R$.

-----Output-----
For each test case, print a single line containing one integer ― the minimum cost.

-----Constraints-----
- $1 \le T \le 4,000$
- $1 \le N \le 10^6$
- $|S| = |R| = N$
- $S$ and $R$ contain only lowercase English letters
- the sum of $N$ over all test cases does not exceed $2 \cdot 10^6$

-----Example Input-----
1
adefb
bdefa

-----Example Output-----
4

-----Explanation-----
Example case 1: $S$ can be made equal to $R$ in two moves. First, we replace $S_1$ by $R_1$ and then replace $S_5$ by $R_5$. We have $k = l = 2$, so the cost is $2 \cdot 2 = 4$. If we wanted to perform only one operation, the cost would be $5$.

for _ in range(int(input())):
 S = input()
 R = input()
 N = len(S)
 groups = []
 cont = False
 for i in range(N):
  if S[i] != R[i]:
   if cont:
    groups[-1][1] += 1
   else:
    groups.append([i, i])
    cont = True
  else:
   cont = False
 # print(groups)
 k = len(groups)
 l = 0
 diff = []
 for i in range(1,k):
  diff.append(groups[i][0] - groups[i - 1][1] - 1)
  l += (groups[i][1] - groups[i][0] + 1)
 if len(groups) > 0:
  l += (groups[0][1] - groups[0][0] + 1)
 diff.sort()
 mx = k * l
 for i in range(len(groups) - 1):
  k -= 1
  l += (diff[i])
  mx = min(mx, k * l)
 print(mx)


Solve in Python:
You are given two strings $s$ and $t$ both of length $n$ and both consisting of lowercase Latin letters.

In one move, you can choose any length $len$ from $1$ to $n$ and perform the following operation:   Choose any contiguous substring of the string $s$ of length $len$ and reverse it;  at the same time choose any contiguous substring of the string $t$ of length $len$ and reverse it as well.

Note that during one move you reverse exactly one substring of the string $s$ and exactly one substring of the string $t$.

Also note that borders of substrings you reverse in $s$ and in $t$ can be different, the only restriction is that you reverse the substrings of equal length. For example, if $len=3$ and $n=5$, you can reverse $s[1 \dots 3]$ and $t[3 \dots 5]$, $s[2 \dots 4]$ and $t[2 \dots 4]$, but not $s[1 \dots 3]$ and $t[1 \dots 2]$.

Your task is to say if it is possible to make strings $s$ and $t$ equal after some (possibly, empty) sequence of moves.

You have to answer $q$ independent test cases.

-----Input-----

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

The first line of the test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of $s$ and $t$.

The second line of the test case contains one string $s$ consisting of $n$ lowercase Latin letters.

The third line of the test case contains one string $t$ consisting of $n$ lowercase Latin letters.

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

-----Output-----

For each test case, print the answer on it — "YES" (without quotes) if it is possible to make strings $s$ and $t$ equal after some (possibly, empty) sequence of moves and "NO" otherwise.

-----Example-----
Input
4
4
abcd
abdc
5
ababa
baaba
4
asdf
asdg
4
abcd
badc

Output
NO
YES
NO
YES

import sys

def minp():
	return sys.stdin.readline().strip()

def mint():
	return int(minp())

def mints():
	return list(map(int,minp().split()))

def solve():
	n = mint()

	s = list(minp())
	t = list(minp())
	if sorted(t) != sorted(s):
		print("NO")
		return

	for i in range(26):
		if s.count(chr(ord('a')+i)) > 1:
			print("YES")
			return
	r = 0
	for i in range(len(s)):
		for j in range(i+1,len(s)):
			if t.index(s[i]) > t.index(s[j]):
				r += 1
	#print(r)
	print(["NO","YES"][r%2 == 0])

for i in range(mint()):
	solve()


Solve in Python:
You are given two strings of equal length $s$ and $t$ consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.

During each operation you choose two adjacent characters in any string and assign the value of the first character to the value of the second or vice versa.

For example, if $s$ is "acbc" you can get the following strings in one operation:   "aabc" (if you perform $s_2 = s_1$);  "ccbc" (if you perform $s_1 = s_2$);  "accc" (if you perform $s_3 = s_2$ or $s_3 = s_4$);  "abbc" (if you perform $s_2 = s_3$);  "acbb" (if you perform $s_4 = s_3$);

Note that you can also apply this operation to the string $t$.

Please determine whether it is possible to transform $s$ into $t$, applying the operation above any number of times.

Note that you have to answer $q$ independent queries.

-----Input-----

The first line contains one integer $q$ ($1 \le q \le 100$) — the number of queries. Each query is represented by two consecutive lines.

The first line of each query contains the string $s$ ($1 \le |s| \le 100$) consisting of lowercase Latin letters.

The second line of each query contains the string $t$ ($1 \le |t| \leq 100$, $|t| = |s|$) consisting of lowercase Latin letters.

-----Output-----

For each query, print "YES" if it is possible to make $s$ equal to $t$, and "NO" otherwise.

You may print every letter in any case you want (so, for example, the strings "yEs", "yes", "Yes", and "YES" will all be recognized as positive answer).

-----Example-----
Input
3
xabb
aabx
technocup
technocup
a
z

Output
YES
YES
NO

-----Note-----

In the first query, you can perform two operations $s_1 = s_2$ (after it $s$ turns into "aabb") and $t_4 = t_3$ (after it $t$ turns into "aabb").

In the second query, the strings are equal initially, so the answer is "YES".

In the third query, you can not make strings $s$ and $t$ equal. Therefore, the answer is "NO".

q = int(input())
for i in range(q):
    c = True
    s = input()
    t = input()
    for j in s:
        if j in t:
            print("YES")
            c = False
            break
    if c:
        print("NO")


Solve in Python:
You are given two strings s and t of the same length. You want to change s to t. Changing the i-th character of s to i-th character of t costs |s[i] - t[i]| that is, the absolute difference between the ASCII values of the characters.
You are also given an integer maxCost.
Return the maximum length of a substring of s that can be changed to be the same as the corresponding substring of twith a cost less than or equal to maxCost.
If there is no substring from s that can be changed to its corresponding substring from t, return 0.

Example 1:
Input: s = "abcd", t = "bcdf", maxCost = 3
Output: 3
Explanation: "abc" of s can change to "bcd". That costs 3, so the maximum length is 3.
Example 2:
Input: s = "abcd", t = "cdef", maxCost = 3
Output: 1
Explanation: Each character in s costs 2 to change to charactor in t, so the maximum length is 1.

Example 3:
Input: s = "abcd", t = "acde", maxCost = 0
Output: 1
Explanation: You can't make any change, so the maximum length is 1.

Constraints:

1 <= s.length, t.length <= 10^5
0 <= maxCost <= 10^6
s and t only contain lower case English letters.

class Solution:
    def equalSubstring(self, s: str, t: str, maxCost: int) -> int:
        currcost=0;i=0;j=0
        if(len(s)==0):
            return 0
        if(len(s)==1):
            if(abs(ord[s[0]])-ord(t[0])>=maxcost):
                return 1
            else:
                return 0
        currcost=0
        ans=0
        state=False
        while(i<len(s) and j<len(s)):
            if(currcost+abs(ord(s[j])-ord(t[j]))<=maxCost):
                currcost+=abs(ord(s[j])-ord(t[j]))
                j+=1
                state=True
            else:
                ans=max(ans,j-i)
                currcost-=abs(ord(s[i])-ord(t[i]))
                i+=1
                state=False
                if(i>=j):
                    j=i
                    currcost=0
        if state:
            ans=max(ans,j-i)
        return ans


Solve in Python:
You are given two strings. In a single move, you can choose any of them, and delete the first (i.e. leftmost) character.

For Example:

* By applying a move to the string `"where"`, the result is the string `"here"`.
* By applying a move to the string `"a"`, the result is an empty string `""`.

Implement a function that calculates the minimum number of moves that should be performed to make the given strings equal.

## Notes

* Both strings consist of lowercase latin letters.
* If the string is already empty, you cannot perform any more delete operations.

def shift_left(a, b):
    while True:
        if a and b and  a[-1] == b[-1]:
            a, b=a[:-1], b[:-1]
            continue
        return len(a)+len(b)


Solve in Python:
You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j].
Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so.

Example 1:
Input: s1 = "xx", s2 = "yy"
Output: 1
Explanation:
Swap s1[0] and s2[1], s1 = "yx", s2 = "yx".
Example 2:
Input: s1 = "xy", s2 = "yx"
Output: 2
Explanation:
Swap s1[0] and s2[0], s1 = "yy", s2 = "xx".
Swap s1[0] and s2[1], s1 = "xy", s2 = "xy".
Note that you can't swap s1[0] and s1[1] to make s1 equal to "yx", cause we can only swap chars in different strings.
Example 3:
Input: s1 = "xx", s2 = "xy"
Output: -1

Example 4:
Input: s1 = "xxyyxyxyxx", s2 = "xyyxyxxxyx"
Output: 4

Constraints:

1 <= s1.length, s2.length <= 1000
s1, s2 only contain 'x' or 'y'.

class Solution:
    def minimumSwap(self, s1: str, s2: str) -> int:
        xy_pair = 0
        yx_pair = 0

        for c1, c2 in zip(s1, s2):
            if c1 == 'x' and c2 == 'y':
                xy_pair += 1
            elif c1 == 'y' and c2 == 'x':
                yx_pair += 1

        if (xy_pair + yx_pair)%2 == 1:
            return -1

        return xy_pair//2 + yx_pair//2 + xy_pair%2 + yx_pair%2

'''
\"xx\"
\"yy\"
\"xy\"
\"yx\"
\"xx\"
\"xy\"
\"xyxy\"
\"yxyx\"
\"xxyyxxyxyxyx\"
\"xyxyxyxxyyxx\"
\"xxyyxyxyxx\"
\"xyyxyxxxyx\"
\"xyxyxyyxx\"
\"yxyyyxxxx\"
\"xyxyxyyxxxyyxyxxxyx\"
\"yxyyyxxxxxxyyxyxyxx\"
'''


Solve in Python:
You are going to be given a string. Your job is to return that string in a certain order that I will explain below:

Let's say you start with this: `012345`

The first thing you do is reverse it:`543210`
Then you will take the string from the 1st position and reverse it again:`501234`
Then you will take the string from the 2nd position and reverse it again:`504321`
Then you will take the string from the 3rd position and reverse it again:`504123`

Continue this pattern until you have done every single position, and then you will return the string you have created. For this particular number, you would return:`504132`

#Input:
A string of length 1 - 1000

#Output:
A correctly reordered string.

def reverse_fun(arr):
  for i in range(len(arr)):
    arr = arr[0:i] + arr[i:][::-1]
  return arr


Solve in Python:
You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters.

#Examples:
~~~if-not:bf
```
Kata.getMiddle("test") should return "es"

Kata.getMiddle("testing") should return "t"

Kata.getMiddle("middle") should return "dd"

Kata.getMiddle("A") should return "A"

```
~~~
~~~if:bf
```
runBF("test\0") should return "es"

runBF("testing\0") should return "t"

runBF("middle\0") should return "dd"

runBF("A\0") should return "A"

```
~~~

#Input

A word (string) of length `0 < str < 1000` (In javascript you may get slightly more than 1000 in some test cases due to an error in the test cases). You do not need to test for this. This is only here to tell you that you do not need to worry about your solution timing out.

#Output

The middle character(s) of the word represented as a string.

import math
def get_middle(s):
    #your code here
    x = len(s)
    y = int(x/2)
    if x%2==0:
        return s[y-1:y+1]
    else:
        return s[y:y+1]


Solve in Python:
You are going to be given a word. Your job will be to make sure that each character in that word has the exact same number of occurrences. You will return `true` if it is valid, or `false` if it is not.

For example:

`"abcabc"` is a valid word because `'a'` appears twice, `'b'` appears twice, and`'c'` appears twice.
`"abcabcd"` is **NOT** a valid word because `'a'` appears twice, `'b'` appears twice, `'c'` appears twice, but `'d'` only appears once!
`"123abc!"` is a valid word because all of the characters only appear once in the word.

For this kata, capitals are considered the same as lowercase letters. Therefore: `'A' == 'a'` .

#Input
A string (no spaces) containing `[a-z],[A-Z],[0-9]` and common symbols. The length will be `0 < string < 100`.

#Output
`true` if the word is a valid word, or `false` if the word is not valid.

def validate_word(word):
    word = word.lower()
    return all(word.count(i) == word.count(word[0]) for i in word)


Solve in Python:
You are going to be given an array of integers. Your job is to take that array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return `-1`.

__For example:__

Let's say you are given the array `{1,2,3,4,3,2,1}`:
Your function will return the index `3`, because at the 3rd position of the array, the sum of left side of the index (`{1,2,3}`) and the sum of the right side of the index (`{3,2,1}`) both equal `6`.

Let's look at another one.
You are given the array `{1,100,50,-51,1,1}`:
Your function will return the index `1`, because at the 1st position of the array, the sum of left side of the index (`{1}`) and the sum of the right side of the index (`{50,-51,1,1}`) both equal `1`.

Last one:
You are given the array `{20,10,-80,10,10,15,35}`
At index 0 the left side is `{}`
The right side is `{10,-80,10,10,15,35}`
They both are equal to `0` when added. (Empty arrays are equal to 0 in this problem)
Index 0 is the place where the left side and right side are equal.

Note: Please remember that in most programming/scripting languages the index of an array starts at 0.

__Input:__
An integer array of length `0 < arr < 1000`. The numbers in the array can be any integer positive or negative.

__Output:__
The lowest index `N` where the side to the left of `N` is equal to the side to the right of `N`. If you do not find an index that fits these rules, then you will return `-1`.

__Note:__
If you are given an array with multiple answers, return the lowest correct index.

def find_even_index(arr):
    left, right = 0,sum(arr)
    for i,v in enumerate(arr):
        right -= v
        if left == right: return i
        left += v
    return -1


Solve in Python:
You are in charge of controlling a dam. The dam can store at most L liters of water. Initially, the dam is empty. Some amount of water flows into the dam every morning, and any amount of water may be discharged every night, but this amount needs to be set so that no water overflows the dam the next morning.
It is known that v_i liters of water at t_i degrees Celsius will flow into the dam on the morning of the i-th day.
You are wondering about the maximum possible temperature of water in the dam at noon of each day, under the condition that there needs to be exactly L liters of water in the dam at that time. For each i, find the maximum possible temperature of water in the dam at noon of the i-th day. Here, consider each maximization separately, that is, the amount of water discharged for the maximization of the temperature on the i-th day, may be different from the amount of water discharged for the maximization of the temperature on the j-th day (j≠i).
Also, assume that the temperature of water is not affected by anything but new water that flows into the dam. That is, when V_1 liters of water at T_1 degrees Celsius and V_2 liters of water at T_2 degrees Celsius are mixed together, they will become V_1+V_2 liters of water at \frac{T_1*V_1+T_2*V_2}{V_1+V_2} degrees Celsius, and the volume and temperature of water are not affected by any other factors.

-----Constraints-----
 - 1≤ N ≤ 5*10^5
 - 1≤ L ≤ 10^9
 - 0≤ t_i ≤ 10^9(1≤i≤N)
 - 1≤ v_i ≤ L(1≤i≤N)
 - v_1 = L
 - L, each t_i and v_i are integers.

-----Input-----
Input is given from Standard Input in the following format:
N L
t_1 v_1
t_2 v_2
:
t_N v_N

-----Output-----
Print N lines. The i-th line should contain the maximum temperature such that it is possible to store L liters of water at that temperature in the dam at noon of the i-th day.
Each of these values is accepted if the absolute or relative error is at most 10^{-6}.

-----Sample Input-----
3 10
10 10
20 5
4 3

-----Sample Output-----
10.0000000
15.0000000
13.2000000

 - On the first day, the...

# なんだか釈然としていないが解説の通りに
from collections import deque
import sys

def MI(): return list(map(int, sys.stdin.readline().split()))

class water:
    def __init__(self, t, v):
        self.v = v
        self.tv = v * t

    def __le__(self, other):
        return self.v * other.tv - self.tv * other.v >= 0

    def __isub__(self, other):
        t = self.tv / self.v
        self.v -= other
        self.tv = t * self.v
        return self

    def __iadd__(self, other):
        self.v+=other.v
        self.tv+=other.tv
        return self

def main():
    n, l = MI()
    dam = deque()
    t, v = MI()
    print(t)
    dam.append(water(t, v))
    # stvはtvの合計（vがlのときのvt）
    stv = t * v
    for _ in range(n-1):
        t, v = MI()
        # 朝に水をもらう
        dam.appendleft(water(t, v))
        over = v
        stv += t * v
        # 増えた分の水を古い方から捨てる
        # ベクトルごと削除できるもの
        while dam[-1].v <= over:
            w = dam.pop()
            over -= w.v
            stv -= w.tv
        # 最後のはみ出しているベクトルは縮める
        stv -= dam[-1].tv  # 一度合計から取り出して
        dam[-1] -= over  # 縮めて
        stv += dam[-1].tv  # 元に戻す
        # その日の水温を出力
        print((stv / l))
        # グラフの左側が凹んでいたらベクトルを合成して凸に直す
        while len(dam)>1 and dam[0] <= dam[1]:
            w = dam.popleft()
            dam[0] += w

main()


Solve in Python:
You are in the capital of Far, Far Away Land, and you have heard about this museum where the royal family's crown jewels are on display. Before you visit the museum, a friend tells you to bring some extra money that you'll need to bribe the guards. You see, he says, the crown jewels are in one of 10 rooms numbered from 1 to 10. The doors to these room are kept closed, and each is guarded by a very intimidating guard.

For security purposes, the jewels are moved every night to a different room. To find out which room they are in, you'll have to ask one of the guards. But first you have to pay him a bribe. After paying him:

  1. If the jewels are behind the door he's guarding, he'll let you in.
  2. Otherwise, he'll point you in the direction of the correct room by telling you if the room has a higher or lower room number than the room he's guarding.

The guards have a special rank system, and, depending on rank, the size of the bribe that you'll need to pay to each guard may vary. For example, you may have to pay $1 to the guard at room 1, $2 to the guard at room 2, and so on, up to $10 to the guard at room 10. The bribe amounts are specified by an array/list sorted by room number in ascending order. Hence, in this example, the bribes are given by `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]`.

The problem you need to solve is to determine the minimum amount you may need _in the worst case_ to get into the room with the crown jewels. As a seasoned programmer, you might try doing a binary search. Let's assume that the bribes are as specified in the example above. You first go to the guard standing in front of room 5, and pay him $5. In the worst case the crown jewels are in room 10 and you'll end up paying: $5 + $8 + $9 + $10 = $32. It turns out that a regular binary search is not optimal in this case. You are better off if you first go to room 7. In the worst case the guard will direct you to the right(i.e., higher numbered rooms) and then you go to room 9. Again, in the worst case the guard will direct you to the...

def memoize(f):
    memo = {}
    def memoized(*args):
        if not args in memo:
            memo[args] = f(*args)
        return memo[args]
    return memoized

def least_bribes(xs):
    @memoize
    def f(i, j):
        return i - j and min(max(f(i, k), f(k + 1, j)) + xs[k] for k in range(i, j))
    return f(0, len(xs))


Solve in Python:
You are in the future. It's the time of autonomous cars. Switching lanes is a pretty difficult task for autonomous cars, and you have the logs from an experiment you had run with two cars. You want to verify whether the logs are corrupted, or could be valid.
In that experiment, you had a highway consisting of two lanes. These were represented by 2 rows of an infinite grid. The cell (1, 1) is the top left cell which is the starting point of the first lane. Cell (2, 1) is the bottom left cell of the grid which is the starting point of the second lane.
There are two cars, 1 and 2 that start from the cell (1, 1) and (2, 1).
At each instant, a car has the following choices.
- Stay at the current position.
- Move one cell to the right.
- Switch Lanes. When a car switches its lane, it stays in the same column. That is, from (1, i) it could go to (2, i), or from (2, i) it could go to (1, i). But both both cars shouldn't end up at the same cell at any point. Note that there could have been a car which had moved at the very instant that you move into it.
Consider one such scenario of driving cars.
Time $t = 0$
1.....
2.....

Time $t = 1$. Car 2 advances one cell right. Car 1 stays at the same place.
1.....
.2....

Time $t = 2$. Car 2 stays at its place. Car 1 switches the lane.
......
12....

Time $t = 3$. Car 2 moves one cell to the right.  Car 1 also moves one cell to the right.
......
.12...

Time $t = 4$. Both the cars stay in the same place.
......
.12...

You are given positions of the car at $n$ instants. Your task is to check whether this situation is feasible or not.

-----Input-----
- The first line of the input contains an integer $T$ denoting the number of test cases. The description of the test cases follows.
- The first line of each test case contains an integer $n$ denoting the number of instants where the positions of the cars were recorded.
- Each of next $n$ lines contains 5 space separated integers denoting $t_i, x_i, y_i, X_i, Y_i$ denoting time, $x$ and $y$ coordinate of the first car, and that of...

# cook your dish here
def check(px,x):
 if px[1]==x[1]:
  return (x[2]-px[2])<=(x[0]-px[0]) and (x[2]>=px[2])
 else:
  return (x[2]-px[2]+1)<=(x[0]-px[0]) and (x[2]>=px[2])

def checkdouble(px,x):
 if px[3]==x[3]:
  return (x[4]-px[4])<=(x[0]-px[0]) and (x[4]>=px[4])
 else:
  return (x[4]-px[4]+1)<=(x[0]-px[0]) and (x[4]>=px[4])

for _ in range(int(input())):
 px=[0,1,1,2,1]
 g=True
 for _ in range(int(input())):
  x=list(map(int,input().split()))
  if x[1]==x[3] and x[2]==x[4]:
   g=False
  if not g:
   continue
  g=check(px,x)
  if g:
   g=checkdouble(px,x)
  px=x
 if not g:
  print("no")
 else:
  print("yes")


Solve in Python:
You are installing a billboard and want it to have the largest height.  The billboard will have two steel supports, one on each side.  Each steel support must be an equal height.
You have a collection of rods which can be welded together.  For example, if you have rods of lengths 1, 2, and 3, you can weld them together to make a support of length 6.
Return the largest possible height of your billboard installation.  If you cannot support the billboard, return 0.

Example 1:
Input: [1,2,3,6]
Output: 6
Explanation: We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.

Example 2:
Input: [1,2,3,4,5,6]
Output: 10
Explanation: We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.

Example 3:
Input: [1,2]
Output: 0
Explanation: The billboard cannot be supported, so we return 0.

Note:

0 <= rods.length <= 20
1 <= rods[i] <= 1000
The sum of rods is at most 5000.

class Solution:
    def tallestBillboard(self, rods: List[int]) -> int:
        # dp[diff] = a: have a pair of (a, a + diff)

        dp = {0: 0}
        for rod in rods:
            for d, x in list(dp.items()):
                dp[d + rod] = max(dp.get(d + rod, 0), x)
                dp[abs(d - rod)] = max(dp.get(abs(d - rod), 0), x + min(d, rod))

        return dp[0]


Solve in Python:
You are making your very own boardgame. The game is played by two opposing players, featuring a 6 x 6 tile system, with the players taking turns to move their pieces (similar to chess). The design is finished, now it's time to actually write and implement the features. Being the good programmer you are, you carefully plan the procedure and break the program down into smaller managable sections. You decide to start coding the logic for resolving "fights" when two pieces engage in combat on a tile.

Your boardgame features four unique pieces:

Swordsman, Cavalry, Archer and Pikeman

Each piece has unique movement and has advantages and weaknesses in combat against one of the other pieces.

Task

You must write a function ```fightResolve``` that takes the attacking and defending piece as input parameters, and returns the winning piece. It may be the case that both the attacking and defending piece belong to the same player, after which you must return an error value to indicate an illegal move.

In C++ and C, the pieces will be represented as ```chars```. Values will be case-sensitive to display ownership. Let the following char values represent each piece from their respective player.

Player 1:  ```p```= Pikeman, ```k```= Cavalry, ```a```= Archer, ```s```= Swordsman

Player 2:  ```P```= Pikeman, ```K```= Cavalry, ```A```= Archer, ```S```= Swordsman

The outcome of the fight between two pieces depends on which piece attacks, the type of the attacking piece and the type of the defending piece. Archers always win against swordsmens, swordsmen always win against pikemen, pikemen always win against cavalry and cavalry always win against archers. If a matchup occurs that was not previously mentioned (for example Archers vs Pikemen) the attacker will always win. This table represents the winner of each possible engagement between an attacker and a defender.

(Attacker→)
   ...

def fight_resolve(d, a):
    if d.islower() == a.islower(): return -1
    map = {"a":"s", "k":"a", "p":"k", "s":"p"}
    return d if map[d.lower()] == a.lower() else a


Solve in Python:
You are participating in a contest which has $11$ problems (numbered $1$ through $11$). The first eight problems (i.e. problems $1, 2, \ldots, 8$) are scorable, while the last three problems ($9$, $10$ and $11$) are non-scorable ― this means that any submissions you make on any of these problems do not affect your total score.
Your total score is the sum of your best scores for all scorable problems. That is, for each scorable problem, you look at the scores of all submissions you made on that problem and take the maximum of these scores (or $0$ if you didn't make any submissions on that problem); the total score is the sum of the maximum scores you took.
You know the results of all submissions you made. Calculate your total score.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$ denoting the number of submissions you made.
- $N$ lines follow. For each $i$ ($1 \le i \le N$), the $i$-th of these lines contains two space-separated integers $p_i$ and $s_i$, denoting that your $i$-th submission was on problem $p_i$ and it received a score $s_i$.

-----Output-----
For each test case, print a single line containing one integer ― your total score.

-----Constraints-----
- $1 \le T \le 10$
- $1 \le N \le 1,000$
- $1 \le p_i \le 11$ for each valid $i$
- $0 \le s_i \le 100$ for each valid $i$

-----Subtasks-----
Subtask #1 (15 points): all submissions are on the same problem, i.e. $p_1 = p_2 = \ldots = p_N$
Subtask #2 (15 points): there is at most one submission made on each problem, i.e. $p_i \neq p_j$ for each valid $i, j$ ($i \neq j$)
Subtask #3 (70 points): original constraints

-----Example Input-----
2
5
2 45
9 100
8 0
2 15
8 90
1
11 1

-----Example Output-----
135
0

-----Explanation-----
Example case 1: The scorable problems with at least one submission are problems $2$ and $8$. For problem $2$, there are two submissions and the maximum score...

# cook your dish here
rii = lambda : list(map(int, input().strip().split(" ")))
ril = lambda : list(map(int, input().strip().split(" ")))
ri = lambda : int(input().strip())
rs = lambda : eval(input())
T = ri()
for _ in range(T):
 N = ri()
 l = [0 for i in range(8)]
 for i in range(N):
  nb, S = rii()
  if nb < 9:
   l[nb-1] = max(S, l[nb-1])
 print(sum(l))


Solve in Python:
You are playing a Billiards-like game on an $N \times N$ table, which has its four corners at the points $\{(0, 0), (0, N), (N, 0),$ and $(N, N)\}$. You start from a coordinate $(x,y)$,  $(0 < x < N, 0 <  y < N)$ and shoot the ball at an angle $45^{\circ}$ with the horizontal. On hitting the sides, the ball continues to move with the same velocity and ensuring that the angle of incidence is equal to the angle of reflection with the normal, i.e, it is reflected with zero frictional loss. On hitting either of the four corners, the ball stops there and doesn’t move any further.
Find the coordinates of the point of collision, when the ball hits the sides for the $K^{th}$ time. If the ball stops before hitting the sides $K$ times, find the coordinates of the corner point where the ball stopped instead.

-----Input:-----
- The first line of the input contains an integer $T$, the number of testcases.
- Each testcase contains a single line of input, which has four space separated integers - $N$, $K$, $x$, $y$, denoting the size of the board, the number of collisions to report the answer for, and the starting coordinates.

-----Output:-----
For each testcase, print the coordinates of the ball when it hits the sides for the $K^{th}$ time, or the coordinates of the corner point if it stopped earlier.

-----Constraints-----
- $1 \leq T \leq 10^5$
- $2 \leq N \leq 10^9$
- $1 \leq K \leq 10^9$

-----Subtasks-----
- $30$ points :  Sum of $K$ over all test cases $\le 10^7$
- $70$ points : Original constraints.

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

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

-----Explanation:-----
- Sample Case $1$ :
We are given a $5$ by $5$ board. We shoot the ball from coordinates $(4,4)$, and we need to find its coordinates after it has collided with sides $5$ times. However, after shooting, the ball goes directly to the corner $(5,5)$, and stops there. So we report the coordinates $(5,5)$.

- Sample Case $2$ :
We are given a $5$ by $5$ board. We shoot the ball from the coordinates $(3,1)$, and we need to...

def res(x,y,n,k):
 d=abs(x-y)
 if x==y:
  return n,n
 elif x>y:
  if k%4==0:
   return d,0
  if k%4==1:
   return n,n-d
  if k%4==2:
   return n-d,n
  if k%4==3:
   return 0,d
 elif x<y:
  if k%4==0:
   return 0,d
  if k%4==1:
   return n-d,n
  if k%4==2:
   return n,n-d
  if k%4==3:
   return d,0
n=int(input())
for i in range(n):
 n,k,x,y=list(map(int,input().split()))
 a,b=res(x,y,n,k)
 print(a,b)


Solve in Python:
You are playing a game where you have been sent in a town to collect 10 types of coin and their symbol are defined with $A, B, C, D, E, F, G, H , I, J$. In that town every enemy have a coin. By killing one you will get a coin from that enemy. Each enemy have only a unique coin.
The challange of the game is You have to collect all the coin and only then you will get the victory. You are a brave gamer so you took this hard challange and successfully finished it. After finishing, you are thinking of the game. You know the order off collecting coin. Now you are thinking how many enemy did you have killed?
Can you solve that out?

-----Input:-----
First line of the input is an integer $T$.Next T line consists of a string which denotes the order of your collecting coins. The string consists of Uppercase latin latter only and from A to J.

-----Output:-----
Print T line, in each line an integer with the number of enemy you have killed in the operation.

-----Constraints-----
- $1 \leq T \leq 5000$

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

-----Sample Output:-----
10

for _ in range(int(input())):
 s=input()
 se=set()
 ans=0
 for i in s:
  se.add(i)
  ans+=1
  if(len(se)==10):
   break
 print(ans)


Solve in Python:
You are playing a variation of game 2048. Initially you have a multiset $s$ of $n$ integers. Every integer in this multiset is a power of two.

You may perform any number (possibly, zero) operations with this multiset.

During each operation you choose two equal integers from $s$, remove them from $s$ and insert the number equal to their sum into $s$.

For example, if $s = \{1, 2, 1, 1, 4, 2, 2\}$ and you choose integers $2$ and $2$, then the multiset becomes $\{1, 1, 1, 4, 4, 2\}$.

You win if the number $2048$ belongs to your multiset. For example, if $s = \{1024, 512, 512, 4\}$ you can win as follows: choose $512$ and $512$, your multiset turns into $\{1024, 1024, 4\}$. Then choose $1024$ and $1024$, your multiset turns into $\{2048, 4\}$ and you win.

You have to determine if you can win this game.

You have to answer $q$ independent queries.

-----Input-----

The first line contains one integer $q$ ($1 \le q \le 100$) – the number of queries.

The first line of each query contains one integer $n$ ($1 \le n \le 100$) — the number of elements in multiset.

The second line of each query contains $n$ integers $s_1, s_2, \dots, s_n$ ($1 \le s_i \le 2^{29}$) — the description of the multiset. It is guaranteed that all elements of the multiset are powers of two.

-----Output-----

For each query print YES if it is possible to obtain the number $2048$ in your multiset, and NO otherwise.

You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

-----Example-----
Input
6
4
1024 512 64 512
1
2048
3
64 512 2
2
4096 4
7
2048 2 2048 2048 2048 2048 2048
2
2048 4096

Output
YES
YES
NO
NO
YES
YES

-----Note-----

In the first query you can win as follows: choose $512$ and $512$, and $s$ turns into $\{1024, 64, 1024\}$. Then choose $1024$ and $1024$, and $s$ turns into $\{2048, 64\}$ and you win.

In the second query $s$ contains $2048$ initially.

q = int(input())
while q:
    n = int(input())
    a = list(map(int, input().split()))
    a.sort()
    i = 0
    d = False
    while i < len(a) - 1:
        if 2048 in a:
            d = True
            break
        if a[i] == a[i + 1]:
            a.append(a[i] + a[i + 1])
            a.sort()
            i += 2
        else:
            i += 1
    if 2048 in a:
        d = True
    if d:
        print("YES")
    else:
        print("NO")
    q -= 1


Solve in Python:
You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $k$ torches. One torch can be crafted using one stick and one coal.

Hopefully, you've met a very handsome wandering trader who has two trade offers:  exchange $1$ stick for $x$ sticks (you lose $1$ stick and gain $x$ sticks).  exchange $y$ sticks for $1$ coal (you lose $y$ sticks and gain $1$ coal).

During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.

Your task is to find the minimum number of trades you need to craft at least $k$ torches. The answer always exists under the given constraints.

You have to answer $t$ independent test cases.

-----Input-----

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

The only line of the test case contains three integers $x$, $y$ and $k$ ($2 \le x \le 10^9$; $1 \le y, k \le 10^9$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively.

-----Output-----

For each test case, print the answer: the minimum number of trades you need to craft at least $k$ torches. The answer always exists under the given constraints.

-----Example-----
Input
5
2 1 5
42 13 24
12 11 12
1000000000 1000000000 1000000000
2 1000000000 1000000000

Output
14
33
25
2000000003
1000000001999999999

t = int(input())

for ii in range(t):

	x, y, k = map(int, input().split())

	coals = k
	sticks = k

	sticks = k*y + k

	num = (sticks-1)//(x-1)

	if (sticks-1)%(x-1) != 0:
		num+=1

	num += k

	print(num)


Solve in Python:
You are playing euchre and you want to know the new score after finishing a hand. There are two teams and each hand consists of 5 tricks. The team who wins the majority of the tricks will win points but the number of points varies. To determine the number of points, you must know which team called trump, how many tricks each team won, and if anyone went alone. Scoring is as follows:

For the team that called trump:

- if they win 2 or less tricks -> other team wins 2 points

- if they win 3 or 4 tricks -> 1 point

- if they don't go alone and win 5 tricks -> 2 points

- if they go alone and win 5 tricks -> 4 points

Only the team who called trump can go alone and you will notice that it only increases your points if you win all 5 tricks.

Your job is to create a method to calculate the new score. When reading the arguments, team 1 is represented by 1 and team 2 is represented by 2. All scores will be stored with this order: { team1, team2 }.

def update_score(current_score, called_trump, alone, tricks):
    n = tricks.count(called_trump)
    if n <= 2:
        called_trump = 3 - called_trump
        p = 2
    elif n <= 4:
        p = 1
    else:
        p = 4 if alone else 2
    current_score[called_trump > 1] += p
    return current_score


Solve in Python:
You are playing following game: given an array A of N natural numbers. All numbers in the array A are at most M. On every turn you may pick any two different elements Ai and Aj (i≠j), such that Ai, Aj ≤ M, and add K to both. The game ends when you are not able to continue. That is, when there is no pair (i,j) left such that both of them are less than equal to M.

Let's call two arrays different if the sum of all their elements is different. When the game ends, you note down the final array A. How many different final arrays can you have.

-----Input-----

The first line contains three integers N, M and K. N elements of the array follow in the next line.

-----Output-----

Output single integer - answer for the given problem modulo 109+7.

-----Constraints-----
-  1 ≤ N ≤ 105
-  1 ≤ M,K ≤ 1012
-  1 ≤ Ai ≤ M

-----Example-----
Input:
3 3 2
1 2 3
Output:
2

-----Explanation-----

All possible sums are 14 and 10. You can get them by, for example, these arrays:
A=(5, 4, 5),
A=(1, 4, 5)

The above arrays are different because their sums are different.

from math import ceil
from bisect import bisect_right as b_r
from bisect import bisect_left as b_l
ar = list(map(int , input().split()))
a = [int(ceil((ar[1]-int(x)+1)/ar[2])) for x in input().split()]
s = sum(a)
ar[1] = max(a)
m = ar[1] - (s-ar[1])%2
mi = s%2
print(int( (m-mi)//2 +1)%(10**9+7))


Solve in Python:
You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number.

Write a function to return a hint according to the secret number and friend's guess, use A to indicate the bulls and B to indicate the cows.

Please note that both secret number and friend's guess may contain duplicate digits.

Example 1:

Input: secret = "1807", guess = "7810"

Output: "1A3B"

Explanation: 1 bull and 3 cows. The bull is 8, the cows are 0, 1 and 7.

Example 2:

Input: secret = "1123", guess = "0111"

Output: "1A1B"

Explanation: The 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow.

Note: You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.

class Solution:
     def getHint(self, secret, guess):
         """
         :type secret: str
         :type guess: str
         :rtype: str
         """
         secretDict={0:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0}
         friendDict={0:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0}
         bulls=0
         cows=0
         for s, g in zip(secret,guess):
             if s==g:
                 bulls+=1
             else:
                 secretDict[int(s)]+=1
                 friendDict[int(g)]+=1
         for i in range(10):
             cows+=min(secretDict[i],friendDict[i])
         return '{}A{}B'.format(bulls,cows)


Solve in Python:
You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.

Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.

Example:

Input: 4
Output: false
Explanation: If there are 4 stones in the heap, then you will never win the game;
             No matter 1, 2, or 3 stones you remove, the last stone will always be
             removed by your friend.

class Solution:
     def canWinNim(self, n):
         return n % 4 != 0


Solve in Python:
You are provided with an input containing a number. Implement a solution to find the largest sum of consecutive increasing digits , and present the output with the largest sum and the positon of start and end of the consecutive digits.
Example :
Input :> 8789651
Output :> 24:2-4
where 24 is the largest sum and 2-4 is start and end of the consecutive increasing digits.

arr=input().strip()
res=[]
for i in range(len(arr)):
    s=int(arr[i])
    k=0
    for j in range(i,len(arr)-1):
        if arr[j+1]>arr[j]:
            s=s+int(arr[j+1])
            k+=1
        else:
            break
    res.append([i+1,i+k+1,s])
for i in range(len(res)):
    for j in range(i+1,len(res)):
        if res[i][2]>res[j][2]:
            temp=res[j]
            res[j]=res[i]
            res[i]=temp
print("{}:{}-{}".format(res[-1][2],res[-1][0],res[-1][1]))


Solve in Python:
You are provided with array of positive non-zero ints and int n representing n-th power (n >= 2).

For the given array, calculate the sum of each value to the n-th power. Then subtract the sum of the original array.

Example 1: Input: {1, 2, 3}, 3 --> (1 ^ 3 + 2 ^ 3 + 3 ^ 3 ) - (1 + 2 + 3) --> 36 - 6 --> Output: 30

Example 2: Input: {1, 2}, 5  --> (1 ^ 5 + 2 ^ 5) - (1 + 2) --> 33 - 3 --> Output: 30

def modified_sum(a, n):
    return sum([x ** n - x for x in a])


Solve in Python:
You are provided with the marks of entire class in Data structures exam out of 100. You need to calculate the number of students having backlog (passing marks is >=31) and the average of the class. But this average is not a normal average, for this average marks of students having backlog are not considered but they will be considered in number of students. Also print the index of topper’s marks and print the difference of everyone’s marks with respect to the topper.
In first line print the number of students having backlog and average of the class. In second line print indices of all the toppers(in case of more than 1 topper print index of all toppers in reverse order). Next N lines print the difference of everyone’s marks with respect to topper(s).
Note- if all students have backlog than average will be 0.
INPUT
The first line of the input contains an integer T denoting the number of test cases.
Next line contains N denoting the no of students in the class.
The line contains N space seprated integers A1,A2,A3….AN denoting the marks of each student in exam.
OUTPUT
First line contains the number of students having backlog and the special average of marks as described above. Average must have 2 decimal places.
Next line contains the indices of all the toppers in given array in reverse order.
Next N lines contain the difference of every student’s marks with respect to toppers.
Constraints
1<= T <= 100
1<= N <= 30
0<= Ai<= 100
Example
Input
1
9
56 42 94 25 74 99 27 52 83
Output
2 55.55
5
43
57
5
74
25
0
72
47
16

t=int(input())
for i in range(t):
 n=int(input())
 l=list(map(int,input().strip().split()))
 bl=0
 jod=0
 big=0
 for j in l:
  if j<31:
   bl+=1
  else:
   jod+=j
  if j>big:
   big=j
 avg=jod/n
 dif=[0 for i in range(n)]
 top=[]
 for j in range(n):
  dif[j]=big-l[j]
  if l[j]==big:
   top.append(j)
 print(bl,end=' ')
 print('%.2f'%avg)
 for j in range(len(top)-1,-1,-1):
  print(top[j],end=' ')
 print()
 for j in range(n):
  print(dif[j])


Solve in Python:
You are required to create a simple calculator that returns the result of addition, subtraction, multiplication or division of two numbers.

Your function will accept three arguments:
The first and second argument should be numbers.
The third argument should represent a sign indicating the operation to perform on these two numbers.
```if-not:csharp
if the variables are not numbers or the sign does not belong to the list above a message "unknown value" must be returned.
```
```if:csharp
If the sign is not a valid sign, throw an ArgumentException.
```

# Example:

```python
calculator(1, 2, '+') => 3
calculator(1, 2, '$') # result will be "unknown value"
```

Good luck!

def calculator(x,y,op):
    print (f"{x}{op}{y}")
    try:
         if op in "+-/*":
            return eval(f"{x}{op}{y}")
    except:
        pass
    return "unknown value"


Solve in Python:
You are stacking some boxes containing gold weights on top of each other. If a box contains more weight than the box below it, it will crash downwards and combine their weights. e.g. If we stack [2] on top of [1], it will crash downwards and become a single box of weight [3]
```
[2]
[1] --> [3]
```
Given an array of arrays, return the bottom row (i.e. the last array) after all crashings are complete.
```
crashing_weights([[1, 2, 3],  --> [[1, 2,  ],      [[1,  ,  ]],
                  [2, 3, 1],  -->  [2, 3, 4],  -->  [2, 2,  ],
                  [3, 1, 2]])      [3, 1, 2]]  -->  [3, 4, 6]]

therefore return [3, 4, 6]
```

## More details

boxes can be stacked to any height, and the crashing effect can snowball:
```
[3]
[2]     [5]
[4] --> [4] --> [9]
```
Crashing should always start from as high up as possible -- this can alter the outcome! e.g.
```
[3]                      [3]
[2]     [5]              [2]     [3]
[1] --> [1] --> [6], not [1] --> [3]
```
Weights will always be integers. The matrix (array of arrays) may have any height or width > 1, and may not be square, but it will always be "nice" (all rows will have the same number of columns, etc).

from functools import reduce

def crashing_weights(weights):
    return reduce(crash_if_heavier, weights)

def crash_if_heavier(upper_row, lower_row):
    return [wl if wu <= wl else wu + wl for wu, wl in zip(upper_row, lower_row)]


Solve in Python:
You are standing near a very strange machine. If you put C cents in the machine, the remaining money in your purse will transform in an unusual way. If you have A dollars and B cents remaining in your purse after depositing the C cents, then after the transformation you will have B dollars and A cents. You can repeat this procedure as many times as you want unless you don't have enough money for the machine. If at any point C > B and A > 0, then the machine will allow you to break one of the A dollars into 100 cents so you can place C cents in the machine. The machine will not allow you to exchange a dollar for 100 cents if B >= C.

Of course, you want to do this to maximize your profit. For example if C=69 and you have 9 dollars and 77 cents then after you put 69 cents in the machine you will have 8 dollars and 9 cents (9.77 --> 9.08 --> 8.09). But I should warn you that you can't cheat. If you try to throw away 9 cents before the transformation (in order to obtain 99 dollars and 8 cents after), the machine will sense you are cheating and take away all of your money. You need to know how many times you should do this transformation in order to make a maximum profit. Since you are very busy man, you want to obtain the maximum possible profit in the minimum amount of time.

-----Input-----
The first line contains a single integer T <= 40, the number of test cases. T test cases follow. The only line of each test case contains three nonnegative integers A, B and C where A, B, C < 100. It means that you have A dollars and B cents in your purse and you need to put C cents in the machine to make the transformation.

-----Output-----
For each test case, output a single line containing the minimal number of times you should do this transformation in order to make a maximal profit. It is guaranteed that the answer is less than 10000.

-----Example-----
Input:
2
9 77 69
98 99 69

Output:
4
0

-----Explanation-----
In the first test we have the following sequence: 9.77, 8.09, 40.07, 38.39, 70.37, 68.69, 0.68. After last...

for _ in range(int(input())):
    dollar, cents, C = map(int, input().split())
    mx = 100*dollar + cents
    mx_i = 0
    for i in range(1,10001):
        if cents >= C:
            dollar, cents = cents - C, dollar
            if 100 * dollar + cents > mx:
                mx = 100 * dollar + cents
                mx_i = i
        else:
            dollar -= 1
            cents += 100
            dollar, cents = cents - C, dollar
            if 100 * dollar + cents > mx:
                mx = 100 * dollar + cents
                mx_i = i
        if 100 * dollar + cents < C:
            break
    print(mx_i)


Solve in Python:
You are standing on top of an amazing Himalayan mountain. The view is absolutely breathtaking! you want to take a picture on your phone, but... your memory is full again! ok, time to sort through your shuffled photos and make some space...

Given a gallery of photos, write a function to sort through your pictures.
You get a random hard disk drive full of pics, you must return an array with the 5 most recent ones PLUS the next one (same year and number following the one of the last).

You will always get at least a photo and all pics will be in the format `YYYY.imgN`

Examples:
```python
sort_photos["2016.img1","2016.img2","2015.img3","2016.img4","2013.img5"]) ==["2013.img5","2015.img3","2016.img1","2016.img2","2016.img4","2016.img5"]
sort_photos["2016.img1"]) ==["2016.img1","2016.img2"]
```

def sort_photos(pics):
    tmp = sorted((pic[:8], int(pic[8:])) for pic in pics)
    return [x+str(y) for x,y in tmp[-5:]] + [tmp[-1][0] + str(tmp[-1][1] + 1)]


Solve in Python:
You are teaching a class of $N$ students. Today, during the morning prayer, all the students are standing in a line. You are given a string $s$ with length $N$; for each valid $i$, the $i$-th character of this string is 'b' if the $i$-th student in the line is a boy or 'g' if this student is a girl.
The awkwardness of this configuration of students is defined as the sum of pairwise distances between each boy and girl. The distance between the $i$-th and $j$-th student in the line is $|i - j|$. Formally, the awkwardness is ∑i=1N∑j=i+1sj≠siN(j−i).∑i=1N∑j=i+1sj≠siN(j−i).\sum\limits_{i=1}^N \, \sum\limits_{j=i+1\\ s_j \neq s_i}^N (j - i)\,.
As the teacher, it is your responsibility to reorder the students in such a way that the awkwardness of the resulting configuration is the smallest possible. You may reorder the students in the line in any way you want. Find the minimum awkwardness that can be achieved.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains a single string $s$.

-----Output-----
For each test case, print a single line containing one integer - the minimum possible awkwardness.

-----Constraints-----
- $1 \le T \le 10^5$
- $1 \le |s| \le 10^5$
- each character of $s$ is either 'b' or 'g'
- the sum of $|s|$ over all test cases does not exceed $4 \cdot 10^6$

-----Example Input-----
3
gb
bgg
bbgg

-----Example Output-----
1
2
6

-----Explanation-----
Example case 1: The total awkwardness is $|1 - 0| = 1$, no matter how you arrange the students.
Example case 2: Initially, the awkwardness is $|1 - 0| + |2 - 0| = 1 + 2 = 3$. However, you can move the boy between the two girls, i.e. choose the configuration "gbg". Here, the awkwardness is $|1 - 0| + |2 - 1| = 1 + 1 = 2$.

def ans(x,g):
 return x*g*g+((x*(x-1))//2)*g

for _ in range(int(input())):
 s=list(input())
 g,b=s.count('g'),s.count('b')
 if g>b:
  g,b=b,g
 #print(b,g)
 n=(g-1)
 co=0
 co+=((n)*(n+1)*(2*n+1))//3
 #print(co)
 b=b-(g-1)
 #print(b,g)
 if b%2==0:
  x=b//2
  co+=2*ans(x,g)
 else:
  x,y=b//2,b//2+1
  co+=ans(x,g)+ans(y,g)
 if co<=0:print(0)
 else:print(co)


Solve in Python:
You are teaching students to generate strings consisting of unique lowercase latin characters (a-z). You give an example reference string $s$ to the students.
You notice that your students just copy paste the reference string instead of creating their own string. So, you tweak the requirements for strings submitted by the students.
Let us define a function F(s, t) where s and t are strings as the number of characters that are same in both the strings. Note that the position doesn't matter. Here are a few examples of F(s, t):
F("abc", "def") = 0
F("abc", "acb") = 3
F("back", "abcd") = 3
Now you ask your students to output a string t with lowercase unique characters of the same length as $s$, such that F(s, t) $\leq k$ where you are also given the value of $k$. If there are multiple such strings, you ask them to output the lexicographically smallest possible string. If no such string is possible, output the string "NOPE" without quotes.

-----Input:-----
- The first line will contain $T$, the number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, which contains a string $s$ and an integer $k$.

-----Output:-----
For each testcase, output in a single line the lexicographically smallest string t such that F(s, t) <= k or "NOPE" without quotes if no such string exists.

-----Constraints-----
- $1 \leq T \leq 10000$
- $1 \leq $length of string s $(|s|) \leq 26$
- $s$ only consists of characters $a$ to $z$
- There are no repeating characters in s
- $0 \leq k \leq |s|$

-----Sample Input:-----
4
helowrd 0
background 0
abcdefghijklmnopqrstuvwxyz 0
b 1

-----Sample Output:-----
abcfgij
efhijlmpqs
NOPE
a

import string

for a in range(int(input())):
 s, k = input().split()
 k = int(k)
 if 26 - len(s) + k < len(s):
  print("NOPE")
 else:
  t = ""
  f = 0
  for c in string.ascii_lowercase:
   if c in s and f < k:
    t += c
    f += 1
   elif c not in s:
    t += c
   if len(t) == len(s):
    break
  print(t)


Solve in Python:
You are the "computer expert" of a local Athletic Association (C.A.A.).
Many teams of runners come to compete. Each time you get a string of
all race results of every team who has run.
For example here is a string showing the individual results of a team of 5 runners:

` "01|15|59, 1|47|6, 01|17|20, 1|32|34, 2|3|17" `

Each part of the string is of the form: ` h|m|s `
where h, m, s (h for hour, m for minutes, s for seconds) are positive or null integer (represented as strings) with one or two digits.
There are no traps in this format.

To compare the results of the teams you are asked for giving
three statistics; **range, average and median**.

`Range` : difference between the lowest and highest values.
In {4, 6, 9, 3, 7} the lowest value is 3, and the highest is 9,
so the range is 9 − 3 = 6.

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

`Median` : In statistics, the median is the number separating the higher half
of a data sample from the lower half.
The median of a finite list of numbers can be found by arranging all
the observations from lowest value to highest value and picking the middle one
(e.g., the median of {3, 3, 5, 9, 11} is 5) when there is an odd number of observations.
If there is an even number of observations, then there is no single middle value;
the median is then defined to be the mean of the two middle values
(the median of {3, 5, 6, 9} is (5 + 6) / 2 = 5.5).

Your task is to return a string giving these 3 values.  For the example given above,
the string result will be

`"Range: 00|47|18 Average: 01|35|15 Median: 01|32|34"`

of the form:

`"Range: hh|mm|ss Average: hh|mm|ss Median: hh|mm|ss"`

where hh, mm, ss are integers (represented by strings) with *each 2 digits*.

*Remarks*:

1. if a result in seconds is ab.xy... it will be given **truncated** as ab.

2. if the given string is "" you will return ""

from statistics import mean, median

def convert_ToInt(s):
    v = s.split('|')
    return sum(int(v[i]) * 60**(2-i) for i in range(3))

def convert_ToStr(n):
    return "{:0>2}|{:0>2}|{:0>2}".format(*map(int, (n//3600, n%3600 // 60, n%60)))

def stat(strg):
    if not strg: return ""

    data = list(map(convert_ToInt, strg.split(', ')))
    return "Range: {} Average: {} Median: {}".format(*map(convert_ToStr, [max(data)-min(data), mean(data), median(data)]))


Solve in Python:
You are the Dungeon Master for a public DnD game at your local comic shop and recently you've had some trouble keeping your players' info neat and organized so you've decided to write a bit of code to help keep them sorted!

The goal of this code is to create an array of objects that stores a player's name and contact number from a given string.

The method should return an empty array if the argument passed is an empty string or `nil`/`None`/`null`.

## Examples

```ruby
player_manager("John Doe, 8167238327, Jane Doe, 8163723827") returns [{player: "John Doe", contact: 8167238327}, {player: "Jane Doe", contact: 8163723827}]
player_manager(nil) returns []
player_manager("") returns []
```
```python
player_manager("John Doe, 8167238327, Jane Doe, 8163723827") returns [{"player": "John Doe", "contact": 8167238327}, {"player": "Jane Doe", "contact": 8163723827}]
player_manager(None) returns []
player_manager("")   returns []
```
```
playerManager("John Doe, 8167238327, Jane Doe, 8163723827") returns [{player: "John Doe", contact: 8167238327}, {player: "Jane Doe", contact: 8163723827}]
playerManager(null) returns []
playerManager("")   returns []
```

Have at thee!

def player_manager(players):
    return [{'player':p.strip(), 'contact':int(c)} for p, c in zip(players.split(',')[::2], players.split(',')[1::2])] if players else []


Solve in Python:
You are the best freelancer in the city. Everybody knows you, but what they don't know, is that you are actually offloading your work to other freelancers and and you rarely need to do any work. You're living the life!

To make this process easier you need to write a method called workNeeded to figure out how much time you need to contribute to a project.

Giving the amount of time in `minutes` needed to complete the project and an array of pair values representing other freelancers' time in `[Hours, Minutes]` format ie. `[[2, 33], [3, 44]]` calculate how much time **you** will need to contribute to the project (if at all) and return a string depending on the case.

* If we need to contribute time to the project then return `"I need to work x hour(s) and y minute(s)"`
* If we don't have to contribute any time to the project then return `"Easy Money!"`

def work_needed(projectMinutes, freeLancers):
    s = projectMinutes - sum(h * 60 + m for h, m in freeLancers)
    return 'Easy Money!' if s <= 0 else 'I need to work {} hour(s) and {} minute(s)'.format(*divmod(s, 60))


Solve in Python:
You are the judge at a competitive eating competition and you need to choose a winner!

There are three foods at the competition and each type of food is worth a different amount of points.
Points are as follows:

- Chickenwings: 5 points

- Hamburgers: 3 points

- Hotdogs: 2 points

Write a function that helps you create a scoreboard.
It takes as a parameter a list of objects representing the participants, for example:
```
[
  {name: "Habanero Hillary", chickenwings: 5 , hamburgers: 17, hotdogs: 11},
  {name: "Big Bob" , chickenwings: 20, hamburgers: 4, hotdogs: 11}
]
```
It should return
"name" and "score" properties sorted by score; if scores are equals, sort alphabetically by name.
```
[
  {name: "Big Bob", score: 134},
  {name: "Habanero Hillary", score: 98}
]
```
Happy judging!

PTS = {'name': 0, 'chickenwings': 5, 'hamburgers': 3, 'hotdogs': 2}

def scoreboard(who_ate_what):
    return sorted( ({'name': d['name'],
                     'score': sum( d.get(what,0)*coef or 0 for what,coef in PTS.items())}
                    for d in who_ate_what),
                  key=lambda d: (-d['score'],d['name']))


Solve in Python:
You are the operator of a Centennial Wheel that has four gondolas, and each gondola has room for up to four people. You have the ability to rotate the gondolas counterclockwise, which costs you runningCost dollars.
You are given an array customers of length n where customers[i] is the number of new customers arriving just before the ith rotation (0-indexed). This means you must rotate the wheel i times before the customers[i] customers arrive. You cannot make customers wait if there is room in the gondola. Each customer pays boardingCost dollars when they board on the gondola closest to the ground and will exit once that gondola reaches the ground again.
You can stop the wheel at any time, including before serving all customers. If you decide to stop serving customers, all subsequent rotations are free in order to get all the customers down safely. Note that if there are currently more than four customers waiting at the wheel, only four will board the gondola, and the rest will wait for the next rotation.
Return the minimum number of rotations you need to perform to maximize your profit. If there is no scenario where the profit is positive, return -1.

Example 1:

Input: customers = [8,3], boardingCost = 5, runningCost = 6
Output: 3
Explanation: The numbers written on the gondolas are the number of people currently there.
1. 8 customers arrive, 4 board and 4 wait for the next gondola, the wheel rotates. Current profit is 4 * $5 - 1 * $6 = $14.
2. 3 customers arrive, the 4 waiting board the wheel and the other 3 wait, the wheel rotates. Current profit is 8 * $5 - 2 * $6 = $28.
3. The final 3 customers board the gondola, the wheel rotates. Current profit is 11 * $5 - 3 * $6 = $37.
The highest profit was $37 after rotating the wheel 3 times.
Example 2:
Input: customers = [10,9,6], boardingCost = 6, runningCost = 4
Output: 7
Explanation:
1. 10 customers arrive, 4 board and 6 wait for the next gondola, the wheel rotates. Current profit is 4 * $6 - 1 * $4 = $20.
2. 9 customers arrive, 4 board and 11 wait (2...

class Solution:
    def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:
        l = list()
        num_of_people = 0
        wait_people = 0
        c = 0
        for i in customers:
            c += 1
            if (i + wait_people) >= 4:
                num_of_people += 4
                wait_people = i + wait_people - 4
            else:
                num_of_people += i + wait_people
                wait_people = 0
            temp = num_of_people*boardingCost - c*runningCost
            l.append(temp)
        while(wait_people > 0):
            c += 1
            if wait_people >= 4:
                num_of_people += 4
                wait_people -= 4
            else:
                num_of_people += wait_people
                wait_people = 0
            temp = num_of_people*boardingCost - c*runningCost
            l.append(temp)
        if max(l) > 0:
            return l.index(max(l))+1
        else:
            return -1


Solve in Python:
You are the principal of the Cake school in chefland and today is your birthday. You want to treat each of the children with a small cupcake which is made by you. But there is a problem, You don't know how many students are present today.
The students have gathered of the morning assembly in $R$ rows and $C$ columns. Now you have to calculate how many cakes you have to make such that each child gets a cupcake.

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

-----Output:-----
For each test case, output number of cupcakes you have to make.

-----Constraints-----
- $1 \leq T \leq 1000$
- $2 \leq R,C \leq 10^6$

-----Sample Input:-----
1
5 10

-----Sample Output:-----
50

n = int(input())
while(n!=0):
    a,b = map(int, input().split(" "))
    print(a*b)
    n-=1


import re

def transpose(amount, tab):

    # get start and end of all frets
    fret_pos = get_all_fret_positions(tab)
    # process each column that contains frets
    pos = 0
    tab_new = ['' for string in tab]
    for fret_start in sorted(fret_pos):
        fret_end = fret_pos[fret_start]
        # get all sub strings from one column
        col = [string[fret_start:fret_end] for string in tab]
        # apply amount to all frets
        col, col_width = apply_amount(col, amount)
        if col == 'Out of frets!':
            return 'Out of frets!'
        # adjust column width
        col = adjust_column_width(col, col_width)
        # add modified column back to tablature
        for i, row in enumerate(col):
            tab_new[i] = tab_new[i] + tab[i][pos:fret_start] + row
        pos = fret_end
        # add the part after the final fret
    for i, row in enumerate(col):
        tab_new[i] = tab_new[i] + tab[i][fret_end:]

    return tab_new

def get_all_fret_positions(tab):
    fret_pos = {}
    for string in tab:
        for match in re.finditer('[0-9]+', string):
            if match.start() in fret_pos.keys():
                if fret_pos[match.start()] < match.end():
                    fret_pos[match.start()] = match.end()
            else:
                fret_pos[match.start()] = match.end()
    return fret_pos

def apply_amount(col, amount):
    col_width = 0
    for i, fret in enumerate(col):
        new_fret = re.search('[0-9]+', fret)
        if new_fret:
            new_fret = int(new_fret.group(0)) + amount
            if new_fret > 22 or new_fret < 0:
                return 'Out of frets!', None
            if len(str(new_fret)) > col_width:
                col_width = len(str(new_fret))
            col[i] = str(new_fret)
    return col, col_width

def adjust_column_width(col, col_width):
    for i, row in enumerate(col):
        if len(row) < col_width:
            col[i] = col[i] + '-' * (col_width - len(row))
        if len(row) > col_width:
            col[i] =...


Solve in Python:
You are trying to cross a river by jumping along stones. Every time you land on a stone, you hop forwards by the value of that stone. If you skip *over* a stone then its value doesn't affect you in any way. Eg:

```
 x--x-----x-->
[1][2][5][1]

```

Of course, crossing from the other side might give you a different answer:

```
 <--------x--x
   [1][2][5][1]

```

Given an array of positive integers, return the total number of steps it would take to go all the way across the river (and past the end of the array) and then all the way back. All arrays will contain at least one element, and may contain up to 100 elements.

### Examples

```
  x--x-----x-->
 [1][2][1][2]
<----x-----x

therefore hop_across([1,2,1,2]) = 3 + 2 = 5

   x-----x--------x------>
  [2][2][3][1][1][2][1]
<--------x--x-----x--x

therefore hop_across([2,2,3,1,1,2,1]) = 3 + 4 = 7

```

def hop_across(lst): return dist(lst)+dist(lst[::-1])

def dist(lst):
    s,i=0,0
    while i<len(lst): i+=lst[i]; s+=1
    return s


Solve in Python:
You are working at a lower league football stadium and you've been tasked with automating the scoreboard.

The referee will shout out the score, you have already set up the voice recognition module which turns the ref's voice into a string, but the spoken score needs to be converted into a pair for the scoreboard!

e.g. `"The score is four nil"` should return `[4,0]`

Either teams score has a range of 0-9, and the ref won't say the same string every time e.g.

    "new score: two three"

    "two two"

    "Arsenal just conceded another goal, two nil"

Note:
```python
Please return an array
```

Please rate and enjoy!

def scoreboard(announcement):
    '''Return scores as numbers from announcement'''
    numbers = {
        'nil': 0,
        'one': 1,
        'two': 2,
        'three': 3,
        'four': 4,
        'five': 5,
        'six': 6,
        'seven': 7,
        'eight': 8,
        'nine': 9
    }
    # scores are the last two words in the referee's announcement
    scores = announcement.split()[-2:]
    return [numbers[score] for score in scores]


Solve in Python:
You are working for the Gryzzl company, headquartered in Pawnee, Indiana.

The new national park has been opened near Pawnee recently and you are to implement a geolocation system, so people won't get lost. The concept you developed is innovative and minimalistic. There will be $n$ antennas located somewhere in the park. When someone would like to know their current location, their Gryzzl hologram phone will communicate with antennas and obtain distances from a user's current location to all antennas.

Knowing those distances and antennas locations it should be easy to recover a user's location... Right? Well, almost. The only issue is that there is no way to distinguish antennas, so you don't know, which distance corresponds to each antenna. Your task is to find a user's location given as little as all antennas location and an unordered multiset of distances.

-----Input-----

The first line of input contains a single integer $n$ ($2 \leq n \leq 10^5$) which is the number of antennas.

The following $n$ lines contain coordinates of antennas, $i$-th line contain two integers $x_i$ and $y_i$ ($0 \leq x_i,y_i \leq 10^8$). It is guaranteed that no two antennas coincide.

The next line of input contains integer $m$ ($1 \leq n \cdot m \leq 10^5$), which is the number of queries to determine the location of the user.

Following $m$ lines contain $n$ integers $0 \leq d_1 \leq d_2 \leq \dots \leq d_n \leq 2 \cdot 10^{16}$ each. These integers form a multiset of squared distances from unknown user's location $(x;y)$ to antennas.

For all test cases except the examples it is guaranteed that all user's locations $(x;y)$ were chosen uniformly at random, independently from each other among all possible integer locations having $0 \leq x, y \leq 10^8$.

-----Output-----

For each query output $k$, the number of possible a user's locations matching the given input and then output the list of these locations in lexicographic order.

It is guaranteed that the sum of all $k$ over all points does not exceed...

import sys
import math

n = int(input())

x = [0]*n
y = [0]*n

for i in range(n):
    x[i], y[i] = list(map(int, input().split()))

sx = sum(x)
sy = sum(y)

for i in range(n):
    x[i] = n * x[i] - sx
    y[i] = n * y[i] - sy

m = int(input())

d = [0]*n
e = [0]*n

HD = 0

def check(a, b):
    nonlocal HD
    HE = 0
    for i in range(n):
        HE ^= hash((a-x[i])*(a-x[i])+(b-y[i])*(b-y[i]))
    return HD == HE

def sqrt(x):
    nn = int(x)
    if nn == 0:
        return 0
    fa, fb = divmod(nn.bit_length(), 2)
    x = 2**(fa+fb)
    while True:
        y = (x + nn//x)//2
        if y >= x:
            return x
        x = y

def hash(x):
    return x * 9991 + 43

pans = []

def solve():
    nonlocal d
    d = list(map(int, input().split()))
    c = 0
    d = [p * n * n for p in d]
    for i in range(n):
        c += d[i] - x[i] * x[i] - y[i] * y[i]

    assert(c % n == 0)
    c //= n
    ans = []
    ax = x[0]
    ay = y[0]
    if ax is 0 and ay is 0:
        ax = x[1]
        ay = y[1]
    rev = 0
    if ay == 0:
        ay = ax
        ax = 0
        rev = 1
    d.sort()
    nonlocal HD
    HD = 0
    for p in d:
        HD ^= hash(p)
    old = -1
    for p in d:
        if (p == old):
            continue
        old = p
        a = c + ax * ax + ay * ay - p
        if (a % 2 != 0):
            continue
        a //= 2
        A = ax * ax + ay * ay
        B = a * ax
        C = a * a - ay * ay * c
        D = B * B - A * C
        if (D < 0):
            continue
        sD = sqrt(D)
        if D != sD * sD:
            continue
        if (B + sD) % A == 0:
            qx = (B + sD) // A
            qy = (a - ax * qx) // ay
            if rev:
                t = qx
                qx = qy
                qy = t
            if ((qx + sx) % n == 0 and (qy + sy) % n == 0 and check(qx, qy)):
                qx = (qx + sx) // n
                qy = (qy + sy) // n
                ans.append([qx, qy])
        if sD == 0:
            continue
        if (B - sD) % A == 0:
            qx = (B - sD) // A
...


Solve in Python:
You came across this story while reading a book. Long a ago when the modern entertainment systems did not exist people used to go to watch plays in theaters, where people would perform live in front of an audience. There was a beautiful actress who had a disability she could not pronounce the character $'r'$. To win her favours which many have been denied in past, you decide to write a whole play without the character $'r'$. Now you have to get the script reviewed by the editor before presenting it to her.
The editor was flattered by the script and agreed to you to proceed. The editor will edit the script in this way to suit her style. For each word replace it with a sub-sequence of itself such that it contains the character 'a'.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements Wikipedia
Now given a script with $N$ words, for each word in the script you wish to know the number of subsequences with which it can be replaced.

-----Input:-----
- First-line will contain $N$, the number of words in the script. Then next $N$ line with one test case each.
- Each test case contains a single word $W_i$

-----Output:-----
For each test case, output in a single line number of subsequences with which it can be replaced.

-----Constraints-----
- $1 \leq N \leq 1000$
- $1 \leq$ length of $W_i$  $\leq 20$
- $W_i$  on contains lowercase english alphabets and does not have the character 'r'

-----Sample Input 1:-----
2
abc
aba

-----Sample Output 1:-----
4
6

-----EXPLANATION:-----
This subsequences with which $abc$ can be replaed : ${a,ab,ac,abc}$.
This subsequences with which $aba$ can be replaed : ${a,ab,aba,a,ba,a}$.

-----Sample Input 2:-----
3
abcde
abcdea
xyz

-----Sample Output 2:-----
16
48
0

# cook your dish here
t=int(input())
for _ in range(t):
    stringa=input()
    a=0
    counter=0
    for char in stringa:
        if char=='a':
            a+=1
    print(2**(len(stringa)-a)*(2**a-1))


Solve in Python:
You can print your name on a billboard ad. Find out how much it will cost you. Each letter has a default price of £30, but that can be different if you are given 2 parameters instead of 1.

You can not use multiplier "*" operator.

If your name would be Jeong-Ho Aristotelis, ad would cost £600.
20 leters * 30 = 600 (Space counts as a letter).

def billboard(name, price = 30):
    cost = 0
    print(name)
    for i in range(len(name)):
        cost += price
    return cost
    #your code here - note that in Python we cannot prevent the use of the
    #multiplication, but try not to be lame and solve the kata in another way!


Solve in Python:
You certainly can tell which is the larger number between 2^(10) and 2^(15).

But what about, say, 2^(10) and 3^(10)? You know this one too.

Things tend to get a bit more complicated with **both** different bases and exponents: which is larger between 3^(9) and 5^(6)?

Well, by now you have surely guessed that you have to build a function to compare powers, returning -1 if the first member is larger, 0 if they are equal, 1 otherwise; powers to compare will be provided in the `[base, exponent]` format:
```python
compare_powers([2,10],[2,15])==1
compare_powers([2,10],[3,10])==1
compare_powers([2,10],[2,10])==0
compare_powers([3,9],[5,6])==-1
compare_powers([7,7],[5,8])==-1
```
```if:nasm
int compare_powers(const int n1[2], const int n2[2])
```
Only positive integers will be tested, incluing bigger numbers - you are warned now, so be diligent try to implement an efficient solution not to drain too much on CW resources ;)!

from math import log

def compare_powers(*numbers):
    a,b = map(lambda n: n[1]*log(n[0]), numbers)
    return (a<b) - (a>b)


Solve in Python:
You drop a ball from a given height. After each bounce, the ball returns to some fixed proportion of its previous height. If the ball bounces to height 1 or less, we consider it to have stopped bouncing. Return the number of bounces it takes for the ball to stop moving.

```
bouncingBall(initialHeight, bouncingProportion)

boucingBall(4, 0.5)
After first bounce, ball bounces to height 2
After second bounce, ball bounces to height 1
Therefore answer is 2 bounces

boucingBall(30, 0.3)
After first bounce, ball bounces to height 9
After second bounce, ball bounces to height 2.7
After third bounce, ball bounces to height 0.81
Therefore answer is 3 bounces

```

Initial height is an integer in range [2,1000]

Bouncing Proportion is a decimal in range [0, 1)

def bouncing_ball(initial, proportion):
    count = 0
    while initial > 1:
        initial = initial * proportion
        count = count + 1
    return count


Solve in Python:
You get a "text" and have to shift the vowels by "n" positions to the right.
(Negative value for n should shift to the left.)
"Position" means the vowel's position if taken as one item in a list of all vowels within the string.
A shift by 1 would mean, that every vowel shifts to the place of the next vowel.
Shifting over the edges of the text should continue at the other edge.

Example:

text = "This is a test!"
n = 1
output = "Thes is i tast!"

text = "This is a test!"
n = 3
output = "This as e tist!"

If text is null or empty return exactly this value.
Vowels are "a,e,i,o,u".

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

I have created other katas. Have a look if you like coding and challenges.

import re
from collections import deque

def vowel_shift(text,n):
    try:
        tokens = re.split(r'([aeiouAEIOU])', text)
        if len(tokens) > 1:
            vowels = deque(tokens[1::2])
            vowels.rotate(n)
            tokens[1::2] = vowels
        return ''.join(tokens)
    except TypeError:
        return None


Solve in Python:
You get a new job working for Eggman Movers.  Your first task is to write a method that will allow the admin staff to enter a person’s name and return what that person's role is in the company.

You will be given an array of object literals holding the current employees of the company.  You code must find the employee with the matching firstName and lastName and then return the role for that employee or if no employee is not found it should return "Does not work here!"

The array is preloaded and can be referenced using the variable `employees` (`$employees` in Ruby). It uses the following structure.

```python
employees = [ {'first_name': "Dipper", 'last_name': "Pines", 'role': "Boss"}, ...... ]
```

There are no duplicate names in the array and the name passed in will be a single string with a space between the first and last name i.e. Jane Doe or just a name.

employees = [{'first_name': 'Ollie', 'last_name': 'Hepburn', 'role': 'Boss'}, {'first_name': 'Morty', 'last_name': 'Smith', 'role': 'Truck Driver'}, {'first_name': 'Peter', 'last_name': 'Ross', 'role': 'Warehouse Manager'}, {'first_name': 'Cal', 'last_name': 'Neil', 'role': 'Sales Assistant'}, {'first_name': 'Jesse', 'last_name': 'Saunders', 'role': 'Admin'}, {'first_name': 'Anna', 'last_name': 'Jones', 'role': 'Sales Assistant'}, {'first_name': 'Carmel', 'last_name': 'Hamm', 'role': 'Admin'}, {'first_name': 'Tori', 'last_name': 'Sparks', 'role': 'Sales Manager'}, {'first_name': 'Peter', 'last_name': 'Jones', 'role': 'Warehouse Picker'}, {'first_name': 'Mort', 'last_name': 'Smith', 'role': 'Warehouse Picker'}, {'first_name': 'Anna', 'last_name': 'Bell', 'role': 'Admin'}, {'first_name': 'Jewel', 'last_name': 'Bell', 'role': 'Receptionist'}, {'first_name': 'Colin', 'last_name': 'Brown', 'role': 'Trainee'}]
def find_employees_role(name):
    for e in employees:
        if e['first_name'] + ' ' + e['last_name'] == name:
            return e['role']
    else:
        return 'Does not work here!'


Solve in Python:
You get an array of different numbers to sum up. But there is one problem, those numbers all have different bases.
For example:
```python
You get an array of numbers with their base as an input:

[["101",16],["7640",8],["1",9]]
```

The output should be the sum as an integer value with a base of 10, so according to the example this would be:

4258
```python
A few more examples:
[["101",2], ["10",8]] --> 13
[["ABC",16], ["11",2]] --> 2751
```
Bases can be between 2 and 36 (2<=base<=36)

def sum_it_up(numbers_with_bases):
    return sum(int(*ls) for ls in numbers_with_bases)


Solve in Python:
You get an array of numbers, return the sum of all of the positives ones.

Example `[1,-4,7,12]` => `1 + 7 + 12 = 20`

Note: if there is nothing to sum, the sum is default to `0`.

def positive_sum(arr):
    sum = 0
    for el in arr:
        if el > 0:
            sum += int(el)
    return sum


def define_suit(card):
    if card[-1] is 'C':
        return 'clubs'
    elif card[-1] is 'S':
        return 'spades'
    elif card[-1] is 'D':
        return 'diamonds'
    elif card[-1] is 'H':
        return 'hearts'


Solve in Python:
You get some nested lists. Keeping the original structures, sort only elements (integers) inside of the lists. In other words, sorting the intergers only by swapping their positions.

```
Example
Input   : [[[2, 1], [4, 3]], [[6, 5], [8, 7]]]
Output  : [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
```

Note:
The structures of the lists are regular (symmetrical) and their depths are 3.

from copy import deepcopy

def sort_nested_list(a):

    def seeker(lst):
        return lst if not lst or not isinstance(lst[0], list) else sum(map(seeker, lst), [])

    def putter(lst):
        for i in range(len(lst)):
            if isinstance(lst[i],list):
                putter(lst[i])
            else:
                lst[i] = next(elts)

    a, elts = deepcopy(a), iter(sorted(seeker(a)))
    putter(a)
    return a


Solve in Python:
You have $n$ barrels lined up in a row, numbered from left to right from one. Initially, the $i$-th barrel contains $a_i$ liters of water.

You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels $x$ and $y$ (the $x$-th barrel shouldn't be empty) and pour any possible amount of water from barrel $x$ to barrel $y$ (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them.

Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $k$ times.

Some examples:   if you have four barrels, each containing $5$ liters of water, and $k = 1$, you may pour $5$ liters from the second barrel into the fourth, so the amounts of water in the barrels are $[5, 0, 5, 10]$, and the difference between the maximum and the minimum is $10$;  if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still $0$.

-----Input-----

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

The first line of each test case contains two integers $n$ and $k$ ($1 \le k < n \le 2 \cdot 10^5$) — the number of barrels and the number of pourings you can make.

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^{9}$), where $a_i$ is the initial amount of water the $i$-th barrel has.

It's guaranteed that the total sum of $n$ over test cases doesn't exceed $2 \cdot 10^5$.

-----Output-----

For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $k$ times.

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

Output
10
0

"""T=int(input())
for _ in range(0,T):
    n=int(input())
    a,b=map(int,input().split())
    s=input()
    s=[int(x) for x in input().split()]
    for i in range(0,len(s)):
        a,b=map(int,input().split())"""

T=int(input())
for _ in range(0,T):
    n,k=list(map(int,input().split()))
    s=[int(x) for x in input().split()]
    s.sort()
    s=s[::-1]
    for i in range(1,min(k+1,len(s))):
        s[0]+=s[i]

    print(s[0])


Solve in Python:
You have $n$ gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The $i$-th gift consists of $a_i$ candies and $b_i$ oranges.

During one move, you can choose some gift $1 \le i \le n$ and do one of the following operations:

  eat exactly one candy from this gift (decrease $a_i$ by one);  eat exactly one orange from this gift (decrease $b_i$ by one);  eat exactly one candy and exactly one orange from this gift (decrease both $a_i$ and $b_i$ by one).

Of course, you can not eat a candy or orange if it's not present in the gift (so neither $a_i$ nor $b_i$ can become less than zero).

As said above, all gifts should be equal. This means that after some sequence of moves the following two conditions should be satisfied: $a_1 = a_2 = \dots = a_n$ and $b_1 = b_2 = \dots = b_n$ (and $a_i$ equals $b_i$ is not necessary).

Your task is to find the minimum number of moves required to equalize all the given gifts.

You have to answer $t$ independent test cases.

-----Input-----

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

The first line of the test case contains one integer $n$ ($1 \le n \le 50$) — the number of gifts. The second line of the test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$), where $a_i$ is the number of candies in the $i$-th gift. The third line of the test case contains $n$ integers $b_1, b_2, \dots, b_n$ ($1 \le b_i \le 10^9$), where $b_i$ is the number of oranges in the $i$-th gift.

-----Output-----

For each test case, print one integer: the minimum number of moves required to equalize all the given gifts.

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

Output
6
16
0
4999999995
7

-----Note-----

In the first test case of the example, we can perform the following sequence...

for _ in range(int(input())):
    n = int(input())
    a = [int(x) for x in input().split()]
    b = [int(x) for x in input().split()]
    am =  min(a)
    bm = min(b)
    ans = 0
    for i in range(n):
        ans += max(b[i]-bm,a[i]-am)
    print(ans)


Solve in Python:
You have 4 cards each containing a number from 1 to 9.  You need to judge whether they could operated through *, /, +, -, (, ) to get the value of 24.

Example 1:

Input: [4, 1, 8, 7]
Output: True
Explanation: (8-4) * (7-1) = 24

Example 2:

Input: [1, 2, 1, 2]
Output: False

Note:

The division operator / represents real division, not integer division.  For example, 4 / (1 - 2/3) = 12.
Every operation done is between two numbers.  In particular, we cannot use - as a unary operator.  For example, with [1, 1, 1, 1] as input, the expression -1 - 1 - 1 - 1 is not allowed.
You cannot concatenate numbers together.  For example, if the input is [1, 2, 1, 2], we cannot write this as 12 + 12.

class Solution:
     def judgePoint24(self, nums):
         """
         :type nums: List[int]
         :rtype: bool
         """
         bad = '对撒剘劥圞剜劏哱掶桺泛揋掵従剟剣彫寣污悫壛梄甏咍哲汭剤堧点卋嬞勆叛汬泐塵栋劚嚮咃宠吖剗楗囧力桻攋壯劯嗏桹劙剢剚焧啫栕炸栫栖嚲彳剛撑烃洿宋汷彲剙揁妷埻撧汢吩壙劇剭埼吕剝汣敯憇勇剥咎囻匓'
         return chr(int(''.join(map(str, sorted(nums)))) + 19968) not in bad


Solve in Python:
You have a bag of size $n$. Also you have $m$ boxes. The size of $i$-th box is $a_i$, where each $a_i$ is an integer non-negative power of two.

You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.

For example, if $n = 10$ and $a = [1, 1, 32]$ then you have to divide the box of size $32$ into two parts of size $16$, and then divide the box of size $16$. So you can fill the bag with boxes of size $1$, $1$ and $8$.

Calculate the minimum number of divisions required to fill the bag of size $n$.

-----Input-----

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

The first line of each test case contains two integers $n$ and $m$ ($1 \le n \le 10^{18}, 1 \le m \le 10^5$) — the size of bag and the number of boxes, respectively.

The second line of each test case contains $m$ integers $a_1, a_2, \dots , a_m$ ($1 \le a_i \le 10^9$) — the sizes of boxes. It is guaranteed that each $a_i$ is a power of two.

It is also guaranteed that sum of all $m$ over all test cases does not exceed $10^5$.

-----Output-----

For each test case print one integer — the minimum number of divisions required to fill the bag of size $n$ (or $-1$, if it is impossible).

-----Example-----
Input
3
10 3
1 32 1
23 4
16 1 4 1
20 5
2 1 16 1 8

Output
2
-1
0

import sys
import math
from collections import defaultdict
from collections import deque
from itertools import combinations
from itertools import permutations
input = lambda : sys.stdin.readline().rstrip()
read = lambda : list(map(int, input().split()))
go = lambda : 1/0
def write(*args, sep="\n"):
  for i in args:
    sys.stdout.write("{}{}".format(i, sep))
INF = float('inf')
MOD = int(1e9 + 7)
YES = "YES"
NO = -1

for _ in range(int(input())):
  try:
    n, m = read()
    arr = read()
    x = [0] * 65

    if sum(arr) < n:
      print(NO)
      go()

    for i in arr:
      x[int(math.log2(i))] += 1

    ans = 0
    for i in range(65):
      if (1 << i) & n:
        if x[i] != 0:
          x[i] -= 1
          continue

        total = 0
        for j in range(i):
          total += (1 << j) * x[j]

        if total >= (1 << i):
          temp = 1 << i
          for j in reversed(range(i)):
            while temp - (1 << j) >= 0 and x[j] > 0:
              temp -= 1 << j
              x[j] -= 1
          continue

        j = i
        while j < 65 and x[j] == 0:
          j += 1
        if j == 65:
          print(NO)
          go()
        else:
          x[j] -= 1
          for k in range(i, j):
            x[k] += 1
          ans += (j - i)

    print(ans)

  except ZeroDivisionError:
    continue

  except Exception as e:
    print(e)
    continue