Solve in Python:
Ask a small girl - "How old are you?". She always says strange things... Lets help her!

For correct answer program should return int from 0 to 9.

Assume test input string always valid and may look like
"1 year old" or "5 years old", etc.. The first char is number only.

def get_age(age):
    k = str(age)
    for i in k:
        if i.isdigit() == True:
            return int(i)


Solve in Python:
Assume `"#"` is like a backspace in string. This means that string `"a#bc#d"` actually is `"bd"`

Your task is to process a string with `"#"` symbols.

## Examples

```
"abc#d##c"      ==>  "ac"
"abc##d######"  ==>  ""
"#######"       ==>  ""
""              ==>  ""
```

def clean_string(s):
    arr = []
    for a in s:
        if a != '#':
            arr.append(a)
        elif arr:
            arr.pop()
    return ''.join(arr)


Solve in Python:
Assume that you have $k$ one-dimensional segments $s_1, s_2, \dots s_k$ (each segment is denoted by two integers — its endpoints). Then you can build the following graph on these segments. The graph consists of $k$ vertexes, and there is an edge between the $i$-th and the $j$-th vertexes ($i \neq j$) if and only if the segments $s_i$ and $s_j$ intersect (there exists at least one point that belongs to both of them).

For example, if $s_1 = [1, 6], s_2 = [8, 20], s_3 = [4, 10], s_4 = [2, 13], s_5 = [17, 18]$, then the resulting graph is the following: [Image]

A tree of size $m$ is good if it is possible to choose $m$ one-dimensional segments so that the graph built on these segments coincides with this tree.

You are given a tree, you have to find its good subtree with maximum possible size. Recall that a subtree is a connected subgraph of a tree.

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

-----Input-----

The first line contains one integer $q$ ($1 \le q \le 15 \cdot 10^4$) — the number of the queries.

The first line of each query contains one integer $n$ ($2 \le n \le 3 \cdot 10^5$) — the number of vertices in the tree.

Each of the next $n - 1$ lines contains two integers $x$ and $y$ ($1 \le x, y \le n$) denoting an edge between vertices $x$ and $y$. It is guaranteed that the given graph is a tree.

It is guaranteed that the sum of all $n$ does not exceed $3 \cdot 10^5$.

-----Output-----

For each query print one integer — the maximum size of a good subtree of the given tree.

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

Output
8

-----Note-----

In the first query there is a good subtree of size $8$. The vertices belonging to this subtree are ${9, 4, 10, 2, 5, 1, 6, 3}$.

import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
  n = int(input())
  ab = [list(map(int,input().split())) for i in range(n-1)]
  graph = [[] for i in range(n+1)]
  deg = [0]*(n+1)
  for a,b in ab:
    graph[a].append(b)
    graph[b].append(a)
    deg[a] += 1
    deg[b] += 1
  pnt = [max(deg[i]-1,1) for i in range(n+1)]
  root = 1
  stack = [root]
  dist = [0]*(n+1)
  dist[root] = pnt[root]
  while stack:
    x = stack.pop()
    for y in graph[x]:
      if dist[y] == 0:
        dist[y] = dist[x]+pnt[y]
        stack.append(y)
  far = dist.index(max(dist))
  root = far
  stack = [root]
  dist = [0]*(n+1)
  dist[root] = pnt[root]
  while stack:
    x = stack.pop()
    for y in graph[x]:
      if dist[y] == 0:
        dist[y] = dist[x]+pnt[y]
        stack.append(y)
  print(max(dist))


Solve in Python:
Assume that you started to store items in progressively expanding square location, like this for the first 9 numbers:

```
05 04 03
06 01 02
07 08 09
```

And like this for the expanding to include up to the first 25 numbers:

```
17 16 15 14 13
18 05 04 03 12
19 06 01 02 11
20 07 08 09 10
21 22 23 24 25
```

You might easily notice that the first - and innermost - layer containes only one number (`01`), the second one  - immediately around it - contains 8 numbers (number in the `02-09` range) and so on.

Your task is to create a function that given a number `n` simply returns the number of layers required to store up to `n` (included).

```python
layers(1) == 1
layers(5) == 2
layers(25) == 3
layers(30) == 4
layers(50) == 5
```

**Fair warning:** you will always and only get positive integers, but be ready for bigger numbers in the tests!

If you had fun with this, also try some follow up kata: [progressive spiral number branch](https://www.codewars.com/kata/progressive-spiral-number-branch/) and [progressive spiral number distance](https://www.codewars.com/kata/progressive-spiral-number-distance/).

*[Base idea taken from [here](http://adventofcode.com/2017/day/3)]*


Solve in Python:
Assume we take a number `x` and perform any one of the following operations:
```Pearl
a) Divide x by 3 (if it is divisible by 3), or
b) Multiply x by 2
```
After each operation, we write down the result. If we start with `9`, we can get a sequence such as:
```
[9,3,6,12,4,8] -- 9/3=3 -> 3*2=6 -> 6*2=12 -> 12/3=4 -> 4*2=8
```
You will be given a shuffled sequence of integers and your task is to reorder them so that they conform to the above sequence. There will always be an answer.
```
For the above example:
solve([12,3,9,4,6,8]) = [9,3,6,12,4,8].
```

More examples in the test cases. Good luck!

def solve(arr):
    fn = lambda p: lambda n: 0 if n % p else 1 + fn(p)(n // p)
    return sorted(sorted(arr, key=fn(3), reverse=True), key=fn(2))


Solve in Python:
Assume you are creating a webshop and you would like to help the user in the search. You have products with brands, prices and name. You have the history of opened products (the most recently opened being the first item).

Your task is to create a list of brands ordered by popularity, if two brands have the same popularity level then choose the one which was opened last from the two and second the other one.

Product popularity is calculated from the history. If a product is more times in the history than it is more popular.

Your function will have one parameter which will be always an array/list of object.

example product:
{
  name: "Phone",
  price: 25,
  brand: "Fake brand"
}

def sorted_brands(history):
    d = {}
    for i in history:
        if i['brand'] in d:
            d[i['brand']] += 1
        else:
            d[i['brand']] = 1
    return sorted(list(d.keys()), key=lambda x: d[x], reverse=True)


Solve in Python:
At a lemonade stand, each lemonade costs $5.
Customers are standing in a queue to buy from you, and order one at a time (in the order specified by bills).
Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill.  You must provide the correct change to each customer, so that the net transaction is that the customer pays $5.
Note that you don't have any change in hand at first.
Return true if and only if you can provide every customer with correct change.

Example 1:
Input: [5,5,5,10,20]
Output: true
Explanation:
From the first 3 customers, we collect three $5 bills in order.
From the fourth customer, we collect a $10 bill and give back a $5.
From the fifth customer, we give a $10 bill and a $5 bill.
Since all customers got correct change, we output true.

Example 2:
Input: [5,5,10]
Output: true

Example 3:
Input: [10,10]
Output: false

Example 4:
Input: [5,5,10,10,20]
Output: false
Explanation:
From the first two customers in order, we collect two $5 bills.
For the next two customers in order, we collect a $10 bill and give back a $5 bill.
For the last customer, we can't give change of $15 back because we only have two $10 bills.
Since not every customer received correct change, the answer is false.

Note:

0 <= bills.length <= 10000
bills[i] will be either 5, 10, or 20.

class Solution:
    def lemonadeChange(self, bills: List[int]) -> bool:
        cash = {20: 0,
                10: 0,
                 5: 0}
        for paid in bills:
            refund = paid - 5
            if refund == 0:
                cash[5] += 1
                continue
            flag = False
            for note in cash:
                if cash[note]>= refund//note:
                    cash[note] -= refund // note
                    refund -= (refund// note) *note
                    flag = True
            if not flag or refund>0:
                return False
            cash[paid] += 1
        return True


Solve in Python:
At the annual family gathering, the family likes to find the oldest living family member’s age and the youngest family member’s age and calculate the difference between them.

You will be given an array of all the family members' ages, in any order.  The ages will be given in whole numbers, so a baby of 5 months, will have an ascribed ‘age’ of 0.  Return a new array (a tuple in Python) with [youngest age, oldest age, difference between the youngest and oldest age].

def difference_in_ages(ages):
    ages.sort()
    older = ages[-1]
    younger = ages[0]
    difference = older - younger
    return (younger, older, difference)


Solve in Python:
At the legendary times of Nonsenso wars in ISM Dhanbad, there was a neck to neck competition between Barney Stinson and Sheldon Cooper. They both were on level 19. After trying too hard both of them could not decipher the nonsense, so they decided to play alongside. Sheldon Cooper had to pass a message to Barney Stinson. So he decided to convert each letter of the sentence to their corresponding to their ASCII codes. When Barney received the message he could not get anything. Now you have to design a code which converts the encrypted message to readable format.

-----Input-----
The input will consist of the first line containing the number of test cases ‘n’ followed by n lines of test cases.

-----Output-----

For each input print the decoded line.

-----Example-----
Input:
2
721011081081113287111114108100
871011089911110910132116111327311010010597

Output:
Hello World
Welcome to India

for _ in range(int(input())):
 code=input().strip()+'0'
 message=''
 asc=int(code[0])

 for i in range(len(code)-1):

  if int(str(asc)+code[i+1])>256:
   message+=chr(asc)
   asc=int(code[i+1])
  else:
   asc=int(str(asc)+code[i+1])

 print(message)


Solve in Python:
At the start of each season, every player in a football team is assigned their own unique squad number. Due to superstition or their history certain numbers are more desirable than others.

Write a function generateNumber() that takes two arguments, an array of the current squad numbers (squad) and the new player's desired number (n). If the new player's desired number is not already taken, return n, else if the desired number can be formed by adding two digits between 1 and 9, return the number formed by joining these two digits together. E.g. If 2 is taken, return 11 because 1 + 1 = 2. Otherwise return null.

Note: Often there will be several different ways to form a replacement number. In these cases the number with lowest first digit should be given priority. E.g. If n = 15, but squad already contains 15, return 69, not 78.

def generate_number(squad,n):
    if n not in squad:return n
    for i in range(n-9,10):
        d=int(f"{i}{n-i}")
        if d not in squad and (n-i)>0:
            return d


Solve in Python:
AtCoDeer the deer found N rectangle lying on the table, each with height 1.
If we consider the surface of the desk as a two-dimensional plane, the i-th rectangle i(1≤i≤N) covers the vertical range of [i-1,i] and the horizontal range of [l_i,r_i], as shown in the following figure:

AtCoDeer will move these rectangles horizontally so that all the rectangles are connected.
For each rectangle, the cost to move it horizontally by a distance of x, is x.
Find the minimum cost to achieve connectivity.
It can be proved that this value is always an integer under the constraints of the problem.

-----Constraints-----
 - All input values are integers.
 - 1≤N≤10^5
 - 1≤l_i<r_i≤10^9

-----Partial Score-----
 - 300 points will be awarded for passing the test set satisfying 1≤N≤400 and 1≤l_i<r_i≤400.

-----Input-----
The input is given from Standard Input in the following format:
N
l_1 r_1
l_2 r_2
:
l_N r_N

-----Output-----
Print the minimum cost to achieve connectivity.

-----Sample Input-----
3
1 3
5 7
1 3

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

The second rectangle should be moved to the left by a distance of 2.

# seishin.py
N = int(input())
P = [list(map(int, input().split())) for i in range(N)]

INF = 10**18

from heapq import heappush, heappop

l0, r0 = P[0]

L = [-l0+1]
R = [l0-1]
s = t = 0

def debug(L, s, t, R):
    L0 = L[:]
    Q1 = []; Q2 = []
    while L0:
        Q1.append(-s-heappop(L0))
    R0 = R[:]
    while R0:
        Q2.append(t+heappop(R0))
    print(("debug:", *Q1[::-1]+Q2))

#print(L, s, t, R)
res = 0
for i in range(N-1):
    l0, r0 = P[i]
    l1, r1 = P[i+1]
    #print(">", l1, r1)
    s += (r1 - l1); t += (r0 - l0)
    if -s-L[0] <= l1-1 <= t+R[0]:
        #print(0)
        heappush(L, -l1+1-s)
        heappush(R, l1-1-t)
        # res += 0
    elif l1-1 < -s-L[0]:
        #print(1)
        heappush(L, -l1+1-s)
        heappush(L, -l1+1-s)
        p = -heappop(L)-s
        #d = (-L[0]-s) - p
        heappush(R, p-t)
        #print(d)
        #res += d
        res += (p - (l1-1))
    elif t+R[0] < l1-1:
        #print(2)
        heappush(R, l1-1-t)
        heappush(R, l1-1-t)
        p = heappop(R) + t
        #d = R[0]+t - p
        heappush(L, -p-s)
        #print(d)
        res += (l1-1 - p)
    #print(L, s, t, R, -s-L[0], R[0]+t, res)
    #debug(L, s, t, R)
print(res)


Solve in Python:
Aureole the Techno-cultural fest of JEC thought of conducting a workshop on big data, as the topic is hot everyone wants to take part but due to limited seats in the Jashan Auditorium there is a selection criteria, a problem is given.
the problem states a string is to be compressed when two or more consecutive characters are same they are to be compressed into one character and the original number count is to be written after it ex. aaabb -> a3b2
where every character is of 8bits and every integer is of 32bits
you are asked to find the difference in size between original string and compressed string

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

-----Output:-----
For each testcase, output in a single line The difference in size.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq |S| \leq 10^5$

-----Subtasks-----
- 40 points : S will contain only a-z
- 60 points : S will contain 0-9 characters also

-----Sample Input:-----
1
aaabb

-----Sample Output:-----
-40

-----EXPLANATION:-----
the resulting string will be a3b2 its size will be 80, original string size will be 40 so ans= 40-80

t=int(input())
for _ in range(t):
    s=input()
    x=""
    i=0
    ans=0
    while i<len(s):
        x=s[i]
        c=1
        i+=1
        while i<len(s) and s[i]==x:
            i+=1
            c+=1
        if c==1:
            ans+=8
        else:
            ans+=40
    m=8*len(s)
    print(m-ans)


Solve in Python:
Autobots are instructed by Optimus Prime to mobilize in the form of a rectangular shape with each Autobot on each vertex of the rectangle region on a -”deployment area” (which may consist of one or more regions). This is done so as to take care of the inner rectangular area called “region”. However the rule states-“no two regions may overlap”.  You have been asked to remove some regions from the “deployment area” so the remaining regions do not obscure each other. To keep the disturbance to the minimum level, you should remove the minimum number of regions to achieve this goal. You may not remove a region and place it in another position; all regions you leave in “deployment area” must be in their original position.
When you examined the “deployment area”, you noticed something very nice. Every region was placed on the deployment area by placing each autobot in the four corners. This was done in a very courteous manner since each autobot is guarding only the region it is holding.
The reason Optimus Prime wants your help because you are good at taking down a single region without disturbing the rest, even if that region is obscured by many others.

-----Input-----
The first line consists of a single integer T indicating the number of test cases (about 25).
Each test case consists begins with a single integer n indicating the number of regions. The next n lines consist of 4 integers x0, x1, y0, and y1 satisfying x0 < x1 and y0 < y1. This means the region covers all points (x,y) satisfying x0 <= x <= x1 and y0 <= y <= y1.
As stated before hand, no corner of any region will intersect any other region anywhere. That is, if (x,y) is a corner point of one region and another region is described by x0, x1, y0, and y1, then we do not have x0 <= x <= x1 and y0 <= y <= y1.
Bounds: 1 <= n <= 100 and each integer in a region description fits in a signed 32 bit integer.

-----Output-----
The output for each test case is a single line containing a single integer that is the maximum number of regions that can be left on the...


Solve in Python:
Automatons, or Finite State Machines (FSM), are extremely useful to programmers when it comes to software design. You will be given a simplistic version of an FSM to code for a basic TCP session.

The outcome of this exercise will be to return the correct state of the TCP FSM based on the array of events given.

---------------------------------

The input array of events will consist of one or more of the following strings:

```
APP_PASSIVE_OPEN, APP_ACTIVE_OPEN, APP_SEND, APP_CLOSE, APP_TIMEOUT, RCV_SYN, RCV_ACK, RCV_SYN_ACK, RCV_FIN, RCV_FIN_ACK
```

---------------------------------

The states are as follows and should be returned in all capital letters as shown:

```
CLOSED, LISTEN, SYN_SENT, SYN_RCVD, ESTABLISHED, CLOSE_WAIT, LAST_ACK, FIN_WAIT_1, FIN_WAIT_2, CLOSING, TIME_WAIT
```

---------------------------------

The input will be an array of events. Your job is to traverse the FSM as determined by the events, and return the proper state as a string, all caps, as shown above.

If an event is not applicable to the current state, your code will return `"ERROR"`.

### Action of each event upon each state:
(the format is `INITIAL_STATE: EVENT -> NEW_STATE`)

```
CLOSED: APP_PASSIVE_OPEN -> LISTEN
CLOSED: APP_ACTIVE_OPEN  -> SYN_SENT
LISTEN: RCV_SYN          -> SYN_RCVD
LISTEN: APP_SEND         -> SYN_SENT
LISTEN: APP_CLOSE        -> CLOSED
SYN_RCVD: APP_CLOSE      -> FIN_WAIT_1
SYN_RCVD: RCV_ACK        -> ESTABLISHED
SYN_SENT: RCV_SYN        -> SYN_RCVD
SYN_SENT: RCV_SYN_ACK    -> ESTABLISHED
SYN_SENT: APP_CLOSE      -> CLOSED
ESTABLISHED: APP_CLOSE   -> FIN_WAIT_1
ESTABLISHED: RCV_FIN     -> CLOSE_WAIT
FIN_WAIT_1: RCV_FIN      -> CLOSING
FIN_WAIT_1: RCV_FIN_ACK  -> TIME_WAIT
FIN_WAIT_1: RCV_ACK      -> FIN_WAIT_2
CLOSING: RCV_ACK         -> TIME_WAIT
FIN_WAIT_2: RCV_FIN      -> TIME_WAIT
TIME_WAIT: APP_TIMEOUT   -> CLOSED
CLOSE_WAIT: APP_CLOSE    -> LAST_ACK
LAST_ACK: RCV_ACK        -> CLOSED
```

!["EFSM TCP" ](http://theangelfallseries.com/img/EFSM_TCP.png)

## Examples

```
["APP_PASSIVE_OPEN",...

NEW_STATE = {
"CLOSED__APP_PASSIVE_OPEN" : "LISTEN",
"CLOSED__APP_ACTIVE_OPEN"  : "SYN_SENT",
"LISTEN__RCV_SYN"          : "SYN_RCVD",
"LISTEN__APP_SEND"         : "SYN_SENT",
"LISTEN__APP_CLOSE"        : "CLOSED",
"SYN_RCVD__APP_CLOSE"      : "FIN_WAIT_1",
"SYN_RCVD__RCV_ACK"        : "ESTABLISHED",
"SYN_SENT__RCV_SYN"        : "SYN_RCVD",
"SYN_SENT__RCV_SYN_ACK"    : "ESTABLISHED",
"SYN_SENT__APP_CLOSE"      : "CLOSED",
"ESTABLISHED__APP_CLOSE"   : "FIN_WAIT_1",
"ESTABLISHED__RCV_FIN"     : "CLOSE_WAIT",
"FIN_WAIT_1__RCV_FIN"      : "CLOSING",
"FIN_WAIT_1__RCV_FIN_ACK"  : "TIME_WAIT",
"FIN_WAIT_1__RCV_ACK"      : "FIN_WAIT_2",
"CLOSING__RCV_ACK"         : "TIME_WAIT",
"FIN_WAIT_2__RCV_FIN"      : "TIME_WAIT",
"TIME_WAIT__APP_TIMEOUT"   : "CLOSED",
"CLOSE_WAIT__APP_CLOSE"    : "LAST_ACK",
"LAST_ACK__RCV_ACK"        : "CLOSED" }

def traverse_TCP_states(events, state="CLOSED"):
    for event in events:
        QUERY = "%s__%s" % (state, event)
        if QUERY in NEW_STATE:
            state = NEW_STATE[QUERY]
        else:
            return "ERROR"

    return state


Solve in Python:
Ayoub thinks that he is a very smart person, so he created a function $f(s)$, where $s$ is a binary string (a string which contains only symbols "0" and "1"). The function $f(s)$ is equal to the number of substrings in the string $s$ that contains at least one symbol, that is equal to "1".

More formally, $f(s)$ is equal to the number of pairs of integers $(l, r)$, such that $1 \leq l \leq r \leq |s|$ (where $|s|$ is equal to the length of string $s$), such that at least one of the symbols $s_l, s_{l+1}, \ldots, s_r$ is equal to "1".

For example, if $s = $"01010" then $f(s) = 12$, because there are $12$ such pairs $(l, r)$: $(1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 4), (4, 5)$.

Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers $n$ and $m$ and asked him this problem. For all binary strings $s$ of length $n$ which contains exactly $m$ symbols equal to "1", find the maximum value of $f(s)$.

Mahmoud couldn't solve the problem so he asked you for help. Can you help him?

-----Input-----

The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \leq t \leq 10^5$)  — the number of test cases. The description of the test cases follows.

The only line for each test case contains two integers $n$, $m$ ($1 \leq n \leq 10^{9}$, $0 \leq m \leq n$) — the length of the string and the number of symbols equal to "1" in it.

-----Output-----

For every test case print one integer number — the maximum value of $f(s)$ over all strings $s$ of length $n$, which has exactly $m$ symbols, equal to "1".

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

Output
4
5
6
0
12

-----Note-----

In the first test case, there exists only $3$ strings of length $3$, which has exactly $1$ symbol, equal to "1". These strings are: $s_1 = $"100", $s_2 = $"010", $s_3 = $"001". The values of $f$ for them are: $f(s_1) = 3, f(s_2) = 4, f(s_3) = 3$, so the maximum value is $4$ and the answer is $4$.

In the second test case, the string $s$...

import sys
readline = sys.stdin.readline
T = int(readline())
Ans = [None]*T
def calc(d):
    return d*(d+1)//2

for qu in range(T):
    N, M = list(map(int, readline().split()))
    seg = M+1
    leng = N-M
    Ans[qu] = calc(N) - calc(leng//seg) * (seg-leng%seg) - calc(leng//seg+1) *(leng%seg)

print('\n'.join(map(str, Ans)))


Solve in Python:
Ayu loves distinct letter sequences ,a distinct letter sequence is defined by a sequence of small case english alphabets such that no character appears more then once.
But however there are two phrases that she doesn't like these phrases are "kar" and "shi" and she is given a sequence of distinct characters and she wonders how many such sequences she can form using all the characters such that these phrases don't occur.
Help her finding the number of such sequences.
New Year Gift - It is guaranteed that for sequences of length greater then 6 letters k,a,r,s,h,i will be present(we thought of being generous, thank us later :)).

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each line consists of a string $S$ (3<=s.length<=18) of distinct characters.

-----Output:-----
Print the number of sequences that can be formed by permuting all the characters such that phrases "kar" and "shi" don't occur.

-----Constraints-----
- $1 \leq T \leq 10$
- $3 \leq S.length \leq 18$

-----Sample Input:-----
2
karp
abcd

-----Sample Output:-----
22
24

# cook your dish here
from collections import deque, defaultdict
from math import sqrt, ceil,factorial
import sys
import copy
def get_array(): return list(map(int, sys.stdin.readline().strip().split()))
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def input(): return sys.stdin.readline().strip()

for _ in range(int(input())):

    s=input()
    if len(s)>6:
        ans=0
        rem=len(s)-6
        ans+=factorial(len(s))
        ans-=2*(factorial(len(s)-2))
        ans+=factorial(rem+2)
        print(ans)

    else:
        if 'k' in s and 'r' in s and 'a' in s and 's' in s and 'h' in s and 'i' in s:
            ans = 0
            rem = len(s) - 6
            ans += factorial(len(s))
            ans -= 2 * (factorial(len(s) - 2))
            ans += factorial(rem + 2)
            print(ans)
        else:
            if 'k' in s and 'a' in s and 'r' in s:
                ans=0
                rem=len(s)-3
                ans+=factorial(len(s))
                ans-=factorial(rem+1)
                print(ans)
                continue
            if 's' in s and 'h' in s and 'i' in s:
                ans = 0
                rem = len(s) - 3
                ans += factorial(len(s))
                ans -= factorial(rem + 1)
                print(ans)
                continue

            print(factorial(len(s)))


Solve in Python:
Baby is getting his frst tooth. This means more sleepless nights, but with the fun of feeling round his gums and trying to guess which will be first out!

Probably best have a sweepstake with your friends - because you have the best chance of knowing. You can feel the gums and see where the raised bits are - most raised, most likely tooth to come through first!

Given an array of numbers (t) to represent baby's gums, you need to return the index of the lump that is most pronounced.

The most pronounced lump is the one that has the biggest differential to its surrounding values. e.g.:

```
[1, 2, 4] = 2

index 0 has a differential of -1 to its right (it is lower so the figure is negative)

index 1 has a differential of +1 to its left, and -2 to its right. Total is -1.

index 2 has a differential of +2 to its left, and nothing to its right,
```

If there is no distinct highest value (more than one occurence of the largest differential), return -1.

def first_tooth(array):

    if len(array) <= 1:
        return 0

    differentials = []
    differentials.append(array[0]-array[1])

    for i in range(1,len(array)-1):
        differentials.append(2*array[i]-array[i-1]-array[i+1])

    differentials.append(array[-1]-array[-2])

    if differentials.count(max(differentials)) > 1:
        return -1
    else:
        return differentials.index(max(differentials))


Solve in Python:
Back in 2015, Usain Bolt announced that he'll be retiring after the 2017 World Championship. Though his final season did not end gloriously, we all know that he is a true legend and we witnessed his peak during 2008 - 2013.
Post retirement, Usain Bolt is still leading an adventurous life. He's exploring the unexplored parts of the globe. But sometimes he gets bored, and reads questions asked about him on Quora. One such question he read was, "Who would win a race between Usain Bolt and a tiger if the race is on a straight line track and the tiger is $distancetoBolt$ meters behind Bolt? The finishing point is $finish$ meters away from Bolt's starting position. The tiger starts with an initial speed of $0$ $meter/second$, and will accelerate itself with $tigerAccelaration$ $m/s^2$. Bolt can run with a constant speed of $boltSpeed$ $m/s$ from start to finish. Given these values, find out who will win the race - Bolt or the tiger? "
Note that Bolt will win the race if and only if he touches the finishing line before the tiger touches it. If both of them finish together, the tiger is announced as the winner since Bolt was given an initial advantage. See the figure below for more clarity.

Since Bolt was busy practicing in the tracks during his Physics school classes, he is asking for your help to solve the question. Can you please help him?
He just remembers two formulae from the class, and thinks that they will be useful to you:
$Displacement (S) $ = $ut$ +$ (1/2)at^2$ where $u$ is the initial velocity , #$ $is the acceleration and $t$ is the time taken.
$Velocity$ = $Displacement /Time$

-----Input:-----
- The first line will contain $T$, the number of testcases. Then the description of each test case follow.
- Each test case contains 4 integers $finish, distancetoBolt, tigerAccelaration, boltSpeed$.

-----Output:-----
For each testcase, output in a single line, the word "Bolt" or "Tiger" without quotes, depending on whether Bolt wins or the tiger wins.

-----Constraints-----
- $1 \leq T \leq 100000$
- $1...

from math import sqrt
for _ in range(int(input())) :
 s1, s2, a2, v = map(int, input().split())
 t1 = s1 / v
 t2 = sqrt((2 * (s1 + s2)) / a2)
 if t1 < t2 :
  print("Bolt")
 else :
  print("Tiger")


Solve in Python:
Background
----------
In another dimension, there exist two immortal brothers: Solomon and Goromon. As sworn loyal subjects to the time elemental, Chronixus, both Solomon and Goromon were granted the power to create temporal folds. By sliding through these temporal folds, one can gain entry to parallel dimensions where time moves relatively faster or slower.

Goromon grew dissatisfied and one day betrayed Chronixus by stealing the Temporal Crystal, an artifact used to maintain the time continuum. Chronixus summoned Solomon and gave him the task of tracking down Goromon and retrieving the Temporal Crystal.

Using a map given to Solomon by Chronixus, you must find Goromon's precise location.

Mission Details
---------------
The map is represented as a 2D array. See the example below:

```python
map_example = [[1,3,5],[2,0,10],[-3,1,4],[4,2,4],[1,1,5],[-3,0,12],[2,1,12],[-2,2,6]]
```
Here are what the values of each subarray represent:
- **Time Dilation:** With each additional layer of time dilation entered, time slows by a factor of `2`. At layer `0`, time passes normally. At layer `1`, time passes at half the rate of layer `0`. At layer `2`, time passes at half the rate of layer `1`, and therefore one quarter the rate of layer `0`.
- **Directions** are as follow: `0 = North, 1 = East, 2 = South, 3 = West`
- **Distance Traveled:** This represents the distance traveled relative to the current time dilation layer. See below:

```
The following are equivalent distances (all equal a Standard Distance of 100):
Layer: 0, Distance: 100
Layer: 1, Distance: 50
Layer: 2, Distance: 25
```
For the `mapExample` above:
```
mapExample[0] -> [1,3,5]
1 represents the level shift of time dilation
3 represents the direction
5 represents the distance traveled relative to the current time dilation layer

Solomon's new location becomes [-10,0]

mapExample[1] -> [2,0,10]
At this point, Solomon has shifted 2 layers deeper.
He is now at time dilation layer 3.
Solomon moves North a Standard Distance of 80.
Solomon's new location becomes...

def solomons_quest(arr):
    pos, lvl = [0,0], 0
    for dilat,dir,dist in arr:
        lvl += dilat
        pos[dir in [0,2]] += dist * 2**lvl * (-1)**( dir in [2,3] )
    return pos


Solve in Python:
Background
There is a message that is circulating via public media that claims a reader can easily read a message where the inner letters of each words is scrambled, as long as the first and last letters remain the same and the word contains all the letters.

Another example shows that it is quite difficult to read the text where all the letters are reversed rather than scrambled.

In this kata we will make a generator that generates text in a similar pattern, but instead of scrambled or reversed, ours will be sorted alphabetically

Requirement
return a string where:
1) the first and last characters remain in original place for each word
2) characters between the first and last characters must be sorted alphabetically
3) punctuation should remain at the same place as it started, for example: shan't -> sahn't
Assumptions
1) words are seperated by single spaces
2) only spaces separate words, special characters do not,  for example: tik-tak -> tai-ktk
3) special characters do not take the position of the non special characters, for example: -dcba  ->  -dbca
4) for this kata puctuation is limited to 4 characters: hyphen(-), apostrophe('), comma(,) and period(.)
5) ignore capitalisation

for reference: http://en.wikipedia.org/wiki/Typoglycemia

SPECIAL = "-',."

def scramble_words(words):
    output = []
    for word in words.split():
        sortable = [c for c in word if c.isalpha()]
        typgly = sortable[:1] + sorted(sortable[1:-1]) + sortable[-1:]
        output.append(''.join(c if not c.isalpha() else typgly.pop(0) for c in word))
    return ' '.join(output)


Solve in Python:
Backwards Read Primes are primes that when read backwards in base 10 (from right to left)
are a different prime. (This rules out primes which are palindromes.)
```
Examples:
13 17 31 37 71 73 are Backwards Read Primes
```
13 is such because it's prime and read from right to left writes 31 which is prime too. Same for the others.

## Task
Find all Backwards Read Primes between two positive given numbers (both inclusive), the second one always being greater than or equal to the first one. The resulting array or the resulting string will be ordered following the natural order of the prime numbers.

## Example

backwardsPrime(2, 100) => [13, 17, 31, 37, 71, 73, 79, 97]
backwardsPrime(9900, 10000) => [9923, 9931, 9941, 9967]
backwardsPrime(501, 599) => []

## Note for Forth
Return only the first backwards-read prime between start and end
or 0 if you don't find any

```python
backwards_prime(2, 100) => [13, 17, 31, 37, 71, 73, 79, 97]
backwards_prime(9900, 10000) => [9923, 9931, 9941, 9967]
```

def backwardsPrime(start, stop):
    primes = []
    for n in range(start, stop+1):
        if n not in primes and is_prime(n) and is_prime(reverse(n)) and n != reverse(n):
            primes.append(n)
            if start <= reverse(n) <= stop:
                primes.append(reverse(n))
    return sorted(primes)

def is_prime(n):
    for i in range(2, int(n**(0.5))+1):
        if n % i == 0:
            return False
    return True

def reverse(n):
    return int(''.join(str(n)[::-1]))


Solve in Python:
Balanced strings are those who have equal quantity of 'L' and 'R' characters.
Given a balanced string s split it in the maximum amount of balanced strings.
Return the maximum amount of splitted balanced strings.

Example 1:
Input: s = "RLRRLLRLRL"
Output: 4
Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'.

Example 2:
Input: s = "RLLLLRRRLR"
Output: 3
Explanation: s can be split into "RL", "LLLRRR", "LR", each substring contains same number of 'L' and 'R'.

Example 3:
Input: s = "LLLLRRRR"
Output: 1
Explanation: s can be split into "LLLLRRRR".

Example 4:
Input: s = "RLRRRLLRLL"
Output: 2
Explanation: s can be split into "RL", "RRRLLRLL", since each substring contains an equal number of 'L' and 'R'

Constraints:

1 <= s.length <= 1000
s[i] = 'L' or 'R'

class Solution:
    def balancedStringSplit(self, s: str) -> int:
        lCount = rCount = 0
        retVal = 0

        for char in s:
            if char == 'R':
                rCount += 1
            else:
                lCount += 1

            if rCount == lCount:
                retVal += 1
                lCount = rCount = 0
        return retVal


Solve in Python:
Bandwidth of a matrix A is defined as the smallest non-negative integer K such that A(i, j) = 0 for |i - j| > K.
For example, a matrix with all zeros will have its bandwith equal to zero. Similarly bandwith of diagonal matrix will also be zero.

For example, for the below given matrix, the bandwith of this matrix is 2.

1 0 0
0 1 1
1 1 0

Bandwidth of the below matrix is 1.

Bandwidth of the below matrix is 2.

Bandwidth of the below matrix is also 2.

You will be a given a binary matrix A of dimensions N × N. You are allowed to make following operation as many times as you wish (possibly zero or more). In a single operation, you can swap any two entries of the matrix. Your aim is to minimize the bandwidth of the matrix. Find the minimum bandwidth of the matrix A you can get after making as many operations of above type as you want.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follow.
First line of each test case contains an integer N denoting the height/width of the matrix.
Next N lines of each test case contain N space separated binary integers (either zero or one) corresponding to the entries of the matrix.

-----Output-----
For each test case, output a single integer corresponding to the minimum bandwidth that you can obtain.

-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 500
- 0 ≤ A(i, j) ≤ 1

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

-----Example-----
Input:
6
2
0 0
0 0
2
1 0
0 1
2
1 0
1 0
2
1 0
1 1
3
1 0 0
0 1 1
1 1 0
4
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1

Output:
0
0
0
1
1
3

-----Explanation-----
Example case 1. The bandwidth of a matrix will all zero entries will be zero. This is the minimum bandwidth you can get, so there is no need of performing any swap operation.
Example case 2. The bandwidth of a diagonal matrix will also be zero.
Example case 3. You can make the given matrix a diagonal matrix by swapping A(2, 1) and A(2, 2), which will have...

for _ in range(int(input())):
    n = int(input())
    d = {}
    i = 0
    while (i < n):
        j = 0
        o = []
        o = list(map(int, input().split()))
        while (j < len(o)):
            x = o[j]
            d[(i, j)] = x
            j = j + 1

        i = i + 1

    do = {}
    dz = {}

    i = 0
    while(i < n):
        j = 0
        while(j < n):
            e = d[(i,j)]
            ri = i + 1
            rj = j + 1
            y = abs(ri - rj)
            if e == 1:
                if y in do:
                    do[y] = do[y]+1

                else:
                    do[y] = 1

            else:
                if y in dz:
                    dz[y] = dz[y] + 1

                else:
                    dz[y] = 1

            j = j+1

        i = i+1

    lo = sorted(do.keys())
    lz = sorted(dz.keys())
    lo = lo[::-1]
    #print(lo)
    #print(lz)
    #print(do)
    #print(dz)

    i = 0
    j = 0
    if i == len(lo):
        print(0)
        continue

    if j == len(lz):
        print(lo[i])
        continue

    while((lo[i] != lz[j]) and (lo[i] > lz[j])):
        ov = lo[i]
        zv = lz[j]
        #print(ov,zv,3)
        do[ov] = do[ov]-1
        dz[zv] = dz[zv]-1

        if do[ov] == 0:
            i = i+1
            if i == len(lo):
                break

        if dz[zv] == 0:
            j = j+1
            if j == len(lz):
                break

    if i != len(lo):
        print(lo[i])

    else:
        print(lz[j])


Solve in Python:
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. [Image]

Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:

1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars.

2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.

Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).

-----Input-----

The first line of input contains a single integer q (1 ≤ q ≤ 1 000).

The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u.

1 ≤ v, u ≤ 10^18, v ≠ u, 1 ≤ w ≤ 10^9 states for every description line.

-----Output-----

For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.

-----Example-----
Input
7
1 3 4 30
1 4 1 2
1 3 6 8
2 4 3
1 6 1 40
2 3 7
2 2 4

Output
94
0
32

-----Note-----

In the example testcase:

Here...

w = {}
def up(a, b, d):
    while a != b:
        if a < b:
            a, b = b, a
        if a not in w:
            w[a] = 0
        w[a] += d
        a = a // 2

def get(a, b):
    res = 0
    while a != b:
        if a < b:
            a, b = b, a
        if a in w:
            res += w[a]
        a = a // 2
    return res

q = int(input())
for i in range(q):
    a = [int(b) for b in input().split()]
    if a[0] == 1:
        up(a[1], a[2], a[3])
    else:
        print(get(a[1], a[2]))


Solve in Python:
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.

 [Image]

Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:

let starting_time be an array of length n

current_time = 0

dfs(v):

        current_time = current_time + 1

        starting_time[v] = current_time

        shuffle children[v] randomly (each permutation with equal possibility)

        // children[v] is vector of children cities of city v

        for u in children[v]:

                dfs(u)

As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).

Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.

-----Input-----

The first line of input contains a single integer n (1 ≤ n ≤ 10^5) — the number of cities in USC.

The second line contains n - 1 integers p_2, p_3, ..., p_{n} (1 ≤ p_{i} < i), where p_{i} is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered p_{i} and i in USC.

-----Output-----

In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].

Your answer for each city will be considered correct if its absolute or relative error does not exceed 10^{ - 6}.

-----Examples-----
Input
7
1 2 1 1 4 4

Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0

Input
12
1 1 2 2 4 4 3 3 1 10 8

Output
1.0 5.0 5.5...

n = int(input())
pos, tree, ans, sz = list(map(int,input().split())) if n > 1 else [],[],[],[]
for i in range(n):
  tree.append([])
  ans.append(0.0)
  sz.append(0)

for i in range(n - 1):
  tree[pos[i] - 1].append(i + 1)

for i in range(n)[::-1]:
  sz[i] = 1
  for to in tree[i]:
    sz[i] += sz[to]

for i in range(n):
  for to in tree[i]:
    ans[to] = ans[i] + 1 + (sz[i] - 1 - sz[to]) * 0.5

st = lambda i: str(i + 1)
print(' '.join(list(map(st, ans))))


Solve in Python:
Base on the fairy tale [Diamonds and Toads](https://en.wikipedia.org/wiki/Diamonds_and_Toads) from Charles Perrault. In this kata you will have to complete a function that take 2 arguments:

- A string, that correspond to what the daugther says.
- A string, that tell you wich fairy the girl have met, this one can be `good` or `evil`.

The function should return the following count as a hash:

- If the girl have met the `good` fairy:
  - count 1 `ruby` everytime you see a `r` and 2 everytime you see a `R`
  - count 1 `crystal` everytime you see a `c` and 2 everytime you see a `C`
- If the girl have met the `evil` fairy:
  - count 1 `python` everytime you see a `p` and 2 everytime uou see a `P`
  - count 1 `squirrel` everytime you see a `s` and 2 everytime you see a `S`

**Note**: For this kata I decided to remplace the normal `Diamonds` and `Toads` by some programming languages. And just discover that [Squirrel](https://en.wikipedia.org/wiki/Squirrel_(programming_language) is a programming language.


Solve in Python:
Based on [this kata, Connect Four.](https://www.codewars.com/kata/connect-four-1)

In this kata we play a modified game of connect four. It's connect X, and there can be multiple players.

Write the function ```whoIsWinner(moves,connect,size)```.

```2 <= connect <= 10```

```2 <= size <= 52```

Each column is identified by a character, A-Z a-z:
``` ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ```

Moves come in the form:

```
['C_R','p_Y','s_S','I_R','Z_Y','d_S']
```
* Player R puts on C
* Player Y puts on p
* Player S puts on s
* Player R puts on I
* ...

The moves are in the order that they are played.

The first player who connect ``` connect ``` items in same color is the winner.

Note that a player can win before all moves are done. You should return the first winner.

If no winner is found, return "Draw".

A board with size 7, where yellow has connected 4:

All inputs are valid, no illegal moves are made.

![alt text](https://i.imgur.com/xnJEsIx.png)

from itertools import compress
from string import ascii_uppercase, ascii_lowercase
D = {c:i for i,c in enumerate(ascii_uppercase + ascii_lowercase)}

def whoIsWinner(moves, con, sz):
    def gen(i, j):
        for x in range(1, con):
            yield ((i, j-x), (i-x, j), (i+x, j), (i-x, j-x), (i+x, j+x), (i+x, j-x), (i-x, j+x))

    def check(i, j, p):
        memo, count = [True]*7, [0]*7
        for L in gen(i, j):
            for x,(k,l) in enumerate(L):
                memo[x] = memo[x] and 0 <= k < sz and 0 <= l < sz and grid[k][l] == p
                count[x] += memo[x]
            if not any(memo):
                return max(count[0], count[1]+count[2], count[3]+count[4], count[5]+count[6])+1 >= con
        else: return True

    if sz >= con <= len(moves):
        grid = [['0']*sz for _ in range(sz)]
        for move in moves:
            i, p = D[move[0]], move[-1]
            j = next(j for j,x in enumerate(grid[i]) if x == '0')
            if check(i, j, p): return p
            grid[i][j] = p
    return "Draw"


Solve in Python:
Based on the well known ['Eight Queens' problem](https://en.wikipedia.org/wiki/Eight_queens_puzzle).

#### Summary
Your challenge is to place N queens on a chess board such that none of the queens are attacking each other.

#### Details
A standard 8x8 chess board has its rows (aka ranks) labelled 1-8 from bottom to top, and its columns (aka files) labelled a-h from left to right. Any square can be denoted by a combination of letter and number. For example, the top left square is a8. A queen may attack any square on its rank or file. It may also attack any square diagonally.

In this kata, chessboard may have any size from 1 to 10. Columns are marked with letters a-j, and rows with single digit from 1 to 0 (first row is marked with 1, ninth row is marked with 9, and tenth row is marked with 0, so `a1` denotes bottom left field of the chessboard, and `j0` - top right field on a 10x10 board).

You will be given the position of one queen on the board (e.g. `'c3'`). Your challenge is to compute the position of the remaining queens and return the full solution (including the original input) as a comma-separated string (e.g. `'d8,a7,e6,h5,b4,g3,c2,f1'`). Fields do not have to be sorted in any particular way, but you have to adhere to above format (lowercase letters, no spaces, fields separated with commas).

Note that there may be multiple valid solutions for a given starting position. Your function only needs to produce (any) one of these. All given starting positions produce valid solutions.

If you wish to write more tests, the validity of a solution may be checked using preloaded function (see sample tests).

Hint: check the wiki article for the various algorithms that are applicable to this problem.

----
Next steps:
 - [N queens problem (with no mandatory queen position)](https://www.codewars.com/kata/52cdc1b015db27c484000031)
 - [N queens problem (with one mandatory queen position) - challenge version](https://www.codewars.com/kata/5985ea20695be6079e000003)

MOVES = ( (1,1), (-1,1), (1,-1), (-1,-1) )

def find_empty(row, X):
    for y,spot in enumerate(row):
        if spot == 0:
            yield (X,y)

def populating_board(x,y, board):
    board[x][y] += 1

    pos = [(x,y)]
    for i in range(len(board)):
        if (x,y) != (i,y):
            board[i][y] += 1
            pos.append((i,y))

        if (x,y) != (x,i):
            board[x][i] +=1
            pos.append((x,i))

    for dx,dy in MOVES:
        c = 0
        while True:
            c += 1
            xx = x+c*dx
            yy = y+c*dy

            if not (0<=xx<len(board) and 0<=yy<len(board)):
                break

            if (xx,yy) != (x,y):
                board[xx][yy] += 1
                pos.append((xx,yy))

    return pos

def queens(position, size):
    board = [[0]*size for i in range(size)]
    y,x = ord(position[0])-97, size - (size==10 and not int(position[1]) and 10 or int(position[1]))
    initial_X = x

    #populating board with not possible Q positions
    populating_board(x,y,board)
    queens = [position]

    def dfs(counter, next_X):
        nonlocal board
        if counter == size:
            return True

        while next_X > 0 and 0 not in board[next_X]:
            next_X -= 1

        while next_X < size-1 and 0 not in board[next_X]:
            next_X += 1

        for x,y in find_empty(board[next_X], next_X):
            queens.append(chr(y+97)+str(size -(size==10 and not x and 10 or x)))
            to_restore = populating_board(x,y,board)

            if dfs(counter+1, x):
                return True

            queens.pop()
            for pos_x, pos_y in to_restore:
                board[pos_x][pos_y] -= 1

    if dfs(1, x):
        return ','.join(queens)


Solve in Python:
Basic regex tasks. Write a function that takes in a numeric code of any length. The function should check if the code begins with 1, 2, or 3 and return `true` if so. Return `false` otherwise.

You can assume the input will always be a number.

import re
def validate_code(code):
  return bool(re.match("[123]{1}.*",str(code)))


Solve in Python:
Batman is about to face Superman so he decides to prepare for the battle by upgrading his Batmobile. He manufactures multiple duplicates of his standard Batmobile each tweaked in a different way such that the maximum speed of each is never less than that of the standard model.
After carrying out this process, he wishes to know how many of his prototypes are faster than his standard Batmobile?

-----Input-----
- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follow:
- The first line of each test case contains a single integer N denoting the number of copies of the standard Batmobile.
- The second line contains a sequence of N+1 space-separated integers, S0 to SN, sorted in non-decreasing order separated by space. S0 is the maximum speed of the standard Batmobile. S1 to SN denote the maximum speeds of the prototypes.

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

-----Constraints-----
- 1 ≤ T ≤ 1000
- 1 ≤ N ≤ 1000
- 1 ≤ Si ≤ 109

-----Example-----
Input:
2
4
1 2 3 4 5
5
1 10 100 1000 10000 100000

Output:
4
5

for i in range(0,int(input())):
 n,m=int(input()),list(map(int,input().split()))
 print(sum([1 for i in m if i > m[0]]))


Solve in Python:
Be u(n) a sequence beginning with:
```
u[1]  = 1,  u[2]  = 1,  u[3]  = 2,  u[4]  = 3,  u[5]  = 3,  u[6] = 4,

u[7]  = 5,  u[8]  = 5,  u[9]  = 6,  u[10] = 6,  u[11] = 6,  u[12] = 8,

u[13] = 8,  u[14] = 8,  u[15] = 10, u[16] = 9,  u[17] = 10, u[18] = 11,

u[19] = 11, u[20] = 12, u[21] = 12, u[22] = 12, u[23] = 12 etc...

```
- How is`u[8]` calculated?

We have `u[7] = 5` and `u[6] = 4`. These numbers tell us that we have to go backwards from index `8` to index `8 - 5 = 3` and to index `8 - 4 = 4` so to index `3` and `4`.

``` u[3] = 2``` and ```u[4] = 3```  hence ```u[8] = u[3] + u[4] = 2 + 3 = 5```.

- Another example: let us calculate `u[13]`. At indexes `12` and `11` we have `8` and `6`. Going backwards of `8` and `6` from `13` we get indexes `13 - 8 = 5` and `13 - 6 = 7`.

``` u[5] = 3```  and ``` u[7] = 5```  so ``` u[13] = u[5] + u[7] = 3 + 5 = 8``` .

## Task
- 0) Express u(n) as a function of n, u[n - 1], u[n - 2]. (not tested).

- 1) Given two numbers `n, k (integers > 2)` write the function `length_sup_u_k(n, k) or lengthSupUK or length-sup-u-k` returning the number of terms `u[i] >= k` with `1 <= i <= n`.
If we look above we can see that between `u[1]` and `u[23]` we have four `u[i]` greater or equal to `12`: `length_sup_u_k(23, 12) => 4`

- 2) Given `n (integer > 2)` write the function `comp(n)` returning the number of times where a term of `u` is less than its **predecessor** up to and including u[n].

## Examples:

```
u(900) => 455 (not tested)
u(90000) => 44337 (not tested)

length_sup_u_k(23, 12) => 4
length_sup_u_k(50, 10) => 35
length_sup_u_k(500, 100) => 304

comp(23) => 1 (since only u(16) < u(15))
comp(100) => 22
comp(200) => 63
```

## Note: Shell
Shell tests only `lengthSupUk`

S,C = [1,1],[0,0]

def length_sup_u_k(n, k):  return update(n) or sum(v>=k for v in S[:n])
def comp(n):               return update(n) or C[n-1]

def update(n):
    for _ in range(n+1-len(S)):
        S.append( S[-S[-2]] + S[-S[-1]] )
        C.append( C[-1] + (S[-2]>S[-1]) )


Solve in Python:
Beaches are filled with sand, water, fish, and sun. Given a string, calculate how many times the words `"Sand"`, `"Water"`, `"Fish"`, and `"Sun"` appear without overlapping (regardless of the case).

## Examples

```python
sum_of_a_beach("WAtErSlIde")                    ==>  1
sum_of_a_beach("GolDeNSanDyWateRyBeaChSuNN")    ==>  3
sum_of_a_beach("gOfIshsunesunFiSh")             ==>  4
sum_of_a_beach("cItYTowNcARShoW")               ==>  0
```


Solve in Python:
Bear Limak has a sequence of N non-negative integers A1, A2, ..., AN. He defines the score of a segment (consecutive subsequence) as its sum of elements modulo P (not necessarily prime). Find the maximum score of a non-empty segment, and also find the number of segments with this maximum score.

-----Input-----
First line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
For each test case, the first line of the input contains two space separated integers, N and P.
The second line contains N space separated integers denoting the sequence.

-----Output-----
For each test case, output two space separated integers denoting the maximum score of a segment and the number of segments with the score, respectively.

-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 105
- 1 ≤ P ≤ 109
- 0 ≤ Ai ≤ 109

Subtask #1: (25 points)
- 1 ≤ N ≤ 100

Subtask #2: (25 points)
- 1 ≤ N ≤ 1000

Subtask #3: (50 points)
- original constraints

-----Example-----
Input:
4
2 3
1 2
3 5
2 4 3
3 100
1 3 5
4 3
1 2 3 4

Output:
2 1
4 2
9 1
2 2

-----Explanation-----
Example case 1. There are three segments - [1], [2] and [1, 2]. Sum of these segments are 1, 2 and 3 respectively. Sum of these segments modulo 3 will be 1, 2 and 0. Maximum score among these is 2. There is also only one segment with this score.
Example case 2. There are six segments - [2], [4], [3], [2, 4], [4, 3] and [2, 4, 3]. Sum of these segments are 2, 4, 3, 6, 7, 9 respectively. Sum of these segments modulo 5 will be 2, 4, 3, 1, 2, 4. Maximum score among these is 4. And there are two segments with this score.

for _ in range(int(input())):
 n,m=input().split()
 n,m=int(n),int(m)
 x=y=c=0
 l=list(map(int,input().split()))
 for i in range(n):
  for j in range(i,n):
   x=x+l[j]
   if (x%m)>y:
    y=x%m
    c=1
   elif y==(x%m):
    c+=1
  x = 0
 print(y,c)


Solve in Python:
Bears love candies and games involving eating them. Limak and Bob play the following game. Limak eats 1 candy, then Bob eats 2 candies, then Limak eats 3 candies, then Bob eats 4 candies, and so on. Once someone can't eat what he is supposed to eat, he loses.
Limak can eat at most A candies in total (otherwise he would become sick), while Bob can eat at most B candies in total.
Who will win the game?
Print "Limak" or "Bob" accordingly.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The only line of each test case contains two integers A and B denoting the maximum possible number of candies Limak can eat and the maximum possible number of candies Bob can eat respectively.

-----Output-----
For each test case, output a single line containing one string — the name of the winner ("Limak" or "Bob" without the quotes).

-----Constraints-----
- 1 ≤ T ≤ 1000
- 1 ≤ A, B ≤ 1000

-----Example-----
Input:
10
3 2
4 2
1 1
1 2
1 3
9 3
9 11
9 12
9 1000
8 11

Output:
Bob
Limak
Limak
Bob
Bob
Limak
Limak
Bob
Bob
Bob

-----Explanation-----
Test case 1. We have A = 3 and B = 2. Limak eats 1 candy first, and then Bob eats 2 candies. Then Limak is supposed to eat 3 candies but that would mean 1 + 3 = 4 candies in total. It's impossible because he can eat at most A candies, so he loses. Bob wins, and so we print "Bob".
Test case 2. Now we have A = 4 and B = 2. Limak eats 1 candy first, and then Bob eats 2 candies, then Limak eats 3 candies (he has 1 + 3 = 4 candies in total, which is allowed because it doesn't exceed A). Now Bob should eat 4 candies but he can't eat even a single one (he already ate 2 candies). Bob loses and Limak is the winner.
Test case 8. We have A = 9 and B = 12. The game looks as follows:
- Limak eats 1 candy.
- Bob eats 2 candies.
- Limak eats 3 candies (4 in total).
- Bob eats 4 candies (6 in total).
- Limak eats 5 candies (9 in total).
- Bob eats 6 candies (12 in total).
- Limak is supposed to eat 7 candies but he...

for t in range(int(input())):
 a,b=map(int, input().split())
 for i in range(1,501,2):
  a-=i
  if a<0:
   print("Bob")
   break
  b-=(i+1)
  if b<0:
   print("Limak")
   break


Solve in Python:
Because my other two parts of the serie were pretty well received I decided to do another part.

Puzzle Tiles

You will get two Integer n (width) and m (height) and your task is to draw following pattern. Each line is seperated with '\n'.

Both integers are equal or greater than 1. No need to check for invalid parameters.
There are no whitespaces at the end of each line.

e.g.:

                                       \_( )\_\_ \_( )\_\_ \_( )\_\_ \_( )\_\_
                                     \_|     \_|     \_|     \_|     \_|
                                    (\_   \_ (\_   \_ (\_   \_ (\_   \_ (\_
                                     |\_\_( )\_|\_\_( )\_|\_\_( )\_|\_\_( )\_|
                                     |\_     |\_     |\_     |\_     |\_
             puzzleTiles(4,3)=>       \_) \_   \_) \_   \_) \_   \_) \_   \_)
                                     |\_\_( )\_|\_\_( )\_|\_\_( )\_|\_\_( )\_|
                                     \_|     \_|     \_|     \_|     \_|
                                    (\_   \_ (\_   \_ (\_   \_ (\_   \_ (\_
                                     |\_\_( )\_|\_\_( )\_|\_\_( )\_|\_\_( )\_|

For more informations take a look in the test cases!

 Serie: ASCII Fun

ASCII Fun #1: X-Shape
ASCII Fun #2: Funny Dots
ASCII Fun #3: Puzzle Tiles
ASCII Fun #4: Build a pyramid


Solve in Python:
Being a crewmate in the Among Us game, you will have to solve a task to win against the imposter.
The task : You are given a certain number of bulbs(Say n) which are initially in OFF position.
The bulbs are numbered from 1 to n. There will be n current fluctuations in such a way that in the 1st fluctuation all bulbs are toggled, in the 2nd fluctuation every 2nd bulb is toggled, in the 3rd fluctuation every 3rd bulb is toggled and so on.
Your job as a crewmate is to find the number of bulbs which are ON at the end of n fluctuations. But, the imposter has a special power which alerts it when a bulb with a number divisible by 3 is kept ON at the end of n fluctuations.
So, you will have to switch off the bulbs with numbers divisible by 3 and give the final result to complete the task and win the game.

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

-----Output:-----
- For each testcase, output a single integer - the number of bulbs that will remain ON after $n$ fluctuations.

-----Constraints :-----
- $1 \leq T \leq 1000$
- $2 \leq n \leq 10^9$

-----Sample Input:-----
2
2
20

-----Sample Output:-----
1

3

import sys
# import math
from math import gcd
# import re
# from heapq import *
# from collections import defaultdict as dd
# from collections import OrderedDict as odict
# from collections import Counter as cc
# from collections import deque
# sys.setrecursionlimit(10**5)#thsis is must
# mod = 10**9+7; md = 998244353
# m = 2**32
input = lambda: sys.stdin.readline().strip()
inp = lambda: list(map(int,sys.stdin.readline().strip().split()))
# def C(n,r,mod):
#   if r>n:
#       return 0
#   num = den = 1
#   for i in range(r):
#       num = (num*(n-i))%mod
#       den = (den*(i+1))%mod
#   return (num*pow(den,mod-2,mod))%mod
# M = 1000000+1
# pfc = [i for i in range(M+1)]
# def pfcs(M):
#     for i in range(2,M+1):
#         if pfc[i]==i:
#             for j in range(i+i,M+1,i):
#                 if pfc[j]==j:
#                     pfc[j] = i
#     return
#______________________________________________________
for _ in range(int(input())):
    n = int(input())
    ans = 0
    for i in range(1,n+1):
        d = i*i
        if d>n:
            break
        if d%3!=0:
            ans+=1
    print(ans)


Solve in Python:
Being tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.

He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position $x$, and the shorter rabbit is currently on position $y$ ($x \lt y$). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by $a$, and the shorter rabbit hops to the negative direction by $b$.

 [Image]

For example, let's say $x=0$, $y=10$, $a=2$, and $b=3$. At the $1$-st second, each rabbit will be at position $2$ and $7$. At the $2$-nd second, both rabbits will be at position $4$.

Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.

-----Input-----

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

Each test case contains exactly one line. The line consists of four integers $x$, $y$, $a$, $b$ ($0 \le x \lt y \le 10^9$, $1 \le a,b \le 10^9$) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.

-----Output-----

For each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.

If the two rabbits will never be at the same position simultaneously, print $-1$.

-----Example-----
Input
5
0 10 2 3
0 10 3 3
900000000 1000000000 1 9999999
1 2 1 1
1 3 1 1

Output
2
-1
10
-1
1

-----Note-----

The first case is explained in the description.

In the second case, each rabbit will be at position $3$ and $7$ respectively at the...

for __ in range(int(input())):
    x, y, a, b = map(int, input().split())
    z = y - x
    c = a + b
    print(-1 if z % c else z // c)


Solve in Python:
Below is a right-angled triangle:

```
  |\
  | \
  |  \
  |   \
o |    \ h
  |     \
  |    θ \
  |_______\
     a
```

Your challange is to write a function (```missingAngle``` in C/C#, ```missing_angle``` in Ruby), that calculates the angle θ in degrees to the nearest integer. You will be given three arguments representing each side: o, h and a. One of the arguments equals zero. Use the length of the two other sides to calculate θ. You will not be expected to handle any erronous data in your solution.

from math import sqrt, asin, degrees

def missing_angle(h, a, o):
  h, o = h or sqrt(a**2 + o**2), o or sqrt(h**2 - a**2)
  return round(degrees(asin(o/h)))


Solve in Python:
Berland year consists of $m$ months with $d$ days each. Months are numbered from $1$ to $m$. Berland week consists of $w$ days. The first day of the year is also the first day of the week. Note that the last week of the year might be shorter than $w$ days.

A pair $(x, y)$ such that $x < y$ is ambiguous if day $x$ of month $y$ is the same day of the week as day $y$ of month $x$.

Count the number of ambiguous pairs.

-----Input-----

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

Each of the next $t$ lines contains three integers $m$, $d$ and $w$ ($1 \le m, d, w \le 10^9$) — the number of months in a year, the number of days in a month and the number of days in a week.

-----Output-----

Print $t$ integers — for each testcase output the number of pairs $(x, y)$ such that $x < y$ and day $x$ of month $y$ is the same day of the week as day $y$ of month $x$.

-----Example-----
Input
5
6 7 4
10 7 12
12 30 7
1 1 1
3247834 10298779 625324

Output
6
9
5
0
116461800

-----Note-----

Here are the pairs for the first test case:  $$

from math import gcd

for _ in range(int(input())):
    m, d, w = list(map(int, input().split()))
    if d == 1:
        print(0)
    else:
        w1 = w // gcd(w, d - 1)
        md = min(m, d)
        # sum(max(md - w1 * n, 0) for n in 1..inf)
        # sum(md - w1 * n for n in 1..md // w1)
        mdd_w1 = md // w1
        print((md * 2 - w1 - mdd_w1 * w1) * mdd_w1 // 2)


Solve in Python:
Bertown is a city with $n$ buildings in a straight line.

The city's security service discovered that some buildings were mined. A map was compiled, which is a string of length $n$, where the $i$-th character is "1" if there is a mine under the building number $i$ and "0" otherwise.

Bertown's best sapper knows how to activate mines so that the buildings above them are not damaged. When a mine under the building numbered $x$ is activated, it explodes and activates two adjacent mines under the buildings numbered $x-1$ and $x+1$ (if there were no mines under the building, then nothing happens). Thus, it is enough to activate any one mine on a continuous segment of mines to activate all the mines of this segment. For manual activation of one mine, the sapper takes $a$ coins. He can repeat this operation as many times as you want.

Also, a sapper can place a mine under a building if it wasn't there. For such an operation, he takes $b$ coins. He can also repeat this operation as many times as you want.

The sapper can carry out operations in any order.

You want to blow up all the mines in the city to make it safe. Find the minimum number of coins that the sapper will have to pay so that after his actions there are no mines left in the city.

-----Input-----

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

Each test case begins with a line containing two integers $a$ and $b$ ($1 \le a, b \le 1000$) — the cost of activating and placing one mine, respectively.

The next line contains a map of mines in the city — a string consisting of zeros and ones.

The sum of the string lengths for all test cases does not exceed $10^5$.

-----Output-----

For each test case, output one integer — the minimum number of coins that the sapper will have to pay.

-----Example-----
Input
2
1 1
01000010
5 1
01101110

Output
2
6

-----Note-----

In the second test case, if we place a mine under the fourth building and then activate it, then all mines on...

for _ in range (int(input())):
    a,b=map(int,input().split())
    s=input()
    n=len(s)
    j=0
    while j<n and s[j]=='0':
        j+=1
    c=0
    r=a
    if j==n:
        r=0
    damp=0
    for i in range(j,n):
        if s[i]=='1':
            if damp>0:
                r+=min(a,damp*b)
            damp=0
        else:
            damp+=1
        #print(damp,r)
    print(r)


Solve in Python:
Bessie and the cows are playing with sequences and need your help. They start with a sequence, initially containing just the number 0, and perform n operations. Each operation is one of the following:  Add the integer x_{i} to the first a_{i} elements of the sequence.  Append an integer k_{i} to the end of the sequence. (And hence the size of the sequence increases by 1)  Remove the last element of the sequence. So, the size of the sequence decreases by one. Note, that this operation can only be done if there are at least two elements in the sequence.

After each operation, the cows would like to know the average of all the numbers in the sequence. Help them!

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 2·10^5) — the number of operations. The next n lines describe the operations. Each line will start with an integer t_{i} (1 ≤ t_{i} ≤ 3), denoting the type of the operation (see above). If t_{i} = 1, it will be followed by two integers a_{i}, x_{i} (|x_{i}| ≤ 10^3; 1 ≤ a_{i}). If t_{i} = 2, it will be followed by a single integer k_{i} (|k_{i}| ≤ 10^3). If t_{i} = 3, it will not be followed by anything.

It is guaranteed that all operations are correct (don't touch nonexistent elements) and that there will always be at least one element in the sequence.

-----Output-----

Output n lines each containing the average of the numbers in the sequence after the corresponding operation.

The answer will be considered correct if its absolute or relative error doesn't exceed 10^{ - 6}.

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

Output
0.500000
0.000000
1.500000
1.333333
1.500000

Input
6
2 1
1 2 20
2 2
1 2 -3
3
3

Output
0.500000
20.500000
14.333333
12.333333
17.500000
17.000000

-----Note-----

In the second sample, the sequence becomes $\{0 \} \rightarrow \{0,1 \} \rightarrow \{20,21 \} \rightarrow \{20,21,2 \} \rightarrow \{17,18,2 \} \rightarrow \{17,18 \} \rightarrow \{17 \}$

def main():
    l, base, res, le, tot = [0] * 200001, [0] * 200001, [], 1, 0
    for _ in range(int(input())):
        s = input()
        c = s[0]
        if c == '1':
            a, x = list(map(int, s[2:].split()))
            base[a] += x
            tot += a * x
        elif c == '2':
            l[le] = x = int(s[2:])
            tot += x
            le += 1
        else:
            x = base[le]
            base[le] = 0
            tot -= x
            le -= 1
            base[le] += x
            tot -= l[le]
        res.append(tot / le)
    print('\n'.join(map(str, res)))

def __starting_point():
    main()

__starting_point()


Solve in Python:
Bessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play!

More specifically, he wants to get from $(0,0)$ to $(x,0)$ by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its $n$ favorite numbers: $a_1, a_2, \ldots, a_n$. What is the minimum number of hops Rabbit needs to get from $(0,0)$ to $(x,0)$? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.

Recall that the Euclidean distance between points $(x_i, y_i)$ and $(x_j, y_j)$ is $\sqrt{(x_i-x_j)^2+(y_i-y_j)^2}$.

For example, if Rabbit has favorite numbers $1$ and $3$ he could hop from $(0,0)$ to $(4,0)$ in two hops as shown below. Note that there also exists other valid ways to hop to $(4,0)$ in $2$ hops (e.g. $(0,0)$ $\rightarrow$ $(2,-\sqrt{5})$ $\rightarrow$ $(4,0)$).

 $1$ Here is a graphic for the first example. Both hops have distance $3$, one of Rabbit's favorite numbers.

In other words, each time Rabbit chooses some number $a_i$ and hops with distance equal to $a_i$ in any direction he wants. The same number can be used multiple times.

-----Input-----

The input consists of multiple test cases. The first line contains an integer $t$ ($1 \le t \le 1000$)  — the number of test cases. Next $2t$ lines contain test cases — two lines per test case.

The first line of each test case contains two integers $n$ and $x$ ($1 \le n \le 10^5$, $1 \le x \le 10^9$)  — the number of favorite numbers and the distance Rabbit wants to travel, respectively.

The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^9$)  — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.

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

-----Output-----

For each test case, print a single integer — the minimum...

a = int(input())
for i in range(a):
    n, d = map(int, input().split())
    m = list(map(int, input().split()))
    ui = 1e10
    for l in m:
        ans = 0
        if d % l != 0:
            ans += 1
        ans += d//l
        if d//l == 0 and d %l != 0:
            ans += 1
        ui = min(ui, ans)
    print(int(ui))


Solve in Python:
Bhallaladeva was an evil king who ruled the kingdom of Maahishmati. He wanted to erect a 100ft golden statue of himself and he looted gold from several places for this. He even looted his own people, by using the following unfair strategy:
There are N houses in Maahishmati, and the ith house has Ai gold plates. Each gold plate costs exactly 1 Nimbda, which is the unit of currency in the kingdom of Maahishmati. Bhallaladeva would choose an integer K, and loots all the houses in several steps. In each step:

- He would choose a house i which hasn't been looted yet, pay the owner exactly Ai Nimbdas, and take away all the gold plates in that house (Hence, he also ends up looting this house).
- He would now choose atmost K houses which haven't been looted yet and take away all the gold plates from these houses without paying a single Nimbda (Yes, he takes all of them for free).

He repeats the above steps until all the N houses have been looted. Your task is to devise a strategy for Bhallaladeva to loot the houses in some order, so that the number of nimbdas he has to pay is minimium. You'll also be given multiple values of K (Q of them to be precise), and you need to find the minimum number of nimbdas for each of these values.

-----Input-----
The first line of input consists of a single integer N denoting the number of houses in Maahishmati. The second line of input consists of N space separated integers denoting A1, A2, ..., AN, where Ai denotes the number of gold plates in the ith house. The third line of input consists of a single integer Q denoting the number of values of K to follow. Each of the following Q lines consist of a single integer, where the value on the ith line denotes the value of K for the ith query.

-----Output-----
Output exactly Q integers on separate lines, where the output on the ith line denotes the answer for the ith value of K.

-----Constraints-----
- 1 ≤ N ≤ 105
- 1 ≤ Q ≤ 105
- 0 ≤ K ≤ N-1
- 1 ≤ Ai ≤ 104

-----Example-----
Input:
4
3 2 1...

import math
n = int(input())
a = sorted(map(int,input().split()))
l = [0]*n
for i in range(n):
 l[i] = a[i] + l[i-1]
for q in range(int(input())):
 print(l[int(math.ceil(float(n)/(int(input())+1)))-1])


Solve in Python:
Bharat was given a problem to solve, by his brother, Lord Ram. The problem was like, given integers, $N$ and $K$, Bharat has to find the number (possibilities) of non-increasing arrays of length $K$, where each element of the array is between $1$ and $N$ (both inclusive). He was confused, regarding this problem. So, help him solve the problem, so that, he can give the answer of the problem, to his brother, Lord Rama. Since, the number of possible sub-arrays can be large, Bharat has to answer the problem as "number of possible non-increasing arrays", modulo  $10^9$ $+$ $7$.

-----Input:-----
- Two space-seperated integers, $N$ and $K$.

-----Output:-----
- Output in a single line, the number of possible non-increasing arrays, modulo $10^9$ $+$ $7$.

-----Constraints:-----
- $1 \leq N, K \leq 2000$

-----Sample Input:-----
2 5

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

-----Explanation:-----
- Possible Arrays, for the "Sample Case" are as follows:
- {1, 1, 1, 1, 1}
- {2, 1, 1, 1, 1}
- {2, 2, 1, 1, 1}
- {2, 2, 2, 1, 1}
- {2, 2, 2, 2, 1}
- {2, 2, 2, 2, 2}
- Hence, the answer to the "Sample Case" is $6$ ($6$ % ($10^9$ $+$ $7$)).

import math
k,n=map(int,input().split())
x=10**9+7
print((math.factorial(n+k-1)//(math.factorial(k-1)*math.factorial(n)))%x)


Solve in Python:
Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x_1, x_2, ..., x_{k} (k > 1) is such maximum element x_{j}, that the following inequality holds: $x_{j} \neq \operatorname{max}_{i = 1}^{k} x_{i}$.

The lucky number of the sequence of distinct positive integers x_1, x_2, ..., x_{k} (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.

You've got a sequence of distinct positive integers s_1, s_2, ..., s_{n} (n > 1). Let's denote sequence s_{l}, s_{l} + 1, ..., s_{r} as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].

Note that as all numbers in sequence s are distinct, all the given definitions make sence.

-----Input-----

The first line contains integer n (1 < n ≤ 10^5). The second line contains n distinct integers s_1, s_2, ..., s_{n} (1 ≤ s_{i} ≤ 10^9).

-----Output-----

Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r].

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

Output
7

Input
5
9 8 3 5 7

Output
15

-----Note-----

For the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].

For the second sample you must choose s[2..5] = {8, 3, 5, 7}.

n=int(input())
a=[int(n) for n in input().split()]
stack=[]
maxx=0
i=0
while i<n:
    if not stack or a[i]<stack[-1]:
        stack.append(a[i])
        i+=1
    else:
        maxx=(max(stack[-1]^a[i],maxx))
        temp=stack.pop()
        if stack:
            maxx=max(stack[-1]^temp,maxx)
    #print(stack)
while len(stack)!=1:
    temp=stack.pop()
    maxx=max(temp^stack[-1],maxx)
print(maxx)


Solve in Python:
Binary with 0 and 1 is good, but binary with only 0 is even better! Originally, this is a concept designed by Chuck Norris to send so called unary messages.

Can you write a program that can send and receive this messages?

Rules

The input message consists of ASCII characters between 32 and 127 (7-bit)
The encoded output message consists of blocks of 0
A block is separated from another block by a space
Two consecutive blocks are used to produce a series of same value bits (only 1 or 0 values):

First block is always 0 or 00. If it is 0, then the series contains 1, if not, it contains 0
The number of 0 in the second block is the number of bits in the series

Example
Let’s take a simple example with a message which consists of only one character (Letter 'C').'C' in binary is represented as 1000011, so with Chuck Norris’ technique this gives:

0 0 - the first series consists of only a single 1
00 0000 - the second series consists of four 0
0 00 - the third consists of two 1

So 'C' is coded as: 0 0 00 0000 0 00
Second example, we want to encode the message "CC" (i.e. the 14 bits 10000111000011) :

0 0 - one single 1
00 0000 - four 0
0 000 - three 1
00 0000 - four 0
0 00 - two 1

So "CC" is coded as: 0 0 00 0000 0 000 00 0000 0 00
Note of thanks
Thanks to the author of the original kata. I really liked this kata. I hope that other warriors will enjoy it too.

import re

def send(text):
    tmp = (ord(char) for char in text)
    tmp = (f"{x:07b}" for x in tmp)
    tmp = "".join(tmp)
    tmp = re.findall("0+|1+", tmp)
    tmp = (f"{'0' if group[0] == '1' else '00'} {'0' * len(group)}" for group in tmp)
    return " ".join(tmp)

def receive(unary):
    tmp = re.findall("(0+) (0+)", unary)
    tmp = (("0" if digit == "00" else "1") * len(count) for digit, count in tmp)
    tmp = "".join(tmp)
    tmp = re.findall(".{7}", tmp)
    tmp = (chr(int(x, 2)) for x in tmp)
    return "".join(tmp)


Solve in Python:
Binod is a youtuber and he is busy in the fame of social media so he asked you to help him solve a problem.
You have been given an array of $positive$ $integers$ $a_{1},a_{2},a_{3},...,a_{i},...,a_{n}$ of size n.You have to find the smallest length of the subarray such that the length of the subarray must be $strictly$ greater than k and it's sum also must be $strictly$ greater than s.

-----Input Format :------
- The first line of input contains three space-separated integers n, k and s
- The second line contains n space-separated integers,describing the array a

-----Output Format:-----
- Print a single integer :- The smallest length of subarray if exists, Otherwise print "-1" (without quotes)

-----Constraints:------
- $1 \leq n, k \leq 10^{6}$
- $1 \leq  a_{1},a_{2},a_{3},...,a_{i},...,a_{n}\leq 10^{9}$
- $1 \leq s \leq 10^{15}$ Subtask #1 (30 points):
- $1 \leq n, k \leq 10^{3}$ Subtask #2 (70 points):
$Original$ $Constraints$

-----Sample Test Cases:------

-----Example 1:-----
5 1 5

1 2 3 4 5

-----Output :-----
2

-----Explanation-----
$\textbf{There are two possibles answers} :$
- Index starts at 3 and ends at 4 have a sum of 7 which is strictly greater than 5 and has a length of subarray greater than 1.
- Index starts at 4 and ends at 5 have a sum of 9 which is strictly greater than 5 and has a length of subarray greater than 1.
Any of the possible scenarios gives the same answer.

-----Example 2:-----
3 2 1

9 9 1

-----Output :-----
3

-----Explanation :-----
- Each value in array index satisfies the condition sum greater than 1 but to satisfy the condition of length greater than 2 choose the subarray of length 3

try:

    n,k,s = list(map(int,input().split(' ')))
    arr = list(map(int,input().split(' ')))

    start = 0
    end = 0
    temp = 0
    for i in range(n):
        temp += arr[i]
        if temp > s and i-start+1 > k:
            end = i
        while temp-arr[start] > s and end-start > k:
            temp -= arr[start]
            start += 1
    if end == start:
        print(-1)
    else:
        print(end-start+1)

except:
    pass


Solve in Python:
Bit Vectors/Bitmaps
A bitmap is one way of efficiently representing sets of unique integers using single bits.
To see how this works, we can represent a set of unique integers between `0` and `< 20` using a vector/array of 20 bits:
```
var set = [3, 14, 2, 11, 16, 4, 6];```
```
var bitmap = [0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0];
```
As you can see, with a bitmap, the length of the vector represents the range of unique values in the set (in this case `0-20`), and the `0/1` represents whether or not the current index is equal to a value in the set.

Task:
Your task is to write a function `toBits` that will take in a set of uniqe integers and output a bit vector/bitmap (an array in javascript) using `1`s and `0`s to represent present and non-present values.
Input:
The function will be passed a set of unique integers in string form, in a random order, separated by line breaks.
Each integer can be expected to have a unique value `>= 0` and `< 5000`.
The input will look like this:
`let exampleInput = '3\n14\n5\n19\n18\n1\n8\n11\n2...'`
Output:
The function will be expected to output a 5000 bit vector (array) of bits, either `0` or `1`, for example:
`let exampleOutput = [0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0,...]`
More in-depth bitmap kata coming very soon, happy coding!
To learn more about bitmapping and to see the inspiration for making these kata, checkout the book Programming Pearls by Jon Bently.  It's a powerful resource for any programmer!

def to_bits(string):
    numbers = set(int(s) for s in string.split())
    return [(0,1)[n in numbers] for n in range(5000)]


Solve in Python:
Bitland declared war on Chefland and sent an army to fight them, but Chefland defended efficiently and Bitland's army has been reduced to N$N$ soldiers. They have no chance of winning the war and do not want to surrender, so they are planning to commit group suicide. Josh, the leader of Bitland's remaining soldiers, has different plans — he wants to survive and somehow escape.
The soldiers are numbered 1$1$ through N$N$; Josh is soldier N$N$. The soldiers are going to stand in a circle in the order 1,2,…,P−1,N,P,P+1,…,N−1$1, 2, \ldots, P-1, N, P, P+1, \ldots, N-1$. Formally, they are standing in the circle in such a way that if Josh's position is P$P$ (1≤P≤N$1 \le P \le N$), then for each i$i$ (1≤i≤N−2$1 \le i \le N-2$, i≠P−1$i \neq P-1$), soldier i+1$i+1$ is directly to the right of soldier i$i$, soldier P$P$ (if P≤N−1$P \le N-1$) or 1$1$ (if P=N$P = N$) is directly to the right of Josh and Josh is directly to the right of soldier P−1$P-1$ (if P≥2$P \ge 2$) or soldier N−1$N-1$ (if P=1$P = 1$); if 2≤P≤N−2$2 \le P \le N-2$, soldier 1$1$ is also directly to the right of soldier N−1$N-1$. For each i$i$ (1≤i≤N−1$1 \le i \le N-1$), soldier i$i$ has a sword with power Ai$A_i$. Josh plans to take a shield with sufficiently high defense power D$D$.
First, the soldiers start to commit group suicide according to the following rules:
- Initially, soldier 1$1$ is the attacking soldier.
- If the attacking soldier is not Josh, this soldier attacks the soldier that is currently to his right.
- When Josh is attacked with power a$a$, the current defense power of his shield decreases by a$a$, and if it becomes negative, Josh dies. When a different soldier is attacked, he does not try to defend and dies immediately. The power of the attacking soldier's sword does not change.
- Then, the next living soldier to the right of the current attacking soldier becomes the attacking soldier and the process continues until there is only one soldier left.
It is clear that this way, Josh cannot be the last survivor. However, Chefland's...

# cook your dish here
def solve_small(numbers, n, f):

    found = False
    min_shield = 0
    min_pos = 0
    for pos in range(n):
        # First optimization
        next_pos0 = pos % (n - 1)
        # print(pos, next_pos0)
        if numbers[next_pos0] > f:
            continue

        new_numbers = [_ for _ in numbers]
        new_numbers.insert(pos, 0)
        #print("new numbers: ",new_numbers, next_pos0)

        curr_pos = 0
        # round = 1
        while len(new_numbers) > 2:
            next_pos = (curr_pos + 1) % len(new_numbers)
            # print("Round {}: {}, {}, {}".format(round, curr_pos, next_pos, new_numbers))
            if new_numbers[next_pos] <= 0:
                # print("Attacked Josh from {} to {}".format(curr_pos, next_pos))
                new_numbers[next_pos] -= new_numbers[curr_pos]
            elif new_numbers[curr_pos] > 0:
                # print("Killed soldier from {} to {}".format(curr_pos, next_pos))
                new_numbers.pop(next_pos)
            else:
                # print("Josh does not attack")
                pass
            if curr_pos >= len(new_numbers) - 1:
                curr_pos = 0
            else:
                curr_pos += 1
            # print("Round {}: {}, {}".format(round, curr_pos, new_numbers))
            # round += 1

        # print(new_numbers, f)
        shield, min_f = -min(new_numbers), max(new_numbers)

        # Other soldier will survive
        if min_f > f:
            continue

        # Only Josh survives
        shield += f
        found = True
        if not min_shield or min_shield > shield:
            min_shield = shield
            min_pos = pos

    if found:
        print("possible")
        return min_pos + 1, min_shield
    else:
        print("impossible")
        return 0, 0
def solve_med(numbers, n, f):

    min_shield = 0
    min_pos = 0
    left_numbers = []
    right_numbers = [0] + [_ for _ in numbers]

    for pos in range(0, n):

        right_numbers.pop(0)
        if pos % 2:
           ...


Solve in Python:
Bleatrix Trotter the sheep has devised a strategy that helps her fall asleep faster. First, she picks a number N. Then she starts naming N, 2 × N, 3 × N, and so on.
Whenever she names a number, she thinks about all of the digits in that number. She keeps track of which digits (0, 1, 2, 3, 4, 5, 6, 7, 8, and 9) she has seen at least once so far as part of any number she has named. Once she has seen each of the ten digits at least once, she will fall asleep.
Bleatrix must start with N and must always name (i + 1) × N directly after i × N.
For example, suppose that Bleatrix picks N = 1692. She would count as follows:

N = 1692. Now she has seen the digits 1, 2, 6, and 9.
2N = 3384. Now she has seen the digits 1, 2, 3, 4, 6, 8, and 9.
3N = 5076. Now she has seen all ten digits, and falls asleep.

The purpose of this kata is to return the last number Bleatrix Trotter sees before falling asleep.
Input
Will always be positive integer or zero

Output
The last number Bleatrix Trotter sees or "INSOMNIA" (-1 in Rust and C++) if she will count forever

Please note, this challenge is not my idea. It's from Google Code Jam 2016

def trotter(n):
    i, numStr, numList =0,'',['0','1','2','3','4','5','6','7','8','9']
    if n==0:
        return('INSOMNIA')
    while all([i in numStr for i in numList])!=True:
        i+=1
        numStr = numStr+str(n*i)
    return(i*n)


Solve in Python:
Blob is a computer science student. He recently got an internship from Chef's enterprise. Along with the programming he has various other skills too like graphic designing, digital marketing and social media management. Looking at his skills Chef has provided him different tasks A[1…N] which have their own scores. Blog wants to maximize the  value of the expression A[d]-A[c]+A[b]-A[a] such that d>c>b>a.

Can you help him in this?

-----Input:-----
- The first line contain the integer N
- The second line contains N space separated integers representing A[1], A[2] … A[N]

-----Output:-----
The maximum score that is possible

-----Constraints-----
- $4 \leq N \leq 10^4$
- $0 \leq A[i] \leq 10^5$

-----Sample Input:-----
6

3 9 10 1 30 40

-----Sample Output:-----
46

def maxval(arr):
    fn = [float('-inf')]*(len(arr)+1)
    sn = [float('-inf')]*len(arr)
    tn = [float('-inf')]*(len(arr)-1)
    fon = [float('-inf')]*(len(arr)-2)
    for i in reversed(list(range(len(arr)))):
        fn[i] = max(fn[i + 1], arr[i])
    for i in reversed(list(range(len(arr) - 1))):
        sn[i] = max(sn[i + 1], fn[i + 1] - arr[i])

    for i in reversed(list(range(len(arr) - 2))):
        tn[i] = max(tn[i + 1], sn[i + 1] + arr[i])

    for i in reversed(list(range(len(arr) - 3))):
        fon[i] = max(fon[i + 1], tn[i + 1] - arr[i])
    return fon[0]
n = int(input())
arr = list(map(int,input().split()))
print(maxval(arr))


Solve in Python:
Bob has a permutation of integers from 1 to n. Denote this permutation as p. The i-th element of p will be denoted as p_{i}. For all pairs of distinct integers i, j between 1 and n, he wrote the number a_{i}, j = min(p_{i}, p_{j}). He writes a_{i}, i = 0 for all integer i from 1 to n.

Bob gave you all the values of a_{i}, j that he wrote down. Your job is to reconstruct any permutation that could have generated these values. The input will be formed so that it is guaranteed that there is at least one solution that is consistent with the information given.

-----Input-----

The first line of the input will contain a single integer n (2 ≤ n ≤ 50).

The next n lines will contain the values of a_{i}, j. The j-th number on the i-th line will represent a_{i}, j. The i-th number on the i-th line will be 0. It's guaranteed that a_{i}, j = a_{j}, i and there is at least one solution consistent with the information given.

-----Output-----

Print n space separated integers, which represents a permutation that could have generated these values. If there are multiple possible solutions, print any of them.

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

Output
2 1

Input
5
0 2 2 1 2
2 0 4 1 3
2 4 0 1 3
1 1 1 0 1
2 3 3 1 0

Output
2 5 4 1 3

-----Note-----

In the first case, the answer can be {1, 2} or {2, 1}.

In the second case, another possible answer is {2, 4, 5, 1, 3}.

#!/bin/python3
import sys
n = int(input())
matrix = []
for i in range(n):
    tlist = [int(a) for a in input().split(' ')]
    matrix.append(tlist)

for i in range(n):
    if set(range(n)) == set(matrix[i]):
        big = i
        break

for i in range(n):
    if i == big:
        sys.stdout.write("{} ".format(n))
    else:
        sys.stdout.write("{} ".format(matrix[big][i]))


Solve in Python:
Bob has a server farm crunching numbers. He has `nodes` servers in his farm. His company has a lot of work to do.

The work comes as a number `workload` which indicates how many jobs there are. Bob wants his servers to get an equal number of jobs each. If that is impossible, he wants the first servers to receive more jobs. He also wants the jobs sorted, so that the first server receives the first jobs.

The way this works, Bob wants an array indicating which jobs are going to which servers.

Can you help him distribute all this work as evenly as possible onto his servers?

Example
-------

Bob has `2` servers and `4` jobs. The first server should receive job 0 and 1 while the second should receive 2 and 3.

```
distribute(2, 4) # => [[0, 1], [2, 3]]
```

On a different occasion Bob has `3` servers and `3` jobs. Each should get just one.

```
distribute(3, 3) # => [[0], [1], [2]]
```

A couple of days go by and Bob sees a spike in jobs. Now there are `10`, but he hasn't got more than `4` servers available. He boots all of them. This time the first and second should get a job more than the third and fourth.

```
distribute(4, 10) # => [[0, 1, 2], [3, 4, 5], [6, 7], [8, 9]]
```

Input
-----

Don't worry about invalid inputs. That is, `nodes > 0` and `workload > 0` and both will always be integers.

def distribute(n, w):
    g, (d,r) = iter(range(w)), divmod(w,n)
    return [ [next(g) for _ in range(d+(i<r))] for i in range(n)]


Solve in Python:
Bob has got some injury in his leg and due to this he can take exactly M steps in one move.
Bob enters a square field of size NxN. The field is only having one gate(for both entrance and exit) at its one of the corners. Bob started walking along the perimeter of square field.(remember Bob can only take exactly M steps in one move and cannot reverse his direction of motion).
Bob wants to know how many minimum number of moves he needs to come out(i.e. he reaches the same gate from where he entered into the field) from the square field. Tell the answer to Bob ASAP.
Luckily, you came to know M=N+1.

-----Input-----
- The first line of the input contains an integer T denoting the number of test cases.
-  Each test case contains a single integer N denoting the sides of the square.

-----Output-----
- For each test case, output a single line containing minimum number of moves Bob required to come out from the field.

-----Constraints-----
- 1 ≤ T ≤ 10000
- 1 ≤ N ≤ 1000000000

-----Example-----
Input:
2
1
2

Output:
2
8

-----Explanation-----
Example case 1.Let four corners of square be (0,0), (0,1), (1,1), (1,0). Let gate be at (0,0). Bob takes 2 steps in one move. Let movement of Bob be as follows (0,0) -> (1,1) -> (0,0). Thus minimum moves needed were 2.
Example case 2.Let four corners of square be (0,0), (0,2), (2,2), (2,0). Let gate be at (0,0). Bob takes 3 steps in one move. Let movement of Bob be as follows (0,0) -> (2,1) -> (0,2) -> (1,0) -> (2,2) -> (0,1) -> (2,0) -> (1,2) -> (0,0). Thus minimum number of moves needed are 8.

def function():
 print('hello world!!its ranjeet kumar yadav from iiitdmj')

#please ignore the size of variable
tgnfdngnd=eval(input())
while tgnfdngnd>0:
 tgnfdngnd=tgnfdngnd-1
 #taking input
 adddddd=eval(input())
 s=0
 #calculating size of perimeter

 s=2*(adddddd+1)+2*(adddddd-1)
 i=0

 vddddddddddddd=0
 dddddddddddddddd=0
 if adddddd%2==0:
  print(s)
 else:
  n=(adddddd-1)/2+1
  if n%2==0:
   print(adddddd)
  else:
   print(adddddd*2)


Solve in Python:
Bob has ladder. He wants to climb this ladder, but being a precocious child, he wonders about exactly how many ways he could to climb this `n` size ladder using jumps of up to distance `k`.

Consider this example...

n = 5\
k = 3

Here, Bob has ladder of length 5, and with each jump, he can ascend up to 3 steps (he can either jump step 1 or 2 or 3). This gives the below possibilities

```
1 1 1 1 1
1 1 1 2
1 1 2 1
1 2 1 1
2 1 1 1
1 2 2
2 2 1
2 1 2
1 1 3
1 3 1
3 1 1
2 3
3 2
```

Your task to calculate number of ways to climb ladder of length `n` with upto `k` steps for Bob. (13 in above case)

Constraints:

```python
1<=n<=50
1<=k<=15
```

_Tip: try fibonacci._

from functools import lru_cache

@lru_cache(None)
def count_ways(n, k):
    return sum(count_ways(n - a, k) for a in range(1, min(n, k) + 1)) if n else 1