Solve in Python:
Alice and Bob created $N$ and $M$ recipes, respectively ($N, M \ge 1$), and submitted them to Chef for evaluation. Each recipe is represented by a string containing only lowercase English letters. Let's denote Alice's recipes by $A_1, A_2, \ldots, A_N$ and Bob's recipes by $B_1, B_2, \ldots, B_M$.
Accidentally, Chef mixed up those recipes ― now, he has $L = N+M$ recipes in a sequence $S_1, S_2, \ldots, S_L$. Thankfully, the recipes created by Alice and Bob are distinguishable from each other. It is well-known that for each recipe $s$ created by Alice, the following property holds, and for each recipe created by Bob, it does not hold: For each $1 \le l < r \le |s|$, the substring $s_l, s_{l+1}, \ldots, s_r$ contains at least as many vowels as consonants. The letters 'a', 'e', 'i', 'o', 'u' are vowels, while the other letters are consonants.
The score of a candidate who made $K$ recipes is calculated as the product of $\frac{x_c}{fx_c^K}$ for all letters $c$ that occur in at least one of these recipes; here, $x_c$ is the number of recipes which contain the letter $c$ and $fx_c$ is the total number of occurrences of this letter in all $K$ recipes.
Let's denote the scores of Alice and Bob by $sc_A$ and $sc_B$ respectively. Chef wants to know their ratio $sc_A/sc_B$. We know that Chef is a legendary cook, but he is not very good at calculating, so he is asking you to find that number.

-----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 $L$.
- $L$ lines follow. For each valid $i$, the $i$-th of these lines contains a single string $S_i$.

-----Output-----
For each test case, if the ratio of scores exceeds $10^7$, print a single line containing the string "Infinity" (without quotes); otherwise, print a single line containing one real number $sc_A/sc_B$.
Your answer will be considered correct if its absolute or relative error does not exceed $10^{-6}$. It...

# v = ["a","e","i","o","u"]
# for _ in range(int(input())):
#   n = int(input())
#   a,b = [],[]
#   for i in range(n):
#       s = input()
#       isa = True
#       for j in range(1,len(s) - 1):
#           if(s[j] in v):
#               if(s[j - 1] not in v and s[j + 1] not in v):
#                   isa = False
#           else:
#               if(s[j - 1] not in v or s[j + 1] not in v):
#                   isa = False
#           if(not isa):
#               break
#       if(s[0] not in v and s[1] not in v):
#           isa = False
#       if(s[-1] not in v and s[-2] not in v):
#           isa = False
#       if(isa):
#           a.append(s)
#       else:
#           b.append(s)
#   dicta,dictb = {},{}
#   for i in a:
#       freq = {}
#       for j in i:
#           if(j in freq):
#               freq[j] += 1
#           else:
#               freq[j] = 1
#       for j in freq:
#           if(j not in dicta):
#               dicta[j] = (1,freq[j])
#           else:
#               dicta[j] = (dicta[j][0] + 1,dicta[j][1] + freq[j])
#   for i in b:
#       freq = {}
#       for j in i:
#           if(j in freq):
#               freq[j] += 1
#           else:
#               freq[j] = 1
#       for j in freq:
#           if(j not in dictb):
#               dictb[j] = (1,freq[j])
#           else:
#               dictb[j] = (dictb[j][0] + 1,dictb[j][1] + freq[j])
#   ans = 1
#   for i in dicta:
#       ans *= dicta[i][0]
#   for i in dictb:
#       ans /= dictb[i][0]
#   x,y = 1,1
#   for i in dictb:
#       x *= dictb[i][1]
#   for i in dicta:
#       y *= dicta[i][1]
#   alice,bob = len(a),len(b)
#   for i in range(bob):
#       while(alice > 0 and ans > 10**7):
#           ans /= y
#           alice -= 1
#       ans *= x
#       if(ans > 10**7 and alice == 0):
#           break
#   while(alice > 0):
#       ans /= y
#       if(ans < 1 and alice > 100):
#           ans = 0
#           break
#       alice -= 1
#   if(ans > 10**7):
#       print("Infinity")
#   else:
#       print(ans)
# #partailly correct...


Solve in Python:
Alice and Bob have an undirected graph of n nodes and 3 types of edges:

Type 1: Can be traversed by Alice only.
Type 2: Can be traversed by Bob only.
Type 3: Can by traversed by both Alice and Bob.

Given an array edges where edges[i] = [typei, ui, vi] represents a bidirectional edge of type typei between nodes ui and vi, find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes.
Return the maximum number of edges you can remove, or return -1 if it's impossible for the graph to be fully traversed by Alice and Bob.

Example 1:

Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]]
Output: 2
Explanation: If we remove the 2 edges [1,1,2] and [1,1,3]. The graph will still be fully traversable by Alice and Bob. Removing any additional edge will not make it so. So the maximum number of edges we can remove is 2.

Example 2:

Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]]
Output: 0
Explanation: Notice that removing any edge will not make the graph fully traversable by Alice and Bob.

Example 3:

Input: n = 4, edges = [[3,2,3],[1,1,2],[2,3,4]]
Output: -1
Explanation: In the current graph, Alice cannot reach node 4 from the other nodes. Likewise, Bob cannot reach 1. Therefore it's impossible to make the graph fully traversable.

Constraints:

1 <= n <= 10^5
1 <= edges.length <= min(10^5, 3 * n * (n-1) / 2)
edges[i].length == 3
1 <= edges[i][0] <= 3
1 <= edges[i][1] < edges[i][2] <= n
All tuples (typei, ui, vi) are distinct.

class DSU:
    def __init__(self, n):
        self.parent = [x for x in range(n)]
        self.rank = [0] * n

    def find(self, x):
        if self.parent[x] != x:
            self.parent[x] = self.find(self.parent[x])
        return self.parent[x]

    def union(self, x, y):
        px, py = self.find(x), self.find(y)
        if px == py:
            return False
        else:
            if self.rank[px] > self.rank[py]:
                self.parent[py] = px
            elif self.rank[py] > self.rank[px]:
                self.parent[px] = py
            else:
                self.parent[px] = py
                self.rank[px] += 1
            return True

class Solution:
    def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:
        dsu1, dsu2 = DSU(n), DSU(n)
        ans = 0
        for t, u, v in edges:
            if t == 3:
                if not dsu1.union(u - 1, v - 1) or not dsu2.union(u - 1, v - 1):
                    ans += 1

        for t, u, v in edges:
            if t == 1 and not dsu1.union(u - 1, v - 1):
                ans += 1
            if t == 2 and not dsu2.union(u - 1, v - 1):
                ans += 1

        p1, p2 = dsu1.find(0), dsu2.find(0)
        for i in range(n):
            if p1 != dsu1.find(i) or p2 != dsu2.find(i):
                return -1
        return ans


Solve in Python:
Alice and Bob have participated to a Rock Off with their bands. A jury of true metalheads rates the two challenges, awarding points to the bands on a scale from 1 to 50 for three categories: Song Heaviness, Originality, and Members' outfits.

For each one of these 3 categories they are going to be awarded one point, should they get a better judgement from the jury. No point is awarded in case of an equal vote.

You are going to receive two arrays, containing first the score of Alice's band and then those of Bob's. Your task is to find their total score by comparing them in a single line.

Example:

Alice's band plays a Nirvana inspired grunge and has been rated
``20`` for Heaviness,
``32`` for Originality and only
``18`` for Outfits.
Bob listens to Slayer and has gotten a good
``48`` for Heaviness,
``25`` for Originality and a rather honest
``40`` for Outfits.

The total score should be followed by a colon ```:``` and by one of the following quotes:
if Alice's band wins: ```Alice made "Kurt" proud!```
if Bob's band wins: ```Bob made "Jeff" proud!```
if they end up with a draw: ```that looks like a "draw"! Rock on!```

The solution to the example above should therefore appear like
``'1, 2: Bob made "Jeff" proud!'``.

def solve(a, b):
    c1=0
    c2=0
    for i in range(len(a)):
        if (a[i]>b[i]):
            c1+=1
        elif (a[i]==b[i]):
            pass
        else:
            c2+=1
    if(c1==c2):
        return("{}, {}: that looks like a \"draw\"! Rock on!".format(c1,c2))
    elif(c1>c2):
        return("{}, {}: Alice made \"Kurt\" proud!".format(c1,c2))
    else:
        return("{}, {}: Bob made \"Jeff\" proud!".format(c1,c2))


Solve in Python:
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.

During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.

For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold):  $\textbf{1}0110 \to 0110$;  $1\textbf{0}110 \to 1110$;  $10\textbf{1}10 \to 1010$;  $101\textbf{1}0 \to 1010$;  $10\textbf{11}0 \to 100$;  $1011\textbf{0} \to 1011$.

After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.

The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.

Each player wants to maximize their score. Calculate the resulting score of Alice.

-----Input-----

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

Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).

-----Output-----

For each test case, print one integer — the resulting score of Alice (the number of $1$-characters deleted by her).

-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111

Output
4
0
6
3
6

-----Note-----

Questions about the optimal strategy will be ignored.

for _ in range (int(input())):
    s=input()
    a = []
    flag = 0
    count = 0
    for i in range (len(s)):
        if s[i]=='1':
            count+=1
        else:
            a.append(count)
            count=0
        if i==len(s)-1 and count!=0:
            a.append(count)
    a.sort(reverse=True)
    ans = 0
    for i in range(len(a)):
        if i%2==0:
            ans+=a[i]
    print(ans)


Solve in Python:
Alice and Bob take turns playing a game, with Alice starting first.
Initially, there are n stones in a pile.  On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile.
Also, if a player cannot make a move, he/she loses the game.
Given a positive integer n. Return True if and only if Alice wins the game otherwise return False, assuming both players play optimally.

Example 1:
Input: n = 1
Output: true
Explanation: Alice can remove 1 stone winning the game because Bob doesn't have any moves.
Example 2:
Input: n = 2
Output: false
Explanation: Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0).
Example 3:
Input: n = 4
Output: true
Explanation: n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0).

Example 4:
Input: n = 7
Output: false
Explanation: Alice can't win the game if Bob plays optimally.
If Alice starts removing 4 stones, Bob will remove 1 stone then Alice should remove only 1 stone and finally Bob removes the last one (7 -> 3 -> 2 -> 1 -> 0).
If Alice starts removing 1 stone, Bob will remove 4 stones then Alice only can remove 1 stone and finally Bob removes the last one (7 -> 6 -> 2 -> 1 -> 0).
Example 5:
Input: n = 17
Output: false
Explanation: Alice can't win the game if Bob plays optimally.

Constraints:

1 <= n <= 10^5

def canWin(n,squares,memo):

    if n in squares:
        #print(n,True)
        return True

    if n in memo:
        return memo[n]

    res = False
    for i in reversed(squares):
        if i>n: continue
        #if n==13: print('here',n-i)
        if not canWin(n-i,squares,memo):
            res = True
            break

    memo[n] = res
    return res

class Solution:
    def winnerSquareGame(self, n: int) -> bool:
        squares = [i**2 for i in range(1,floor(sqrt(n))+1)]
        memo = dict()
        #print(squares)
        return canWin(n,squares,memo)


Solve in Python:
Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number N on the chalkboard.  On each player's turn, that player makes a move consisting of:

Choosing any x with 0 < x < N and N % x == 0.
Replacing the number N on the chalkboard with N - x.

Also, if a player cannot make a move, they lose the game.
Return True if and only if Alice wins the game, assuming both players play optimally.

Example 1:
Input: 2
Output: true
Explanation: Alice chooses 1, and Bob has no more moves.

Example 2:
Input: 3
Output: false
Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves.

Note:

1 <= N <= 1000

class Solution:

    #this function will return all the possible nums after one move

    def divisorGame(self, N: int) -> bool:

        return N & 1 == 0


Solve in Python:
Alice and Johnny are playing a simple guessing game. Johnny picks an arbitrary positive integer n (1<=n<=109) and gives Alice exactly k hints about the value of n. It is Alice's task to guess n, based on the received hints.

Alice often has a serious problem guessing the value of n, and she's beginning to suspect that Johnny occasionally cheats, that is, gives her incorrect hints.
After the last game, they had the following little conversation:

- [Alice] Johnny, you keep cheating!

- [Johnny] Indeed? You cannot prove it.

- [Alice] Oh yes I can. In fact, I can tell you with the utmost certainty that in the last game you lied to me at least *** times.

So, how many times at least did Johnny lie to Alice? Try to determine this, knowing only the hints Johnny gave to Alice.

-----Input-----
The first line of input contains t, the number of test cases (about 20). Exactly t test cases follow.

Each test case starts with a line containing a single integer k, denoting the number of hints given by Johnny (1<=k<=100000). Each of the next k lines contains exactly one hint. The i-th hint is of the form:
operator li logical_value
where operator denotes one of the symbols < , > , or =; li is an integer (1<=li<=109), while logical_value is one of the words: Yes or No. The hint is considered correct if logical_value is the correct reply to the question: "Does the relation: n operator li hold?", and is considered to be false (a lie) otherwise.

-----Output-----
For each test case output a line containing a single integer, equal to the minimal possible number of Johnny's lies during the game.

-----Example-----
Input:
3
2
< 100 No
> 100 No
3
< 2 Yes
> 4 Yes
= 3 No
6
< 2 Yes
> 1 Yes
= 1 Yes
= 1 Yes
> 1 Yes
= 1 Yes

Output:
0
1
2

Explanation: for the respective test cases, the number picked by Johnny could have been e.g. n=100, n=5, and n=1.

# cook your dish here
def guessingGame (l):
 a = []
 m = 1000000001
 for i in range (len(l)):
  k=int(l[i][1])
  if (l[i][0]=='<' and l[i][2]=='Yes'):
   a.append((1,1))
   a.append((k,-1))

  if (l[i][0]=='<' and l[i][2]=='No'):
   a.append((k,1))
   a.append((m,-1))

  if (l[i][0]=='=' and l[i][2]=='Yes'):
   a.append((k,1))
   a.append((k+1,-1))

  if (l[i][0]=='=' and l[i][2]=='No'):
   a.append((1,1))
   a.append((k,-1))
   a.append((k+1,1))
   a.append((m,-1))

  if (l[i][0]=='>' and l[i][2]=='Yes'):
   a.append((k+1,1))
   a.append((m,-1))

  if (l[i][0]=='>' and l[i][2]=='No'):
   a.append((1,1))
   a.append((k+1,-1))

 a.sort()
 w=0
 r=0

 for i in range (len(a)):
  w+=a[i][1]
  r=max(w,r)

 return len(l)-r

def __starting_point():

 T = int(input())
 answer = []

 for _ in range (T):
  e = int(input())
  temp = []
  for q_t in range (e):
   q = list(map(str,input().rstrip().split()))
   temp.append(q)
  result = guessingGame(temp)
  print(result)
__starting_point()


Solve in Python:
Alice has a hand of cards, given as an array of integers.
Now she wants to rearrange the cards into groups so that each group is size W, and consists of W consecutive cards.
Return true if and only if she can.

Example 1:
Input: hand = [1,2,3,6,2,3,4,7,8], W = 3
Output: true
Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8].
Example 2:
Input: hand = [1,2,3,4,5], W = 4
Output: false
Explanation: Alice's hand can't be rearranged into groups of 4.

Constraints:

1 <= hand.length <= 10000
0 <= hand[i] <= 10^9
1 <= W <= hand.length

Note: This question is the same as 1296: https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/

class Solution:
    def isNStraightHand(self, hand: List[int], W: int) -> bool:
        count_map = Counter()
        for num in hand:
            count_map[num] += 1
        test = sorted(count_map)
        sorted_hand = sorted(dict.fromkeys(hand))
        while len(sorted_hand) > 0:
            while len(sorted_hand) > 0 and count_map[sorted_hand[0]] == 0:
                sorted_hand.pop(0)
            if len(sorted_hand) > 0:
                for key in range(sorted_hand[0], sorted_hand[0]+W):
                    if key in count_map:
                        count_map[key] -= 1
                        if count_map[key] < 0:
                            return False
                    else:
                        return False
        return True


Solve in Python:
Alice is a very brilliant student. He considers '4' and '7' as Magic numbers. The numbers containing only magic numbers are also magical. Given a magic number N ,he wants to know what could be the next magical number greater than the given number.

-----Input-----

First line of input contains number of test cases T. For each test case, there is exits only one line containing a magic number N.

-----Output-----

For each test case,  output a single line containing the next greater magical number.

-----Constraints-----
1<=T<=1000
4<= N<=10^100

-----Example-----
Input:
2
4
47

Output:
7
74

k=int(input())
for char in range(k):
    num=int(input())
    if '4' not in (str(num)):
        x=len(str(num))+1
        print('4'*x)
    elif num%2==0:
        print(num+3)
    else:
        num=str(num)
        for i in range(len(num)-1,-1,-1):
            if num[i]=='4':
                index=i
                break
        q=int(index)
        l=num[0:q]
        what=len(num)-(index+1)
        print(l+'7'+'4'*what)


Solve in Python:
Alice likes prime numbers. According to Alice, only those strings are nice whose sum of character values at a prime position is prime. She has a string $S$. Now, she has to count the number of nice strings which come before string $S$( including $S$) in the dictionary and are of the same length as $S$.
Strings are zero-indexed from left to right.
To find the character value she uses the mapping {'a': 0, 'b':1, 'c':2 ……. 'y': 24, 'z':25} .
For example, for string $abcde$ Characters at prime positions are $'c'$ and $'d'$. c + d = 2 + 3 = 5. Since, 5 is a prime number, the string is $nice$.
Since there could be many nice strings print the answer modulo $10^{9}+7$.

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

-----Output:-----
For each testcase, output in a single line number of nice strings modulo $10^{9}+7$.

-----Constraints-----
- $1 \leq T \leq 10$
- $2 \leq |S| \leq 10^2$
String $S$ contains only lowercase letters.

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

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

import sys
from collections import defaultdict
from copy import copy

MOD = 10**9 + 7

R = lambda t = int: t(input())
RL = lambda t = int: [t(x) for x in input().split()]
RLL = lambda n, t = int: [RL(t) for _ in range(n)]

# primes up to n
def primes(n):
  P = []
  n = int(n)
  U = [1] * (n+1)
  p = 2
  while p <= n:
    if U[p]:
      P += [p]
      x = p
      while x <= n:
        U[x] = 0
        x += p
    p += 1
  return P

def solve():
    S = R(str).strip()
    X = [ord(c)-ord('a') for c in S]
    P = primes(10000)
    L = defaultdict(lambda : 0)
    s = 0
    for i in range(len(S)):
        p = i in P
        NL = defaultdict(lambda : 0)
        for a in range(26):
            for l in L:
                NL[l + a * p] += L[l]
        for a in range(X[i]):
            NL[s + a * p] += 1
        s += X[i] * p
        L = NL
    L[s] += 1
    r = 0
    for p in P:
        r += L[p]
    print(r % MOD)

T = R()
for t in range(1, T + 1):
    solve()


Solve in Python:
Alice lives on a line. Today, she will travel to some place in a mysterious vehicle.
Initially, the distance between Alice and her destination is D. When she input a number x to the vehicle, it will travel in the direction of the destination by a distance of x if this move would shorten the distance between the vehicle and the destination, and it will stay at its position otherwise. Note that the vehicle may go past the destination when the distance between the vehicle and the destination is less than x.
Alice made a list of N numbers. The i-th number in this list is d_i. She will insert these numbers to the vehicle one by one.
However, a mischievous witch appeared. She is thinking of rewriting one number in the list so that Alice will not reach the destination after N moves.
She has Q plans to do this, as follows:
 - Rewrite only the q_i-th number in the list with some integer so that Alice will not reach the destination.
Write a program to determine whether each plan is feasible.

-----Constraints-----
 - 1≤ N ≤ 5*10^5
 - 1≤ Q ≤ 5*10^5
 - 1≤ D ≤ 10^9
 - 1≤ d_i ≤ 10^9(1≤i≤N)
 - 1≤ q_i ≤ N(1≤i≤Q)
 - D and each d_i are integers.

-----Input-----
Input is given from Standard Input in the following format:
N D
d_1 d_2 ... d_N
Q
q_1 q_2 ... q_Q

-----Output-----
Print Q lines. The i-th line should contain YES if the i-th plan is feasible, and NO otherwise.

-----Sample Input-----
4 10
3 4 3 3
2
4 3

-----Sample Output-----
NO
YES

For the first plan, Alice will already arrive at the destination by the first three moves, and therefore the answer is NO.
For the second plan, rewriting the third number in the list with 5 will prevent Alice from reaching the destination as shown in the following figure, and thus the answer is YES.

N, D = list(map(int, input().split()))
ds = list(map(int, input().split()))
Q = int(input())
querys = list([int(x) - 1 for x in input().split()])

# ps[i]: i回目の移動後の位置（目的地までの距離）
ps = [0] * (N + 1)
ps[0] = D
for i in range(N):
    ps[i + 1] = min(abs(ps[i] - ds[i]), ps[i])

if ps[N] != 0:
    print(('\n'.join(['YES'] * Q)))
    return

# ms[i]: i番目の移動後にm以下の位置ならば全て、目的地に到達可能であるようなmの最大値
ms = [0] * (N + 1)
for i in range(N)[::-1]:
    if ms[i + 1] + 1 >= ds[i] - ms[i + 1]:
        ms[i] = ms[i + 1] + ds[i]
    else:
        ms[i] = ms[i + 1]

for q in querys:
    if ps[q] <= ms[q + 1]: # 妨害は不可能
        print('NO')
    else:
        print('YES')


Solve in Python:
Alice plays the following game, loosely based on the card game "21".
Alice starts with 0 points, and draws numbers while she has less than K points.  During each draw, she gains an integer number of points randomly from the range [1, W], where W is an integer.  Each draw is independent and the outcomes have equal probabilities.
Alice stops drawing numbers when she gets K or more points.  What is the probability that she has N or less points?
Example 1:
Input: N = 10, K = 1, W = 10
Output: 1.00000
Explanation:  Alice gets a single card, then stops.

Example 2:
Input: N = 6, K = 1, W = 10
Output: 0.60000
Explanation:  Alice gets a single card, then stops.
In 6 out of W = 10 possibilities, she is at or below N = 6 points.

Example 3:
Input: N = 21, K = 17, W = 10
Output: 0.73278
Note:

0 <= K <= N <= 10000
1 <= W <= 10000
Answers will be accepted as correct if they are within 10^-5 of the correct answer.
The judging time limit has been reduced for this question.

class Solution:
    def new21Game(self, N: int, K: int, W: int) -> float:
        if K == 0:
            return 1
        dp = [0] * (W + K)
        dp[0] = 1
        sliding_sum = 1
        for i in range(1, K+W):
            # print(sliding_sum)
            # constant = dp[i] / W
            # for j in range(i+1, i+W+1):
            #     dp[j] += constant
            # dp[i] = 0
            dp[i] = sliding_sum / W
            if i < K:
                sliding_sum += dp[i]
            if i-W >= 0:
                sliding_sum -= dp[i-W]
                dp[i-W] = 0
        # print(dp)
        return sum(dp[K:N+1])/ sum(dp)


Solve in Python:
Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of $n$ stations, enumerated from $1$ through $n$. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station $i$ is station $i+1$ if $1 \leq i < n$ or station $1$ if $i = n$. It takes the train $1$ second to travel to its next station as described.

Bob gave Alice a fun task before he left: to deliver $m$ candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from $1$ through $m$. Candy $i$ ($1 \leq i \leq m$), now at station $a_i$, should be delivered to station $b_i$ ($a_i \neq b_i$). [Image] The blue numbers on the candies correspond to $b_i$ values. The image corresponds to the $1$-st example.

The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.

Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.

-----Input-----

The first line contains two space-separated integers $n$ and $m$ ($2 \leq n \leq 5\,000$; $1 \leq m \leq 20\,000$) — the number of stations and the number of candies, respectively.

The $i$-th of the following $m$ lines contains two space-separated integers $a_i$ and $b_i$ ($1 \leq a_i, b_i \leq n$; $a_i \neq b_i$) — the station that initially contains candy $i$ and the destination station of the candy, respectively.

-----Output-----

In the first and only line, print $n$ space-separated integers, the $i$-th of which is the minimum time, in seconds, the train would need to deliver all the candies...

import sys
from collections import defaultdict,deque
n,m=list(map(int,sys.stdin.readline().split()))
dist=defaultdict(list)
sweet=defaultdict(list)
for i in range(m):
    u,v=list(map(int,sys.stdin.readline().split()))
    sweet[u].append(v)
    dist[u].append(0)
for i in sweet:
    le=len(sweet[i])
    for j in range(le):
        if sweet[i][j]>=i:
            dist[i][j]=sweet[i][j]-i
        else:
            dist[i][j]=n-(i-sweet[i][j])
    dist[i].sort()
#print(dist,'dits')
for i in dist:
    count=0
    le=len(dist[i])
    for k in range(le-1,-1,-1):
        dist[i][k]+=count*n
        count+=1
    dist[i].sort()
vis=defaultdict(int)
for i in dist:
    if dist[i]==[]:
        vis[i]=0
    else:
        vis[i]=dist[i][-1]
#print(dist,'dist')
#print(vis,'vis')
ans=[0 for _ in range(n)]
for i in range(1,n+1):
    cur=0
    #print(i,'i')
    for k in range(1,n+1):
        new=0
        if k>=i:
            if vis[k]!=0:
                new=vis[k]+k-i
                #print(new,'new',k,'k')
        else:
            if vis[k]!=0:
                new=vis[k]+(n)-(i-k)
                #print(new,'new',k,'k')
        cur=max(cur,new)
    ans[i-1]=cur
print(*ans)


Solve in Python:
Alice's school is planning to take some students from her class on a field trip. Alice is really excited about it. There are a total of S students in her class. But due to budget constraints, the school is planning to take only N students for the trip. These students will be picked randomly. And each student has equal chance of being picked.
Alice's friend circle has M students including her. Though she is excited about the field trip, she will enjoy it only if there are atleast K of her friends with her on the trip. She is wondering what are the chances of that happening. She needs your help. Tell her the probability that she will enjoy given that she goes on the trip.

-----Input:-----
First line of input contains a single integer T, the number of test cases.

Each test starts with a single line having 4 space separated integers, S, N, M and K.

-----Output:-----
For each test case, output a line containing the required probability. The answer will be accepted if the relative error is not more than 10-6.

-----Constraints:-----
1 ≤ T ≤ 100
1 ≤ S ≤ 1000
1 ≤ N ≤ S
1 ≤ M ≤ S
0 ≤ K < M

-----Example:-----Input:
3
10 10 5 3
10 4 6 4
3 2 2 1

Output:
1.000000
0.000000
0.500000

-----Explanation:-----Case #1:
Every student will be taken to the trip. So all her 4 friends will accompany her to the trip no matter what.
Case #2:
Alice wants 4 out of her 5 friends to come along with her which isn't possible because the school is willing to pick only 4 students for the trip.

import math
f=[1]
for i in range(1,1002):
 f.append(i*f[i-1])
def c(n,r):
 if n<r:
  return 0
 else:
  return float(f[n]/(f[n-r]*f[r]))
t=int(input())
while t>0:
 [s,n,m,k]=[int(i) for i in input().split()]
 ways=0.0
 if k==0 or s==n:
  print(float(1))
 elif k>=n:
  print(float(0))
 else:
  j=k-1
  flag=0
  while s-m>=0 and j>=0 and n-j-1>=0:
   ways=ways+c(m-1,j)*c(s-m,n-j-1)
   j-=1
  p=ways/c(s-1,n-1)
  p=(1-p)
  print(p)
 t-=1


Solve in Python:
Alice, Samantha, and Patricia are relaxing on the porch, when Alice suddenly says: _"I'm thinking of two numbers, both greater than or equal to 2. I shall tell Samantha the sum of the two numbers and Patricia the product of the two numbers."_

She takes Samantha aside and whispers in her ear the sum so that Patricia cannot hear it. Then she takes Patricia aside and whispers in her ear the product so that Samantha cannot hear it.

After a moment of reflection, Samantha says:

 **Statement 1:** _"Patricia cannot know what the two numbers are."_

After which Patricia says:

 **Statement 2:**  _"In that case, I do know what the two numbers are."_

To which Samantha replies:

 **Statement 3:**  _"Then I too know what the two numbers are."_

Your first task is to write a function `statement1(s)` that takes an `int` argument `s` and returns `True` if and only if Samantha could have made statement 1 if given the number `s`. You may assume that `s` is the sum of two numbers both greater than or equal to 2.

Your second task is to write a function `statement2(p)` that takes an `int` argument `p` and returns `True` if and only if Patricia, when given the number `p`, could have made statement 2 after hearing Samantha make statement 1. You may assume that `p` is the product of two numbers both greater than or equal to 2 and that Patricia would not have been able to determine the two numbers by looking at `p` alone.

Your third task is to write a function `statement3(s)` that takes an `int` argument `s` and returns `True` if and only if Samantha, when given the number `s`, could have made statement 3 after hearing Patricia make statement 2.

Finally, it is to you to figure out what two numbers Alice was thinking of. Since there are multiple solutions, you must write a function `is_solution(a, b)` that returns `True` if and only if `a` and `b` could have been two numbers that Alice was thinking of.

Hint: To get you started, think of what Samantha's first statement implies. Samantha knows that Patricia was not given the...

def is_prime(n):
    return n == 2 or n % 2 != 0 and all(n % k != 0 for k in range(3, root(n) + 1, 2))

def root(p):
    return int(p ** 0.5)

def statement1(s):
    return not(s % 2 == 0 or is_prime(s - 2))

def statement2(p):
    return sum(statement1(i + p / i) for i in range(2, root(p) + 1) if p % i == 0) == 1

def statement3(s):
    return sum(statement2(i * (s - i)) for i in range(2, s / 2 + 1)) == 1

def is_solution(a, b):
    return statement1(a + b) and statement2(a * b) and statement3(a + b)


Solve in Python:
All of the animals are having a feast! Each animal is bringing one dish. There is just one rule: the dish must start and end with the same letters as the animal's name. For example, the great blue heron is bringing garlic naan and the chickadee is bringing chocolate cake.

Write a function `feast` that takes the animal's name and dish as arguments and returns true or false to indicate whether the beast is allowed to bring the dish to the feast.

Assume that `beast` and `dish` are always lowercase strings, and that each has at least two letters. `beast` and `dish` may contain hyphens and spaces, but these will not appear at the beginning or end of the string. They will not contain numerals.

def feast(beast, dish):
    a=len(dish)-1
    if beast[0]==dish[0] and beast[len(beast)-1]==dish[a]:
         return True
    else:
        return False


Solve in Python:
All strings in Chefland are beautiful because they are binary strings (a binary string contains only characters '0' and '1'). The beauty of a binary string $S$ is defined as the number of pairs $(i, j)$ ($1 \le i \le j \le |S|$) such that the substring $S_i, S_{i+1}, \ldots, S_j$ is special.
For a binary string $U$, let's denote the number of occurrences of the characters '1' and '0' in $U$ by $cnt_1$ and $cnt_0$ respectively; then, $U$ is special if $cnt_0 = cnt_1 \cdot cnt_1$.
Today, Chef's friend Araspa is celebrating her birthday. Chef wants to give Araspa the most beautiful binary string he can find. Currently, he is checking out binary strings in a shop, but he needs your help to calculate their beauties. Tell Chef the beauty of each binary string he gives you.

-----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 beauty of the string $S$.

-----Constraints-----
- $1 \le T \le 10$
- $1 \le |S| \le 10^5$
- each character of $S$ is '0' or '1'

-----Example Input-----
2
010001
10

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

-----Explanation-----
Example case 1: The special substrings correspond to $(i, j) = (1, 2), (1, 6), (2, 3), (5, 6)$.

for i in range(int(input())):
 s=input()
 one=[0]
 for i in range(len(s)):
  one+=[one[-1]]
  if s[i]=='1':
   one[-1]+=1
 ans=0
 i=1
 r=2
 while r<=len(s):
  r=i+i**2
  j=0
  while j<=len(s)-r:
   if one[j+r]-one[j]==i:
    ans+=1
    j+=1
   else:
    j+=abs(i-(one[j+r]-one[j]))
  i+=1
 print(ans)


Solve in Python:
All techniques in the ninja world consist of hand seals. At the moment Naruto is learning a new technique, which consists of $n\cdot m$ different seals, denoted by distinct numbers. All of them were written in an $n\times m$ table.

The table is lost now. Naruto managed to remember elements of each row from left to right, and elements of each column from top to bottom, but he doesn't remember the order of rows and columns. Please restore the table consistent with this data so that Naruto will be able to learn the new technique.

-----Input-----

The first line of the input contains the only integer $t$ ($1\leq t\leq 100\,000$) denoting the number of test cases. Their descriptions follow.

The first line of each test case description consists of two space-separated integers $n$ and $m$ ($1 \leq n, m \leq 500$) standing for the number of rows and columns in the table, respectively. All hand seals are encoded by the positive integers from $1$ to $n\cdot m$.

The following $n$ lines contain $m$ space separated integers each, denoting elements of an arbitrary row in the table left to right.

The following $m$ lines contain $n$ space separated integers each, denoting elements of an arbitrary column in the table top to bottom.

Sum of $nm$ over all test cases does not exceed $250\,000$. It is guaranteed that each row occurs in the input exactly once, as well as each column. It is also guaranteed that each number from $1$ to $nm$ occurs exactly once in all rows, as well as in all columns. Finally, it is guaranteed that a table consistent with the input exists.

-----Output-----

For each test case, output $n$ lines with $m$ space-separated integers each, denoting the restored table. One can show that the answer is always unique.

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

Output
1 2 3
6 5 4
3
1
2

-----Note-----

Consider the first test case. The matrix is $2 \times 3$. You are given the rows and columns in arbitrary order.

One of the rows is $[6, 5, 4]$. One of the rows is $[1,...

from sys import stdin
input = stdin.readline

tests = int(input())
for test in range(tests):
    n, m = list(map(int, input().split()))
    a = [[0] * m for _ in range(n)]
    r = [[int(i) for i in input().split()] for _ in range(n)]
    c = [[int(i) for i in input().split()] for _ in range(m)]
    z = [[-1, -1] for _ in range(n * m + 1)]

    for i in range(n):
        for j in range(m):
            z[r[i][j]][0] = j
    for i in range(m):
        for j in range(n):
            z[c[i][j]][1] = j

    for i in range(1, n * m + 1):
        a[z[i][1]][z[i][0]] = i

    for i in a:
        print(' '.join([str(j) for j in i]))


Solve in Python:
Allen and Bessie are playing a simple number game. They both know a function $f: \{0, 1\}^n \to \mathbb{R}$, i. e. the function takes $n$ binary arguments and returns a real value. At the start of the game, the variables $x_1, x_2, \dots, x_n$ are all set to $-1$. Each round, with equal probability, one of Allen or Bessie gets to make a move. A move consists of picking an $i$ such that $x_i = -1$ and either setting $x_i \to 0$ or $x_i \to 1$.

After $n$ rounds all variables are set, and the game value resolves to $f(x_1, x_2, \dots, x_n)$. Allen wants to maximize the game value, and Bessie wants to minimize it.

Your goal is to help Allen and Bessie find the expected game value! They will play $r+1$ times though, so between each game, exactly one value of $f$ changes. In other words, between rounds $i$ and $i+1$ for $1 \le i \le r$, $f(z_1, \dots, z_n) \to g_i$ for some $(z_1, \dots, z_n) \in \{0, 1\}^n$. You are to find the expected game value in the beginning and after each change.

-----Input-----

The first line contains two integers $n$ and $r$ ($1 \le n \le 18$, $0 \le r \le 2^{18}$).

The next line contains $2^n$ integers $c_0, c_1, \dots, c_{2^n-1}$ ($0 \le c_i \le 10^9$), denoting the initial values of $f$. More specifically, $f(x_0, x_1, \dots, x_{n-1}) = c_x$, if $x = \overline{x_{n-1} \ldots x_0}$ in binary.

Each of the next $r$ lines contains two integers $z$ and $g$ ($0 \le z \le 2^n - 1$, $0 \le g \le 10^9$). If $z = \overline{z_{n-1} \dots z_0}$ in binary, then this means to set $f(z_0, \dots, z_{n-1}) \to g$.

-----Output-----

Print $r+1$ lines, the $i$-th of which denotes the value of the game $f$ during the $i$-th round. Your answer must have absolute or relative error within $10^{-6}$.

Formally, let your answer be $a$, and the jury's answer be $b$. Your answer is considered correct if $\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$.

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

Output
1.500000
2.250000
3.250000

Input
1 0
2 3

Output
2.500000

Input
2 0
1 1 1...

n, r = [int(x) for x in input().split()]

n = 2 ** n

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

s = sum(xs)

res = [0 for _ in range(r+1)]
for i in range(r):
    res[i] = s / n
    i, val = [int(x) for x in input().split()]
    s += val - xs[i]
    xs[i] = val
res[r] = s / n
print("\n".join(map(str, res)))


Solve in Python:
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem.

Allen's future parking lot can be represented as a rectangle with $4$ rows and $n$ ($n \le 50$) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having $k$ ($k \le 2n$) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places.

 [Image] Illustration to the first example.

However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space.

Allen knows he will be a very busy man, and will only have time to move cars at most $20000$ times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.

-----Input-----

The first line of the input contains two space-separated integers $n$ and $k$ ($1 \le n \le 50$, $1 \le k \le 2n$), representing the number of columns and the number of cars, respectively.

The next four lines will contain $n$ integers each between $0$ and $k$ inclusive, representing the initial state of the parking lot. The rows are numbered $1$ to $4$ from top to bottom and the columns are numbered $1$ to $n$ from left to right.

In the first and last line, an integer $1 \le x \le k$ represents a parking spot assigned to car $x$ (you can only move this car to this place), while the integer $0$ represents a empty space (you can't move any car...

def main():
    n, k = map(int, input().split())
    a, b, c, d = (list(map(int, input().split())) for _ in 'abcd')
    ss, tt, n2, res = [*b, *c[::-1]], [*a, *d[::-1]], n * 2, []
    yx = [*[(2, i + 1) for i in range(n)], *[(3, i) for i in range(n, 0, -1)]]

    def park():
        for i, s, t, (y, x) in zip(range(n2), ss, tt, yx):
            if s == t != 0:
                ss[i] = 0
                res.append(f'{s} {(1, 4)[y == 3]} {x}')

    def rotate():
        start = ss.index(0)
        for i in range(start - n2, start - 1):
            s = ss[i] = ss[i + 1]
            if s:
                y, x = yx[i]
                res.append(f'{s} {y} {x}')
        ss[start - 1] = 0

    park()
    if all(ss):
        print(-1)
        return
    while any(ss):
        rotate()
        park()
    print(len(res), '\n'.join(res), sep='\n')

def __starting_point():
    main()

__starting_point()


Solve in Python:
Allen is hosting a formal dinner party. $2n$ people come to the event in $n$ pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The $2n$ people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the picture more aesthetic.

Help Allen find the minimum number of swaps of adjacent positions he must perform to make it so that each couple occupies adjacent positions in the line.

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 100$), the number of pairs of people.

The second line contains $2n$ integers $a_1, a_2, \dots, a_{2n}$. For each $i$ with $1 \le i \le n$, $i$ appears exactly twice. If $a_j = a_k = i$, that means that the $j$-th and $k$-th people in the line form a couple.

-----Output-----

Output a single integer, representing the minimum number of adjacent swaps needed to line the people up so that each pair occupies adjacent positions.

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

Output
2

Input
3
1 1 2 2 3 3

Output
0

Input
3
3 1 2 3 1 2

Output
3

-----Note-----

In the first sample case, we can transform $1 1 2 3 3 2 4 4 \rightarrow 1 1 2 3 2 3 4 4 \rightarrow 1 1 2 2 3 3 4 4$ in two steps. Note that the sequence $1 1 2 3 3 2 4 4 \rightarrow 1 1 3 2 3 2 4 4 \rightarrow 1 1 3 3 2 2 4 4$ also works in the same number of steps.

The second sample case already satisfies the constraints; therefore we need $0$ swaps.

n = 2 * int(input())
a = [int(i) for i in input().split()]
ans = 0
for i in range(1, len(a), 2):
    j = i
    while a[j] != a[i - 1]:
        j += 1
    while j != i:
        ans += 1
        a[j - 1], a[j] = a[j], a[j - 1]
        j -= 1
print(ans)


Solve in Python:
Almir had a small sequence $A_1, A_2, \ldots, A_N$. He decided to make $K$ copies of this sequence and concatenate them, forming a sequence $X_1, X_2, \ldots, X_{NK}$; for each valid $i$ and $j$ ($0 \le j < K$), $X_{j \cdot N + i} = A_i$.
For example, if $A = (1, 2, 3)$ and $K = 4$, the final sequence is $X = (1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3)$.
A pair $(i, j)$, where $1 \le i < j \le N$, is an inversion if $X_i > X_j$. Find the number of inversions in the final sequence $X$.

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

-----Output-----
For each test case, print a single line containing one integer ― the number of inversions in the sequence $X$.

-----Constraints-----
- $1 \le T \le 1,000$
- $1 \le N \le 100$
- $1 \le K \le 10^6$
- $1 \le A_i \le 10^9$ for each valid $i$

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

-----Example Input-----
2
3 3
2 1 3
4 100
99 2 1000 24

-----Example Output-----
12
30000

# cook your dish here
for _ in range(int(input())):
    n, k = map(int, input().split())
    arr = list(map(int, input().split()))
    x, suffix = 0, 0
    for i in range(n):
        for j in range(n):
            if arr[i] > arr[j]: x += 1
            if j > i:
                if arr[i] > arr[j]: suffix += 1
    print(x*( (k*(k-1))//2 ) + suffix*k)


Solve in Python:
Alright, detective, one of our colleagues successfully observed our target person, Robby the robber. We followed him to a secret warehouse, where we assume to find all the stolen stuff. The door to this warehouse is secured by an electronic combination lock. Unfortunately our spy isn't sure about the PIN he saw, when Robby entered it.

The keypad has the following layout:
```
┌───┬───┬───┐
│ 1 │ 2 │ 3 │
├───┼───┼───┤
│ 4 │ 5 │ 6 │
├───┼───┼───┤
│ 7 │ 8 │ 9 │
└───┼───┼───┘
    │ 0 │
    └───┘
```
He noted the PIN `1357`, but he also said, it is possible that each of the digits he saw could actually be another adjacent digit (horizontally or vertically, but not diagonally). E.g. instead of the `1` it could also be the `2` or `4`. And instead of the `5` it could also be the `2`, `4`, `6` or `8`.

He also mentioned, he knows this kind of locks. You can enter an unlimited amount of wrong PINs, they never finally lock the system or sound the alarm. That's why we can try out all possible (*) variations.

\* possible in sense of: the observed PIN itself and all variations considering the adjacent digits

Can you help us to find all those variations? It would be nice to have a function, that returns an array (or a list in Java and C#)  of all variations for an observed PIN with a length of 1 to 8 digits. We could name the function `getPINs` (`get_pins` in python, `GetPINs` in C#). But please note that all PINs, the observed one and also the results, must be strings, because of potentially leading '0's. We already prepared some test cases for you.

Detective, we are counting on you!

For C# user: Do not use Mono. Mono is too slower when run your code.


Solve in Python:
Americans are odd people: in their buildings, the first floor is actually the ground floor and there is no 13th floor (due to superstition).

Write a function that given a floor in the american system returns the floor in the european system.

With the 1st floor being replaced by the ground floor and the 13th floor being removed, the numbers move down to take their place. In case of above 13, they move down by two because there are two omitted numbers below them.

Basements (negatives) stay the same as the universal level.

[More information here](https://en.wikipedia.org/wiki/Storey#European_scheme)

## Examples

```
1  =>  0
0  =>  0
5  =>  4
15  =>  13
-3  =>  -3
```

def get_real_floor(n):

    return n - 1 * (n>0) - 1 * (n>13)


Solve in Python:
Amicable numbers are two different numbers so related that the sum of the proper divisors of each is equal to the other number. (A proper divisor of a number is a positive factor of that number other than the number itself. For example, the proper divisors of 6 are 1, 2, and 3.)

For example, the smallest pair of amicable numbers is (220, 284); for the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110, of which the sum is 284; and the proper divisors of 284 are 1, 2, 4, 71 and 142, of which the sum is 220.

Derive function ```amicableNumbers(num1, num2)``` which returns ```true/True``` if pair ```num1 num2``` are amicable, ```false/False``` if not.

See more at https://en.wikipedia.org/wiki/Amicable_numbers

def amicable_numbers(n1,n2):
    s1 = sum([x for x in range(1,n1) if n1%x==0])
    s2 = sum([x for x in range(1,n2) if n2%x==0])
    return s1 == n2 and s2 == n1


Solve in Python:
Amidakuji is a method of lottery designed to create random pairings between two sets comprised of an equal number of elements.
Your task is to write a function amidakuji that returns the final positions of each element. Note that the elements are an ascending sequence of consecutive integers starting with 0 (from left to right).
Input
Your function will receive an array/list of equal-length strings consisting of 0 and 1 characters; this represents the "ladder" structure. The 1s represent the rungs of the ladder and the 0s represent empty space.
Each element begins at the top of its corresponding vertical rail, as illustrated in the diagram below.During the descent of the ladder, whenever a vertical rail intersects a horizontal rung, it swaps values with the adjacent connecting vertical rail.
Output
Your function should return an array of integers, with each integer in its final position.
Test Example

The diagram above is a visual representation of the test example below. The yellow highlighted path shows the path taken by the 2 value. Each time it encounters a crosspiece, it shifts position.

```python
ladder = [
        '001001',
        '010000',
        '100100',
        '001000',
        '100101',
        '010010',
        '101001',
        '010100'
]

amidakuji(ladder) # [4, 2, 0, 5, 3, 6, 1]
```

Other Technical Details

A function visualizer is preloaded to help illustrate the structure of the ladder; you can call this function with test inputs
No two rungs will ever be adjacent (so there is no ambiguity about directional path)
Full Test Suite: 10 fixed tests and 100 randomly-generated tests
Test input dimension upper bounds:

maximum width: 20
maximum height: 50

Inputs will always be valid

If you enjoyed this kata, be sure to check out my other katas

def amidakuji(board):
    li = [0] * (len(board[0]) + 1)
    for i in range(len(board[0]) + 1):
        c = i
        for k in range(len(board)):
            if int(board[k][c]) if c<len(board[0]) else 0 : c += 1
            elif int(board[k][c - 1]) if c>0 else 0 : c -= 1
        li[c] = i
    return li


Solve in Python:
Amit is going on a date and he wants to gift his date an array of positive numbers. But he is running short on money. He already has an array of numbers in design. Cost of an array of numbers is the sum of elements in it. But he wants to minimize the cost of making it.
So he does the following number of operations one by one for any number of times:
He chooses two adjacent elements ,replace them by one element with value = XOR of the two numbers. This operation reduces length of array (and elements are re-numerated accordingly)
Find the minimum amount of money that Amit needs to spend to gift his date.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of $2$ lines of input, first line contains a single integer $N$ and the second line contains $N$ elements - $A1,A2,A3,.....,AN$

-----Output:-----
For each testcase, output in a single line answer denoting the minimum cost

-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq N \leq 10^5$
- $0 \leq Ai \leq 10^9$ for $1\leq i \leq N$

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

-----Sample Output:-----
8
15
0

-----EXPLANATION:-----
For first case,
This array is :
$[8,4,1,5,0] -> [8,4,4,0] -> [8,0,0]$. Sum=$8$ So the answer is 8.

for i in range(int(input())):
    n=int(input())
    lst=list(map(int,input().split()))
    x=0
    for j in range(n):
        x^=lst[j]

    print(x)


Solve in Python:
Among Johnny's numerous hobbies, there are two seemingly harmless ones: applying bitwise operations and sneaking into his dad's office. As it is usually the case with small children, Johnny is unaware that combining these two activities can get him in a lot of trouble.

There is a set $S$ containing very important numbers on his dad's desk. The minute Johnny heard about it, he decided that it's a good idea to choose a positive integer $k$ and replace each element $s$ of the set $S$ with $s \oplus k$ ($\oplus$ denotes the exclusive or operation).

Help him choose such $k$ that Johnny's dad will not see any difference after his son is done playing (i.e. Johnny will get the same set as before playing). It is possible that no such number exists. It is also possible that there are many of them. In such a case, output the smallest one. Note that the order of elements in a set doesn't matter, i.e. set $\{1, 2, 3\}$ equals to set $\{2, 1, 3\}$.

Formally, find the smallest positive integer $k$ such that $\{s \oplus k | s \in S\} = S$ or report that there is no such number.

For example, if $S = \{1, 3, 4\}$ and $k = 2$, new set will be equal to $\{3, 1, 6\}$. If $S = \{0, 1, 2, 3\}$ and $k = 1$, after playing set will stay the same.

-----Input-----

In the first line of input, there is a single integer $t$ ($1 \leq t \leq 1024$), the number of test cases. In the next lines, $t$ test cases follow. Each of them consists of two lines.

In the first line there is a single integer $n$ ($1 \leq n \leq 1024$) denoting the number of elements in set $S$. Second line consists of $n$ distinct integers $s_i$ ($0 \leq s_i < 1024$), elements of $S$.

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

-----Output-----

Print $t$ lines; $i$-th line should contain the answer to the $i$-th test case, the minimal positive integer $k$ satisfying the conditions or $-1$ if no such $k$ exists.

-----Example-----
Input
6
4
1 0 2 3
6
10 7 14 8 3 12
2
0 2
3
1 2 3
6
1 4 6 10 11 12
2
0...

t = int(input())

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

    check = set(s)
    found = False
    for i in range(1, 1025):
        newset = set([e^i for e in s])
        if check == newset:
            print(i)
            found = True
            break
    if not found:
        print(-1)


Solve in Python:
Among the ruins of an ancient city a group of archaeologists found a mysterious function with lots of HOLES in it called ```getNum(n)``` (or `get_num(n)` in ruby, python, or r). They tried to call it with some arguments. And finally they got this journal:
The archaeologists were totally stuck with this challenge. They were all in desperation but then.... came YOU the SUPER-AWESOME programmer. Will you be able to understand the mystery of this function and rewrite it?

get_num = lambda n: sum(int('1000001021'[int(d)]) for d in str(n))


Solve in Python:
An **anagram** is the result of rearranging the letters of a word to produce a new word.

**Note:** anagrams are case insensitive

Complete the function to return `true` if the two arguments given are anagrams of each other; return `false` otherwise.

## Examples

* `"foefet"` is an anagram of `"toffee"`

* `"Buckethead"` is an anagram of `"DeathCubeK"`

def is_anagram(a_str, b_str):

    # Check same number of letters
    if len(a_str) == len(b_str):

        # Check letters used same number of times
        a_list = list(a_str.lower())
        b_list = list(b_str.lower())

        for char in a_list:
            if char in b_list:
                b_list.remove(char)

        if not b_list:
            return True
        else:
            return False

    else:
        return False


Solve in Python:
An AI has infected a text with a character!!

This text is now **fully mutated** to this character.

If the text or the character are empty, return an empty string.
There will never be a case when both are empty as nothing is going on!!

**Note:** The character is a string of length 1 or an empty string.

# Example
```python
text before = "abc"
character   = "z"
text after  = "zzz"
```

def contamination(text, char):
    i,s=0,''
    while i <len(text):
        s+=char
        i+=1
    return s


Solve in Python:
An Arithmetic Progression is defined as one in which there is a constant difference between the consecutive terms of a given series of numbers. You are provided with consecutive elements of an Arithmetic Progression. There is however one hitch: exactly one term from the original series is missing from the set of numbers which have been given to you. The rest of the given series is the same as the original AP.  Find the missing term.

You have to write a function that receives a list, list size will always be at least 3 numbers. The missing term will never be the first or last one.

## Example
```python
find_missing([1, 3, 5, 9, 11]) == 7
```

PS: This is a sample question of the facebook engineer challenge on interviewstreet.
I found it quite fun to solve on paper using math, derive the algo that way.
Have fun!

def find_missing(sequence):
    t = sequence
    return (t[0] + t[-1]) * (len(t) + 1) / 2 - sum(t)


Solve in Python:
An Ironman Triathlon is one of a series of long-distance triathlon races organized by the World Triathlon Corporaion (WTC).
It consists of a 2.4-mile swim, a 112-mile bicycle ride and a marathon (26.2-mile) (run, raced in that order and without a break. It hurts... trust me.

Your task is to take a distance that an athlete is through the race, and return one of the following:

If the distance is zero, return `'Starting Line... Good Luck!'`.

If the athlete will be swimming, return an object with `'Swim'` as the key, and the remaining race distance as the value.

If the athlete will be riding their bike, return an object with `'Bike'` as the key, and the remaining race distance as the value.

If the athlete will be running, and has more than 10 miles to go, return an object with `'Run'` as the key, and the remaining race distance as the value.

If the athlete has 10 miles or less to go, return return an object with `'Run'` as the key, and `'Nearly there!'` as the value.

Finally, if the athlete has completed te distance, return `"You're done! Stop running!"`.

All distance should be calculated to two decimal places.

def i_tri(s):
    t = 2.4 + 112.0 + 26.2
    v = t - s
    k = "Swim" if s < 2.4 else "Bike" if s >= 2.4 and s < 114.4 else 'Run'
    if s == 0: return 'Starting Line... Good Luck!'
    elif s >= t: return "You're done! Stop running!"
    elif t - s <= 10: return {'Run':'Nearly there!'}
    else: return {k: "{:.2f}".format(v) + ' to go!'}


Solve in Python:
An NBA game runs 48 minutes (Four 12 minute quarters). Players do not typically play the full game, subbing in and out as necessary. Your job is to extrapolate a player's points per game if they played the full 48 minutes.

Write a function that takes two arguments, ppg (points per game) and mpg (minutes per game) and returns a straight extrapolation of ppg per 48 minutes rounded to the nearest tenth. Return 0 if 0.

Examples:
```python
nba_extrap(12, 20) # 28.8
nba_extrap(10, 10) # 48
nba_extrap(5, 17) # 14.1
nba_extrap(0, 0) # 0
```

Notes:
All inputs will be either be an integer or float.
Follow your dreams!

def nba_extrap(ppg, mpg):
    pts = 0
    if mpg > 0:
        pts = round((ppg / mpg) * 48, 1)
    else:
        pass
    return pts


Solve in Python:
An `non decreasing` number is one containing no two consecutive digits (left to right), whose the first is higer than the second. For example, 1235 is an non decreasing number, 1229 is too, but 123429 isn't.

Write a function that finds the number of non decreasing numbers up to `10**N` (exclusive) where N is the input of your function. For example, if `N=3`, you have to count all non decreasing numbers from 0 to 999.

 You'll definitely need something smarter than brute force for large values of N!

from functools import lru_cache

@lru_cache(maxsize=None)
def f(ndigits, starting_digit):
    if ndigits == 0:
        return 1
    return sum(f(ndigits-1, i) for i in range(starting_digit, 10))

def increasing_numbers(digits):
    if digits == 0:
        return 1
    return sum(f(digits-1, i) for i in range(10))


Solve in Python:
An abundant number or excessive number is a number for which the sum of its proper divisors is greater than the number itself.

The integer 12 is the first abundant number. Its proper divisors are 1, 2, 3, 4 and 6 for a total of 16 (> 12).

Derive function `abundantNumber(num)/abundant_number(num)` which returns `true/True/.true.` if `num` is abundant, `false/False/.false.` if not.

def abundant_number(n):
    return sum(n//i+i for i in range(2,int(n**.5)+1) if n%i==0)+1 > n


Solve in Python:
An acrostic is a text in which the first letter of each line spells out a word. It is also a quick and cheap way of writing a poem for somebody, as exemplified below :

Write a program that reads an acrostic to identify the "hidden" word. Specifically, your program will receive a list of words (reprensenting an acrostic) and will need to return a string corresponding to the word that is spelled out by taking the first letter of each word in the acrostic.

def read_out(acrostic):
    return ''.join(s[0] for s in acrostic)


Solve in Python:
An agent called Cypher is decrypting a message, that contains a composite number $n$. All divisors of $n$, which are greater than $1$, are placed in a circle. Cypher can choose the initial order of numbers in the circle.

In one move Cypher can choose two adjacent numbers in a circle and insert their least common multiple between them. He can do that move as many times as needed.

A message is decrypted, if every two adjacent numbers are not coprime. Note that for such constraints it's always possible to decrypt the message.

Find the minimal number of moves that Cypher should do to decrypt the message, and show the initial order of numbers in the circle for that.

-----Input-----

The first line contains an integer $t$ $(1 \le t \le 100)$ — the number of test cases. Next $t$ lines describe each test case.

In a single line of each test case description, there is a single composite number $n$ $(4 \le n \le 10^9)$ — the number from the message.

It's guaranteed that the total number of divisors of $n$ for all test cases does not exceed $2 \cdot 10^5$.

-----Output-----

For each test case in the first line output the initial order of divisors, which are greater than $1$, in the circle. In the second line output, the minimal number of moves needed to decrypt the message.

If there are different possible orders with a correct answer, print any of them.

-----Example-----
Input
3
6
4
30

Output
2 3 6
1
2 4
0
2 30 6 3 15 5 10
0

-----Note-----

In the first test case $6$ has three divisors, which are greater than $1$: $2, 3, 6$. Regardless of the initial order, numbers $2$ and $3$ are adjacent, so it's needed to place their least common multiple between them. After that the circle becomes $2, 6, 3, 6$, and every two adjacent numbers are not coprime.

In the second test case $4$ has two divisors greater than $1$: $2, 4$, and they are not coprime, so any initial order is correct, and it's not needed to place any least common multiples.

In the third test case all divisors of $30$ greater than $1$ can be...

from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop,heapify
import math
from collections import *
from functools import reduce,cmp_to_key
import sys
input = sys.stdin.readline

from itertools import accumulate
from functools import lru_cache

M = mod = 998244353
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)

def li():return [int(i) for i in input().rstrip('\n').split()]
def st():return input().rstrip('\n')
def val():return int(input().rstrip('\n'))
def li2():return [i for i in input().rstrip('\n')]
def li3():return [int(i) for i in input().rstrip('\n')]

def isprime(n):
    for j in range(2, int(n ** 0.5) + 1):
        if n % j == 0:return 0
    return 1

for _ in range(val()):
    n = val()

    l1 = factors(n)[1:]
    l = []
    for j in l1:
        if isprime(j):l.append(j)
    l1 = set(l1)
    l1 -= set(l)
    # print(l, l1)
    d = defaultdict(set)
    for j in range(len(l)):
        for i in sorted(list(l1)):
            if i % l[j] == 0 and i % l[j - 1] == 0:
                d[tuple(sorted([l[j], l[j - 1]]))].add(i)
                l1.remove(i)
                break
    # print(l, l1)
    for j in range(len(l)):
        for i in sorted(list(l1)):
            if i % l[j] == 0 and i % l[j - 1] == 0:
                d[tuple(sorted([l[j], l[j - 1]]))].add(i)
                l1.remove(i)
    # print(l, l1, d)

    only = defaultdict(list)
    for j in range(len(l)):
        for i in sorted(list(l1)):
            if i % l[j] == 0:
                only[l[j]].append(i)
                l1.remove(i)

    fin = []
    if len(l) == 2:
        fin.append(l[0])
        for j in only[l[0]]:fin.append(j)
        for i in range(len(l)):
            for j in list(d[tuple(sorted([l[i], l[(i + 1)  % len(l)]]))]):
                fin.append(j)
                d[tuple(sorted([l[i], l[(i + 1)  % len(l)]]))].remove(j)
                if i != len(l)...


Solve in Python:
An anagram is a word, a phrase, or a sentence formed from another by rearranging its letters. An example of this is "angel", which is an anagram of "glean".

Write a function that receives an array of words, and returns the total number of distinct pairs of anagramic words inside it.

Some examples:

- There are 2 anagrams in the array `["dell", "ledl", "abc", "cba"]`
- There are 7 anagrams in the array `["dell", "ledl", "abc", "cba", "bca", "bac"]`

from collections import Counter

def anagram_counter(words):
    return sum(n * (n - 1) / 2 for n in Counter(frozenset(word) for word in words).values())


Solve in Python:
An architect wants to construct a vaulted building supported by a family of arches Cn.

fn(x) = -nx - xlog(x) is the equation of the arch Cn where `x` is a positive real number (0 < x <= 1), `log(x)` is the natural logarithm (base e), `n` a non negative integer. Let fn(0) = 0.

Be An the point of Cn where the tangent to Cn is horizontal and Bn+1 the orthogonal projection of An on the x-axis (it means that An and Bn+1 have the same x -coordinate).
Kn is the intersection of Cn with the x-axis.

The figure shows C0, A0, B1, K0 as C(0), A0, B1, K0.

![alternative text](https://i.imgur.com/Td9aWIJ.png)

The architect wants to support each arch Cn with a wall of glass filling the **curved** surface An Bn+1 Kn under the curve Cn.
On the drawing you can see the surface `A0 B1 K0` in blue.

He asks if we could calculate the weight of the surface of glass he needs to support all arches C0...Cn where n is a positive integer knowing he can choose glass thickness hence glass weight per square unit of surface.

He gives us the absolute value of A0 B1 K0 area (in blue); call it `i0` which is approximately `0.14849853757254047` in square units.

## Task
Write the function `weight` with parameters `n` and `w` where `n` is the number of arches to consider (n >= 1) and `w` is the weight of a square unit of glass depending on the wall thickness.

This function should return the weight of n glass walls as described above.

## Example
```
weight(10, 700) -> 120.21882500408238
weight(8, 1108) -> 190.28922301858418
```
## Hint:
There is no integral to calculate. You can plot C1 and try to see the relationship between the different Cn and then use `i0`.

## Note:
- don't round or truncate your result

from math import exp

def weight(n, w):
    return w * (exp(2) - 3) * (1 - exp(-2*n)) / (4 * (exp(2) - 1))


Solve in Python:
An area named Renus, is divided into $(N \times M)$ cells. According to archaeological survey the area contains huge amount of treasure. Some cells out of $(N \times M)$ cells contain treasure. But problem is, you can't go to every cell as some of the cells are blocked.
For every $a_{ij}$ cell($1 \leq i \leq N$,$1 \leq j \leq M$), your task is to find the distance of the nearest cell having treasure.
Note:
- You can only traverse up, down, left and right from a given cell.
- Diagonal movements are not allowed.
- Cells having treasure can't be blocked, only empty cells ( cells without treasure) can be blocked.

-----Input Format:------
- First line contains $T$, the number of test cases.
- Second line contains two space-separated integers $N\ and\ M$.
- Third line contains a single integer $X$ denoting number of cells having treasures, followed by $X$ lines containing two space-separated integers $x_i$ and $y_i$ denoting  position of row and column of $i^{th}$ treasure, for every $1\leq i \leq X$
- The next line contains a single integer $Y$ denoting the number of cells that are blocked, and it is followed by subsequent $Y$ lines containing  two space-separated integers $u_i$ and $v_i$ denoting position of row and column of blocked cells , for every $1\leq i \leq Y$

-----Constraints:------
- $1\le T \le 100$
- $1 \le N, M \le 200$
- $1 \le X < N*M$
- $0 \le Y <(N*M) - X$
- $1 \le x_i,u_j \le N, for\ every\ 1 \le i \le X\ and\ 1 \le j \le Y$
- $1 \le y_i,v_j \le M, for\ every\ 1 \le i \le X\ and\ 1 \le j \le Y$

-----Output Format:------
For each test case print a $N \times M$ matrix where each cell consists of distance of nearest treasure. Cells that are blocked will show "$X$" (without quotes). Also cells that doesn't have access to any treasure will show "$-1$" (without quotes).
Note: Co-ordinate of top left cell is $(1,1)$.

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

-----Sample Output-----
0 1 0
X X 1
4 3 2

-----Explanation:-----
- Coordinates  (1,1) and (1,3)  shows "0" because they contain...

t=int(input())
for _ in range(t):
 n,m=[int(x) for x in input().split()]
 mat=[]
 ans=[]
 for i in range(n+2):
  l=[]
  p=[]
  for j in range(m+2):
   l.append(0)
   p.append(1000000000)
  mat.append(l)
  ans.append(p)
 y=int(input())
 for i in range(y):
  a,b=[int(x) for x in input().split()]
  mat[a][b]=1
  ans[a][b]=0
 y=int(input())
 for i in range(y):
  a,b=[int(x) for x in input().split()]
  mat[a][b]=1000000000
  ans[a][b]=1000000000
 for i in range(1,n+1):
  for j in range(1,m+1):
   if mat[i][j]==1 or mat[i][j]==1000000000:
    continue
   else:
    ans[i][j]=min(ans[i][j],ans[i][j-1]+1,ans[i-1][j]+1)
 for i in range(n,0,-1):
  for j in range(m,0,-1):
   if mat[i][j] == 1 or mat[i][j] == 1000000000:
    continue
   else:
    ans[i][j]=min(ans[i][j],ans[i+1][j]+1,ans[i][j+1]+1)
 for i in range(1,n+1):
  for j in range(m, 0, -1):
   if mat[i][j] == 1 or mat[i][j] == 1000000000:
    continue
   else:
    ans[i][j] = min(ans[i][j], ans[i - 1][j] + 1, ans[i][j + 1] + 1)
 for i in range(n, 0, -1):
  for j in range(1,m+1):
   if mat[i][j] == 1 or mat[i][j] == 1000000000:
    continue
   else:
    ans[i][j] = min(ans[i][j], ans[i + 1][j] + 1, ans[i][j - 1] + 1)
 for i in range(1,n+1):
  for j in range(1,m+1):
   if mat[i][j]==1 or mat[i][j]==1000000000:
    continue
   else:
    ans[i][j]=min(ans[i][j],ans[i][j-1]+1,ans[i-1][j]+1)
 for i in range(n,0,-1):
  for j in range(m,0,-1):
   if mat[i][j] == 1 or mat[i][j] == 1000000000:
    continue
   else:
    ans[i][j]=min(ans[i][j],ans[i+1][j]+1,ans[i][j+1]+1)
 for i in range(1,n+1):
  for j in range(m, 0, -1):
   if mat[i][j] == 1 or mat[i][j] == 1000000000:
    continue
   else:
    ans[i][j] = min(ans[i][j], ans[i - 1][j] + 1, ans[i][j + 1] + 1)
 for i in range(n, 0, -1):
  for j in range(1,m+1):
   if mat[i][j] == 1 or mat[i][j] == 1000000000:
    continue
   else:
    ans[i][j] = min(ans[i][j], ans[i + 1][j] + 1, ans[i][j - 1] + 1)
 for i in range(1,n+1):
  for j in range(1,m+1):
   if mat[i][j]==1000000000:
    print('X',end=" ")
   elif...


def circularly_sorted(arr):
    flag= 0
    for i in range(0, len(arr)):
        prev = arr[i-1]
        if prev > arr[i]:
            flag +=1
    if flag > 1:
        return False
    else:
        return True


Solve in Python:
An array is called `centered-N` if some `consecutive sequence` of elements of the array sum to `N` and this sequence is preceded and followed by the same number of elements.

Example:
```
[3,2,10,4,1,6,9] is centered-15
because the sequence 10,4,1 sums to 15 and the sequence
is preceded by two elements [3,2] and followed by two elements [6,9]

```

Write a method called `isCenteredN` that returns :

- `true` if its array argument is `not empty` and `centered-N` or empty and centered-0
- otherwise returns `false`.

def is_centered(arr, n):
    if (len(arr) % 2 == 0) and n == 0:
        return True
    left, right = (len(arr) // 2, len(arr) // 2) if len(arr) % 2 else (len(arr) // 2 - 1, len(arr) // 2)
    while left >= 0 and right <= len(arr):
        if sum(arr[left:right + 1]) == n:
            return True
        left -= 1
        right += 1
    return False


Solve in Python:
An array is called `zero-balanced` if its elements sum to `0` and for each positive element `n`, there exists another element that is the negative of `n`. Write a function named `ìsZeroBalanced` that returns `true` if its argument is `zero-balanced` array, else return `false`. Note that an `empty array` will not sum to `zero`.

def is_zero_balanced(arr):
    return all(arr) == 0 and sum(arr) == 0


Solve in Python:
An array is defined to be `inertial`if the following conditions hold:
```
a. it contains at least one odd value
b. the maximum value in the array is even
c. every odd value is greater than every even value that is not the maximum value.
```
eg:-
```
So [11, 4, 20, 9, 2, 8] is inertial because
a. it contains at least one odd value [11,9]
b. the maximum value in the array is 20 which is even
c. the two odd values (11 and 9) are greater than all the even values that are not equal to 20 (the maximum), i.e., [4, 2, 8]
```
Write a function called `is_inertial` that accepts an integer array and returns `true` if the array is inertial; otherwise it returns `false`.

def is_inertial(arr):
    if not arr or len(arr)<2: return False
    m1=max(arr)
    m2,m_odd=max(arr[1:],key=lambda x:(1-(x%2) and x!=m1,x)),min(arr,key=lambda x:(1-x%2,x))
    return bool(m_odd%2) and not bool(m1%2) and bool(m2%2 or m_odd>m2)


Solve in Python:
An array is defined to be `odd-heavy` if it contains at least one odd element and every element whose value is `odd` is greater than
every even-valued element.

eg.
```
Array [11,4,9,2,8] is odd-heavy
because:- its odd elements [11,9] are greater than all the even elements [4,2,8]

Array [11,4,9,2,3,10] is not odd-heavy
because:- one of it's even element 10 from [4,2,10] is greater than two of its odd elements [9,3] from [ 11,9,3]

```
write a function called `isOddHeavy` or `is_odd_heavy` that accepts an integer array and returns `true` if the array is `odd-heavy` else return `false`.

def is_odd_heavy(arr):
    maxEven, minOdd = ( f(filter(lambda n: n%2 == v, arr), default=float("-inf")) for f,v in ((max, 0), (min,1)) )
    return maxEven < minOdd


Solve in Python:
An array is monotonic if it is either monotone increasing or monotone decreasing.
An array A is monotone increasing if for all i <= j, A[i] <= A[j].  An array A is monotone decreasing if for all i <= j, A[i] >= A[j].
Return true if and only if the given array A is monotonic.

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

Example 2:
Input: [6,5,4,4]
Output: true

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

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

Example 5:
Input: [1,1,1]
Output: true

Note:

1 <= A.length <= 50000
-100000 <= A[i] <= 100000

class Solution:
    def isMonotonic(self, arr: List[int]) -> bool:
        length = len(arr)
        dec = inc = 1
        for i in range(length-1):
            if arr[i] < arr[i+1]:
                dec += 1
            elif arr[i] > arr[i+1]:
                inc += 1
            else:
                dec += 1
                inc += 1
        if dec == length:
            return True
        elif inc == length:
            return True
        else:
            return False


Solve in Python:
An array is said to be `hollow` if it contains `3` or more `0`s in the middle that are preceded and followed by the same number of non-zero elements. Furthermore, all the zeroes in the array must be in the middle of the array.

Write a function named `isHollow`/`is_hollow`/`IsHollow` that accepts an integer array and returns `true` if it is a hollow array,else `false`.

def is_hollow(x):
    while x and x[0] != 0 and x[-1] != 0: x = x[1:-1]
    return len(x) > 2 and set(x) == {0}


Solve in Python:
An array of integers $p_{1},p_{2}, \ldots,p_{n}$ is called a permutation if it contains each number from $1$ to $n$ exactly once. For example, the following arrays are permutations: $[3,1,2], [1], [1,2,3,4,5]$ and $[4,3,1,2]$. The following arrays are not permutations: $[2], [1,1], [2,3,4]$.

There is a hidden permutation of length $n$.

For each index $i$, you are given $s_{i}$, which equals to the sum of all $p_{j}$ such that $j < i$ and $p_{j} < p_{i}$. In other words, $s_i$ is the sum of elements before the $i$-th element that are smaller than the $i$-th element.

Your task is to restore the permutation.

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 2 \cdot 10^{5}$) — the size of the permutation.

The second line contains $n$ integers $s_{1}, s_{2}, \ldots, s_{n}$ ($0 \le s_{i} \le \frac{n(n-1)}{2}$).

It is guaranteed that the array $s$ corresponds to a valid permutation of length $n$.

-----Output-----

Print $n$ integers $p_{1}, p_{2}, \ldots, p_{n}$ — the elements of the restored permutation. We can show that the answer is always unique.

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

Output
3 2 1

Input
2
0 1

Output
1 2

Input
5
0 1 1 1 10

Output
1 4 3 2 5

-----Note-----

In the first example for each $i$ there is no index $j$ satisfying both conditions, hence $s_i$ are always $0$.

In the second example for $i = 2$ it happens that $j = 1$ satisfies the conditions, so $s_2 = p_1$.

In the third example for $i = 2, 3, 4$ only $j = 1$ satisfies the conditions, so $s_2 = s_3 = s_4 = 1$. For $i = 5$ all $j = 1, 2, 3, 4$ are possible, so $s_5 = p_1 + p_2 + p_3 + p_4 = 10$.

def sum_number(n,j):
    j[0]=0
    j[1]=0
    for i in range(2,n+1):
        j[i]=j[i-1]+(i-1)
    return(j)
po=int(input())
l=[0]*(po+1)
l1=[int(i) for i in input().split()]
def getsum(BITTree,i):
    s = 0
    while i > 0:
        s += BITTree[i]
        i -= i & (-i)
    return(s)
def updatebit(BITTree , n , i ,v):
    #print('n',n)
    while i <= n:
        #print('i',i)
        BITTree[i] += v
        i += i & (-i)
    #print(BITTree)
for i in range(1,po+1):
    updatebit(l,po,i,i)
output=[0]*po
for i in range(po-1,-1,-1):
    min_=0
    max_=po
    k=l1[i]
    while True:
        x=(min_+max_+1)//2
        if getsum(l,x)>k:
            if getsum(l,x-1)==k:
                output[i]=x
                break
            else:
                #print(x)
                max_=x
        else :
            #print(x)
            min_=x
    updatebit(l,po,x,-x)
print(*output)


Solve in Python:
An array of size N x M represents pixels of an image.
Each cell of this array contains an array of size 3 with the pixel's color information: `[R,G,B]`

Convert the color image, into an *average* greyscale image.

The `[R,G,B]` array contains integers between 0 and 255 for each color.

To transform a color pixel into a greyscale pixel, average the values of that pixel:
```
p = [R,G,B] => [(R+G+B)/3, (R+G+B)/3, (R+G+B)/3]
```

**Note:** the values for the pixel must be integers, therefore you should round floats to the nearest integer.

## Example

Here's an example of a 2x2 image:

Here's the expected image after transformation:

You are always welcome to check out some of my other katas:

Very Easy (Kyu 8)
Add Numbers
Easy (Kyu 7-6)
Convert Color image to greyscale
Array Transformations
Basic Compression
Find Primes in Range
No Ifs No Buts
Medium (Kyu 5-4)
Identify Frames In An Image
Photoshop Like - Magic Wand
Scientific Notation
Vending Machine - FSA
Find Matching Parenthesis
Hard (Kyu 3-2)
Ascii Art Generator

def color_2_grey(colors):
    return [[[round((r + g + b) / 3)] * 3 for r, g, b in row] for row in colors]


Solve in Python:
An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis.
Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap.
Given two axis-aligned rectangles rec1 and rec2, return true if they overlap, otherwise return false.

Example 1:
Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3]
Output: true
Example 2:
Input: rec1 = [0,0,1,1], rec2 = [1,0,2,1]
Output: false
Example 3:
Input: rec1 = [0,0,1,1], rec2 = [2,2,3,3]
Output: false

Constraints:

rect1.length == 4
rect2.length == 4
-109 <= rec1[i], rec2[i] <= 109
rec1[0] <= rec1[2] and rec1[1] <= rec1[3]
rec2[0] <= rec2[2] and rec2[1] <= rec2[3]

class Solution:
    def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
        return rec1[0] < rec2[2] and rec2[0] < rec1[2] and rec1[1] < rec2[3] and rec2[1] < rec1[3]


Solve in Python:
An element in an array is dominant if it is greater than all elements to its right. You will be given an array and your task will be to return a list of all dominant elements. For example:
```Haskell
solve([1,21,4,7,5]) = [21,7,5] because 21, 7 and 5 are greater than elments to their right.
solve([5,4,3,2,1]) = [5,4,3,2,1]

Notice that the last element is always included.
```

More examples in the test cases.

Good luck!

def solve(arr):
    return [a for i, a in enumerate(arr[:-1]) if a > max(arr[i+1:])] + [arr[-1]]


Solve in Python:
An encoded string S is given.  To find and write the decoded string to a tape, the encoded string is read one character at a time and the following steps are taken:

If the character read is a letter, that letter is written onto the tape.
If the character read is a digit (say d), the entire current tape is repeatedly written d-1 more times in total.

Now for some encoded string S, and an index K, find and return the K-th letter (1 indexed) in the decoded string.

Example 1:
Input: S = "leet2code3", K = 10
Output: "o"
Explanation:
The decoded string is "leetleetcodeleetleetcodeleetleetcode".
The 10th letter in the string is "o".

Example 2:
Input: S = "ha22", K = 5
Output: "h"
Explanation:
The decoded string is "hahahaha".  The 5th letter is "h".

Example 3:
Input: S = "a2345678999999999999999", K = 1
Output: "a"
Explanation:
The decoded string is "a" repeated 8301530446056247680 times.  The 1st letter is "a".

Constraints:

2 <= S.length <= 100
S will only contain lowercase letters and digits 2 through 9.
S starts with a letter.
1 <= K <= 10^9
It's guaranteed that K is less than or equal to the length of the decoded string.
The decoded string is guaranteed to have less than 2^63 letters.

class Solution:
    def decodeAtIndex(self, S: str, K: int) -> str:
        size = 0
        # Find size = length of decoded string
        for c in S:
            if c.isdigit():
                size *= int(c)
            else:
                size += 1

        for c in reversed(S):
            K %= size
            if K == 0 and c.isalpha():
                return c

            if c.isdigit():
                size /= int(c)
            else:
                size -= 1


Solve in Python:
An encoder encodes the first $16$ lowercase English letters using $4$ bits each. The first bit (from the left) of the code is $0$ if the letter lies among the first $8$ letters, else it is $1$, signifying that it lies among the last $8$ letters. The second bit of the code is $0$ if the letter lies among the first $4$ letters of those $8$ letters found in the previous step, else it's $1$, signifying that it lies among the last $4$ letters of those $8$ letters. Similarly, the third and the fourth bit each signify the half in which the letter lies.
For example, the letter $j$ would be encoded as :
- Among $(a,b,c,d,e,f,g,h$ $|$ $i,j,k,l,m,n,o,p)$, $j$ appears in the second half. So the first bit of its encoding is $1$.
- Now, among $(i,j,k,l$ $|$ $m,n,o,p)$, $j$ appears in the first half. So the second bit of its encoding is $0$.
- Now, among $(i,j$ $|$ $k,l)$, $j$ appears in the first half. So the third bit of its encoding is $0$.
- Now, among $(i$ $|$ $j)$, $j$ appears in the second half. So the fourth and last bit of its encoding is $1$.
So $j$'s encoding is $1001$,
Given a binary encoded string $S$, of length at most $10^5$, decode the string. That is, the first 4 bits are the encoding of the first letter of the secret message, the next 4 bits encode the second letter, and so on. It is guaranteed that the string's length is a multiple of 4.

-----Input:-----
- The first line of the input contains an integer $T$, denoting the number of test cases.
- The first line of each test case contains an integer $N$, the length of the encoded string.
- The second line of each test case contains the encoded string $S$.

-----Output:-----
For each test case, print the decoded string, in a separate line.

-----Constraints-----
- $1 \leq T \leq 10$
- $4 \leq N \leq 10^5$
- The length of the encoded string is a multiple of $4$.
- $0 \le S_i \le 1$

-----Subtasks-----
- $100$ points : Original constraints.

-----Sample Input:-----
3
4
0000
8
00001111
4
1001

-----Sample Output:-----
a
ap
j

-----Explanation:-----
- Sample...


Solve in Python:
An even sequence has the following property: each maximal contiguous subsequence which contains only equal integers (i.e. the same integer repeated a number of times) has an even length. In particular, the empty sequence is even. A subsequence is maximal if it is not contained in a larger contiguous subsequence which contains only equal integers.
Chef was given an integer sequence $A_1, A_2, \ldots, A_N$ by his friend Mr. Z. He may perform the following operation any number of times: either delete an element of the current sequence (if it is non-empty) or insert an integer anywhere in the current sequence (possibly at the beginning or at the end).
Find the minimum number of operations needed to make the sequence even.

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

-----Output-----
For each test case, print a single line containing one integer — the minimum number of operations.

-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq N \leq 2 \cdot 10^5$
- $1 \leq A_i \leq N$ for each valid $i$
- the sum of $N$ over all test cases does not exceed $2 \cdot 10^6$

-----Subtasks-----
Subtask #1 (10 points): $N \leq 18$
Subtask #2 (10 points): $A_i \leq A_{i+1}$ for each valid $i$
Subtask #3 (20 points): $N \leq 3,000$
Subtask #4 (20 points): $A_i \leq 26$ for each valid $i$
Subtask #5 (40 points): original constraints

-----Example Input-----
2
4
1 1 2 1
11
2 2 2 10 2 10 1 1 5 3 5

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

-----Explanation-----
Example case 1: Here are two ways to make the sequence even using $2$ operations:
- Delete the first element $1$ and the only element $2$, resulting in a sequence $(1, 1)$, which is even.
- Delete the last element $1$ and insert $2$ at the end, resulting in a sequence $(1,1,2,2)$, which is even.
It can be proved that one operation is...

t = int(input())

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

 s = set()

 count = 0
 for i in l:
  if i in s:
   count += 2
   s.clear()
  else:
   s.add(i)

 print(n-count)


Solve in Python:
An eviternity number is a number which:
* contains only digits 8, 5 and 3, and
* the count of the digit `8` >= count of digit `5` >= count of digit `3`.

The first few eviternity numbers are as follows.
```Haskell
[8, 58, 85, 88, 358, 385, 538, 583, 588, 835, 853, 858, 885, 888]
```
You will be given two integers, `a` and `b`, and your task is to return the number of eviternity numbers in the range `>= a and < b`.
```Haskell
For example:
solve(0,1000) = 14, because they are [8, 58, 85, 88, 358, 385, 538, 583, 588, 835, 853, 858, 885, 888]
```

The upper bound will not exceed `500,000`.

More examples in test cases. Good luck!

def solve(a,b):
    number_counter = 0
    for i in range(a, b):
        number = str(i)
        if '0' in number or '1' in number or '2' in number or '4' in number or '6' in number or '7' in number or '9' in number:
            continue
        a = number.count('3')
        b = number.count('5')
        c = number.count('8')
        if(a + b + c == len(number)) and (a <= b) and (b <= c):
            number_counter +=1
    return number_counter


Solve in Python:
An expression is formed by taking the digits 1 to 9 in numerical order and then inserting into each gap between the numbers either a plus sign or a minus sign or neither.

Your task is to write a method which takes one parameter and returns the **smallest possible number** of plus and minus signs necessary to form such an expression which equals the input.

**Note:** All digits from 1-9 must be used exactly once.

If there is no possible expression that evaluates to the input, then return `null/nil/None`.

~~~if:haskell
`eval :: String -> Int` is available in `Preloaded` for your convenience.
~~~

There are 50 random tests with upper bound of the input = 1000.

## Examples

When the input is 100, you need to return `3`, since that is the minimum number of signs required, because: 123 - 45 - 67 + 89 = 100 (3 operators in total).

More examples:
```
 11  -->  5  #  1 + 2 + 34 + 56 + 7 - 89 = 11
100  -->  3  #  123 - 45 - 67 + 89 = 100
766  -->  4  #  1 - 2 + 34 - 56 + 789 = 766
160  -->  -  #  no solution possible
```

Inspired by a [puzzle on BBC Radio 4](https://www.bbc.co.uk/programmes/p057wxwl) (which is unfortunately not available anymore)

from itertools import chain, zip_longest

def operator_insertor(target):
    return min((x.count('+') + x.count('-') for x in insertions(target, [1, 2, 3, 4, 5, 6, 7, 8, 9])), default=None)

def insertions(rem, nums, ops=''):
    if len(nums) == 1:
        return ([''.join(map(''.join, zip_longest('123456789', ops, fillvalue=''))).replace('|', '')]
                if rem - nums[0] == 0 else [])
    return list(chain(insertions(rem - nums[0], nums[1:], ops + '+'),
                      insertions(rem - nums[0], [-nums[1]] + nums[2:], ops + '-'),
                      insertions(rem, [int(f'{nums[0]}{nums[1]}')] + nums[2:], ops + '|')))


Solve in Python:
An integer partition of n is a weakly decreasing list of positive integers which sum to n.

For example, there are 7 integer partitions of 5:

[5], [4,1], [3,2], [3,1,1], [2,2,1], [2,1,1,1], [1,1,1,1,1].

Write a function named partitions which returns the number of integer partitions of n.  The function should be able to find the number of integer partitions of n for n as least as large as 100.

from functools import lru_cache

@lru_cache(maxsize=None)
def partitions(n, start=1):
    if n == 0:
        return 1
    elif n < 0:
        return 0
    return sum(partitions(n-i, i) for i in range(start, n+1))


Solve in Python:
An integral:

can be approximated by the so-called Simpson’s rule:

Here `h = (b-a)/n`, `n` being an even integer and `a <= b`.

We want to try Simpson's rule with the function f:

The task is to write a function called `simpson` with parameter `n` which returns the value of the integral of f on the interval `[0, pi]` (pi being 3.14159265359...).
## Notes:
- Don't round or truncate your results. See in "RUN EXAMPLES" the function `assertFuzzyEquals` or `testing`.
- `n` will always be even.

- We know that the exact value of the integral of f on the given interval is `2`.

You can see:
about rectangle method and trapezoidal rule.

import math

def simpson(n):
    a, b = 0, math.pi
    f = lambda x: (3/2) * (math.sin(x) ** 3)
    h = (b - a) / n
    res = f(a)
    res += 4 * sum(f(a + i*h) for i in range(1, n, 2))
    res += 2 * sum(f(a + i*h) for i in range(2, n, 2))
    res += f(b)
    return (h / 3) * res


Solve in Python:
An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case.

```python
is_isogram("Dermatoglyphics" ) == true
is_isogram("aba" ) == false
is_isogram("moOse" ) == false # -- ignore letter case
```
```C
is_isogram("Dermatoglyphics" ) == true;
is_isogram("aba" ) == false;
is_isogram("moOse" ) == false; // -- ignore letter case
```

def is_isogram(string):
    return len(string) == len(set(string.lower()))


Solve in Python:
An onion array is an array that satisfies the following condition for all values of `j` and `k`:

If all of the following are `true`:

* `j >= 0`
* `k >= 0`
* `j + k = array.length - 1`
* `j != k`

then:

* `a[j] + a[k] <= 10`

### Examples:

```
[1, 2, 19, 4, 5]   =>  true  (as 1+5 <= 10 and 2+4 <= 10)
[1, 2, 19, 4, 10]  =>  false (as 1+10 > 10)
```

Write a function named `isOnionArray`/`IsOnionArray`/`is_onion_array()` that returns `true` if its argument is an onion array and returns `false` if it is not.

~~~if:php
Your solution should at least be moderately efficient.  Make sure you don't do any unnecessary looping ;)
~~~

def is_onion_array(a):
    print(a)
    for num in range(len(a)):
        if a[num] !=a[-(num+1)]:
            if not a[num] + a[-(num + 1)] <=10:
                return False

    return True


Solve in Python:
An ordered sequence of numbers from 1 to N is given. One number might have deleted from it, then the remaining numbers were mixed. Find the number that was deleted.

Example:
 - The starting array sequence is `[1,2,3,4,5,6,7,8,9]`
 - The mixed array with one deleted number is `[3,2,4,6,7,8,1,9]`
 - Your function should return the int `5`.

If no number was deleted from the array and no difference with it, your function should return the int `0`.

Note that N may be 1 or less (in the latter case, the first array will be `[]`).

def find_deleted_number(arr, mixed_arr):
    return sum(arr)-sum(mixed_arr)


Solve in Python:
An undirected, connected tree with N nodes labelled 0...N-1 and N-1 edges are given.
The ith edge connects nodes edges[i][0] and edges[i][1] together.
Return a list ans, where ans[i] is the sum of the distances between node i and all other nodes.
Example 1:
Input: N = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]
Output: [8,12,6,10,10,10]
Explanation:
Here is a diagram of the given tree:
  0
 / \
1   2
   /|\
  3 4 5
We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)
equals 1 + 1 + 2 + 2 + 2 = 8.  Hence, answer[0] = 8, and so on.

Note: 1 <= N <= 10000

class Solution:
    def sumOfDistancesInTree(self, N: int, edges: List[List[int]]) -> List[int]:
        edges_dict = dict()
        for i in range(N):
            edges_dict[i] = []
        for edge in edges:
            edges_dict[edge[0]].append(edge[1])
            edges_dict[edge[1]].append(edge[0])
        dp_dict = dict()
        def dp(node, src):
            if (node, src) in dp_dict:
                return dp_dict[(node, src)]
            tgt_num = 1
            tgt_sum = 0
            for tgt in edges_dict[node]:
                if tgt == src:
                    continue
                else:
                    temp = dp(tgt, node)
                    tgt_num += temp[0]
                    tgt_sum += temp[0] + temp[1]
            dp_dict[(node, src)] = (tgt_num, tgt_sum)
            return dp_dict[(node, src)]
        results = [0]*N
        for node in range(N):
            for tgt in edges_dict[node]:
                results[node] += sum(dp(tgt, node))
        # print(dp_dict)
        return results