Solve in Python:
Jett is tired after destroying the town and she wants to have a rest. She likes high places, that's why for having a rest she wants to get high and she decided to craft staircases.

A staircase is a squared figure that consists of square cells. Each staircase consists of an arbitrary number of stairs. If a staircase has $n$ stairs, then it is made of $n$ columns, the first column is $1$ cell high, the second column is $2$ cells high, $\ldots$, the $n$-th column if $n$ cells high. The lowest cells of all stairs must be in the same row.

A staircase with $n$ stairs is called nice, if it may be covered by $n$ disjoint squares made of cells. All squares should fully consist of cells of a staircase. This is how a nice covered staircase with $7$ stairs looks like: [Image]

Find out the maximal number of different nice staircases, that can be built, using no more than $x$ cells, in total. No cell can be used more than once.

-----Input-----

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

The description of each test case contains a single integer $x$ $(1 \le x \le 10^{18})$  — the number of cells for building staircases.

-----Output-----

For each test case output a single integer  — the number of different nice staircases, that can be built, using not more than $x$ cells, in total.

-----Example-----
Input
4
1
8
6
1000000000000000000

Output
1
2
1
30

-----Note-----

In the first test case, it is possible to build only one staircase, that consists of $1$ stair. It's nice. That's why the answer is $1$.

In the second test case, it is possible to build two different nice staircases: one consists of $1$ stair, and another consists of $3$ stairs. This will cost $7$ cells. In this case, there is one cell left, but it is not possible to use it for building any nice staircases, that have not been built yet. That's why the answer is $2$.

In the third test case, it is possible to build only one of two nice staircases: with $1$ stair or with $3$ stairs. In the first...

from math import log2
for _ in range(int(input())):
    x = int(input())
    acc = 0
    for i in range(1, 60):
        acc += (2**i-1) * (2**(i-1))
        if acc > x:
            break
    print(i-1)


Solve in Python:
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3.

A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge.

John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it.

-----Input-----

A single line contains an integer k (1 ≤ k ≤ 10^5) — the number of cycles of length 3 in the required graph.

-----Output-----

In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i.

-----Examples-----
Input
1

Output
3
011
101
110

Input
10

Output
5
01111
10111
11011
11101
11110

n , k = 0 , int(input())
p=[['0']*100 for i in range(100)]
while k:
 for i in range(n):
  if i>k:
   break
  p[n][i]=p[i][n]='1'
  k=k-i
 n+=1
print(n)
for i in range(n): print(''.join(p[i][:n]))


Solve in Python:
John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.

There are $n$ students, each of them has a unique id (from $1$ to $n$). Thomas's id is $1$. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids.

In the table, the students will be sorted by decreasing the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by increasing their ids.

Please help John find out the rank of his son.

-----Input-----

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

Each of the next $n$ lines contains four integers $a_i$, $b_i$, $c_i$, and $d_i$ ($0\leq a_i, b_i, c_i, d_i\leq 100$) — the grades of the $i$-th student on English, German, Math, and History. The id of the $i$-th student is equal to $i$.

-----Output-----

Print the rank of Thomas Smith. Thomas's id is $1$.

-----Examples-----
Input
5
100 98 100 100
100 100 100 100
100 100 99 99
90 99 90 100
100 98 60 99

Output
2

Input
6
100 80 90 99
60 60 60 60
90 60 100 60
60 100 60 80
100 100 0 100
0 0 0 0

Output
1

-----Note-----

In the first sample, the students got total scores: $398$, $400$, $398$, $379$, and $357$. Among the $5$ students, Thomas and the third student have the second highest score, but Thomas has a smaller id, so his rank is $2$.

In the second sample, the students got total scores: $369$, $240$, $310$, $300$, $300$, and $0$. Among the $6$ students, Thomas got the highest score, so his rank is $1$.

def main():
    n = int(input())
    scores = []
    for i in range(n):
        a = list(map(int, input().split()))
        tot = sum(a)
        scores.append((-tot, i))

    scores.sort()
    for i in range(n):
        if scores[i][1] == 0:
            print(i + 1)

main()


Solve in Python:
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.

Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?

Example:

With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.

The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.

The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.

The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.

Examples:

`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`

`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`

`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`

Note: don't modify the input list `ls`

from itertools import combinations

def choose_best_sum(t, k, ls):
    l = [i for i in ls if i<=t]
    print(t, k, ls, l)
    try:
        return sorted([sum(i) for i in combinations(l, k) if sum(i)<=t])[-1]
    except:
        return None


Solve in Python:
John and his wife Ann have decided to go to Codewars.

On first day Ann will do one kata and John - he wants to know how it is working - 0 kata.

Let us call `a(n)` - and `j(n)` - the number of katas done by Ann - and John - at day `n`. We have `a(0) = 1` and in the same manner `j(0) = 0`.

They have chosen the following rules:

- On day `n` the number of katas done by Ann should be `n` minus the number of katas done by John at day `t`, `t` being equal to the number of katas done
by Ann herself at day `n - 1`.

- On day `n` the number of katas done by John should be `n` minus the number of katas done by Ann at day `t`, `t` being equal to the number of katas done
by John himself at day `n - 1`.

Whoops! I think they need to lay out a little clearer exactly what there're getting themselves into!

# Could you write:
- 1) two functions `ann` and `john (parameter n)` giving the list of the numbers of katas Ann and John should take on the first n days (see first examples below)?
- 2) The total number of katas taken by ann `function sum_ann(n)` and john `function sum_john(n)` - on the first n days?

The functions in 1) are not tested in Fortran and not tested in Shell.

# Examples:
```
john(11) -->  [0, 0, 1, 2, 2, 3, 4, 4, 5, 6, 6]
ann(6) -->  [1, 1, 2, 2, 3, 3]

sum_john(75) -->  1720
sum_ann(150) -->  6930
```

# Shell Note:
sumJohnAndAnn has two parameters:

first one : n (number of days, $1)

second one : which($2) ->

- 1 for getting John's sum

- 2 for getting Ann's sum.

See "Sample Tests".

# Note:

Keep an eye on performance.

from functools import lru_cache

@lru_cache(maxsize = None)
def john_value(n):
    if n == 0:
        return 0
    return n - ann_value(john_value(n - 1))

@lru_cache(maxsize = None)
def ann_value(n):
    if n == 0:
        return 1
    return n - john_value(ann_value(n - 1))

def ann(n):
    return [ann_value(x) for x in range(n)]

def john(n):
    return [john_value(x) for x in range(n)]

def sum_john(n):
    return sum(john(n))

def sum_ann(n):
    return sum(ann(n))


Solve in Python:
John has invited some friends. His list is:
```
s = "Fred:Corwill;Wilfred:Corwill;Barney:Tornbull;Betty:Tornbull;Bjon:Tornbull;Raphael:Corwill;Alfred:Corwill";
```

Could you make a program that
- makes this string uppercase
- gives it sorted in alphabetical order by last name.

When the last names are the same, sort them by first name.
Last name and first name of a guest come in the result between parentheses separated by a comma.

So the result of function `meeting(s)` will be:
```
"(CORWILL, ALFRED)(CORWILL, FRED)(CORWILL, RAPHAEL)(CORWILL, WILFRED)(TORNBULL, BARNEY)(TORNBULL, BETTY)(TORNBULL, BJON)"
```
It can happen that in two distinct families with the same family name two people have the same first name too.

# Notes
- You can see another examples in the "Sample tests".

from functools import reduce

def meeting(s):
    people = [ i.split(":")[::-1] for i in s.upper().split(";") ]
    people.sort(key=lambda x: x[0]+" "+x[1])
    return reduce(lambda acc, x: acc+"("+x[0]+", "+x[1]+")", people, "")


Solve in Python:
John has some amount of money of which he wants to deposit a part `f0` to the bank at the beginning
of year `1`. He wants to withdraw each year for his living an amount `c0`.

Here is his banker plan:

- deposit `f0` at beginning of year 1
- his bank account has an interest rate of `p` percent per year, constant over the years
- John can withdraw each year `c0`, taking it whenever he wants in the year; he must take account of an inflation of `i` percent per year in order to keep his quality of living. `i` is supposed to stay constant over the years.
- all amounts f0..fn-1, c0..cn-1 are truncated by the bank to their integral part
- Given f0, `p`, c0, `i`
the banker guarantees that John will be able to go on that way until the `nth` year.

# Example:

```
f0 = 100000, p = 1 percent, c0 = 2000, n = 15, i = 1 percent
```

```
beginning of year 2 -> f1 = 100000 + 0.01*100000 - 2000 = 99000;  c1 = c0 + c0*0.01 = 2020 (with inflation of previous year)
```

```
beginning of year 3 -> f2 =  99000 + 0.01*99000 - 2020  = 97970;  c2 = c1 + c1*0.01 = 2040.20
(with inflation of previous year, truncated to 2040)
```

```
beginning of year 4 -> f3 =  97970 + 0.01*97970 - 2040  = 96909.7 (truncated to 96909);
c3 = c2 + c2*0.01 = 2060.4 (with inflation of previous year, truncated to 2060)
```
and so on...

John wants to know if the banker's plan is right or wrong.
Given parameters `f0, p, c0, n, i` build a function `fortune` which returns `true` if John can make a living until the `nth` year
and `false` if it is not possible.

# Some cases:
```
fortune(100000, 1, 2000, 15, 1) -> True
fortune(100000, 1, 10000, 10, 1) -> True
fortune(100000, 1, 9185, 12, 1) -> False

For the last case you can find below the amounts of his account at the beginning of each year:
100000, 91815, 83457, 74923, 66211, 57318, 48241, 38977, 29523, 19877, 10035, -5
```
f11 = -5 so he has no way to withdraw something for his living in year 12.

> **Note:** Don't forget to convert the percent parameters as percentages in the body of your function: if a...


Solve in Python:
John is developing a system to report fuel usage but needs help with the coding.

First, he needs you to write a function that, given the actual consumption (in l/100 km) and remaining amount of petrol (in l), will give you how many kilometers you'll be able to drive.

Second, he needs you to write a function that, given a distance (in km), a consumption (in l/100 km), and an amount of petrol (in l), will return one of the following: If you can't make the distance without refueling, it should return the message "You will need to refuel". If you can make the distance, the function will check every 100 km and produce an array with [1:kilometers already driven. 2: kilometers till end. 3: remaining amount of petrol] and return all the arrays inside another array ([[after 100km], [after 200km], [after 300km]...])

PLEASE NOTE: any of the values with decimals that you return should be rounded to 2 decimals.

def total_kilometers(cons, petrol):
    distance = round(((petrol/cons) * 100), 2)
    return distance

def check_distance(distance, cons, petrol):
    outp = []
    track = 0
    driven_dist = 0
    if distance > ((petrol/cons) * 100):
        return 'You will need to refuel'
    while track <= distance:
        outp.append([driven_dist, distance - driven_dist, round(petrol, 2)])
        driven_dist += 100
        petrol -= cons
        track += 100
    return outp


Solve in Python:
John wants to decorate a room with wallpaper. He's heard that
making sure he has the right amount of wallpaper is more complex than it sounds.
He wants a fool-proof method for getting it right.

John knows that the rectangular room has a length of `l` meters, a width of `w` meters, a height of `h` meters.
The standard width of the rolls he wants to buy is `52` centimeters. The
length of a roll is `10` meters.
He bears in mind however, that it’s best to have an extra length of wallpaper handy in case of mistakes or miscalculations so he wants to buy a length `15%` greater than the one he needs.

Last time he did these calculations he got a headache, so could you help John? Your function `wallpaper(l, w, h)` should return as a plain English word
in lower case the number of rolls he must buy.

### Example:

`wallpaper(4.0, 3.5, 3.0) should return "ten"`

`wallpaper(0.0, 3.5, 3.0) should return "zero"`

# Notes:
- all rolls (even with incomplete width) are put edge to edge
- 0 <= l, w, h (floating numbers), it can happens that `w x h x l` is zero
- the integer `r` (number of rolls) will always be less or equal to 20

- FORTH: the number of rolls will be a *positive or null integer* (not a plain English word; this number can be greater than 20)

def wallpaper(l, w, h):

    result = {

        '1': 'one',
        '2': 'two',
        '3': 'three',
        '4': 'four',
        '5': 'five',
        '6': 'six',
        '7': 'seven',
        '8': 'eight',
        '9': 'nine',
        '10': 'ten',
        '11': 'eleven',
        '12': 'twelve',
        '13': 'thirteen',
        '14': 'fourteen',
        '15': 'fifteen',
        '16': 'sixteen',
        '17': 'seventeen',
        '18': 'eighteen',
        '19': 'nineteen',
        '20': 'twenty',
    }

    wall_area = 1.15 * ((2*l*h) + (2*w*h))
    wallpaper = 0.52 * 10
    to_buy = wall_area / wallpaper

    for k,v in result.items():
        if l == 0 or w == 0 or h == 0:
            return 'zero'
        elif int(k) == round(to_buy + 0.5):
            return v


Solve in Python:
John was learning mathematics and was very bored. Jane his best friend gave him a problem to solve.
The description of the problem was as follows:-
You are given a decimal number $N$(1<=$N$<=$10^9$) and three integers $A$, $B$, $C$.
Steps to perform:
1) You have to create a $LIST$.
2) You have to initialize the $LIST$ by adding N to the $LIST$ as its first element.
3) Divide$N$ by $A$ and if the first digit of the fractional part is Non-Zero then add this digit to the  $LIST$ otherwise add the first digit of the integral part(Leftmost digit).
(The integer part or integral part of a decimal is the integer written to the left of the decimal separator.  The part from the decimal separator i.e to the right is the fractional part. )
4) Update $N$  by Last element of the $LIST$.
N = Last element of $LIST$
5) You have to perform the same process from step 3 on $N$ for $B$ and $C$ respectively
6) Repeat from step 3
You have to answer$Q$(1 <= $Q$<= 100 ) queries
For each query you are given an integer $i$ (0 <= $i$ <= $10^9$ ). You have to print the element present at the ith position of the $LIST$.
Help John solve this problem.

-----Input:-----
- The First Line of input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The First Line of each test case contains the  integer $N$.
- The second line of each test case contains three integers $A$, $B$, and $C$ separated by a space
- The third line of each test case contains an integer $Q$.
- Then the next $Q$ line follows.
- An integer $i$ (0 <= $i$ <= 10^9 )

-----Output:-----
You have to answer the $Q$ queries in the next $Q$ lines.

-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq N \leq 10^9$
- $2 \leq A \leq 10$
- $2 \leq B \leq 10$
- $2 \leq C \leq 10$
- $2 \leq Q \leq 100$
- $0 \leq i \leq 10^9$

-----Sample Input:-----
1
56
3 5 7
4
0
1
2
3

-----Sample Output:-----
56
6
2
2

-----EXPLANATION:-----
This list is :
$N$ = 56 and $A$ = 3, $B$ = 5, $C$ = 7.
Initially $LIST$ = $[ 56 ]$
$N$$/$$A$...

t=int(input())
for i in range(t):
    n=int(input())
    q0=n
    a,b,c=list(map(int,input().split()))
    list1=[n]
    k=1
    while(len(list1)-list1.index(n)-1<3 or (len(list1)-1-list1.index(n))%3!=0):
        if(k==1):
            n/=a
            k=2
        elif(k==2):
            n/=b
            k=3
        elif(k==3):
            n/=c
            k=1
        fd=str(n)[0]
        if((int(n*10))%10!=0):
            list1.append((int(n*10))%10)
        else:
            list1.append(int(fd))
        n=list1[-1]
    del list1[-1]
    list2=list1[list1.index(n):]
    for j in range(int(input())):
        q=int(input())
        if(q<len(list1)):
            print(list1[q])
        else:
            print(list2[(q-list1.index(n))%(len(list2))])


Solve in Python:
Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems.

The boy has found an online judge with tasks divided by topics they cover. He has picked $p^{k_i}$ problems from $i$-th category ($p$ is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced.

Formally, given $n$ numbers $p^{k_i}$, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo $10^{9}+7$.

-----Input-----

Input consists of multiple test cases. The first line contains one integer $t$ $(1 \leq t \leq 10^5)$ — the number of test cases. Each test case is described as follows:

The first line contains two integers $n$ and $p$ $(1 \leq n, p \leq 10^6)$. The second line contains $n$ integers $k_i$ $(0 \leq k_i \leq 10^6)$.

The sum of $n$ over all test cases doesn't exceed $10^6$.

-----Output-----

Output one integer — the reminder of division the answer by $1\,000\,000\,007$.

-----Example-----
Input
4
5 2
2 3 4 4 3
3 1
2 10 1000
4 5
0 1 1 100
1 8
89

Output
4
1
146981438
747093407

-----Note-----

You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to $2$, but there is also a distribution where the difference is $10^9 + 8$, then the answer is $2$, not $1$.

In the first test case of the example, there're the following numbers: $4$, $8$, $16$, $16$, and $8$. We can divide them into such two sets: ${4, 8, 16}$ and ${8, 16}$. Then the difference between the sums of numbers in sets would be $4$.

import sys
input = sys.stdin.readline

MOD = 10 ** 9 + 7

t = int(input())
for _ in range(t):
    n, p = list(map(int, input().split()))
    l = list(map(int, input().split()))
    if p == 1:
        print(n % 2)
    else:
        l.sort(reverse = True)
        curr = l[0]
        out = 0
        real = True

        for v in l:
            if v < curr:
                diff = curr - v
                if 10 ** (7/diff) < p and out > 0:
                    real = False
                out *= pow(p, diff, MOD)
                if out > 10 ** 7:
                    real = False
                out %= MOD

                curr = v
            if out > 0 or not real:
                out -= 1
            else:
                out += 1
            out %= MOD

        out *= pow(p, curr, MOD)
        print(out % MOD)


Solve in Python:
Johnny has some difficulty memorizing the small prime numbers. So, his computer science teacher has asked him to play with the following puzzle game frequently.
The puzzle is a 3x3 board consisting of numbers from 1 to 9. The objective of the puzzle is to swap the tiles until the following final state is reached:
1 2 3
4 5 6
7 8 9

At each step, Johnny may swap two adjacent tiles if their sum is a prime number. Two tiles are considered adjacent if they have a common edge.
Help Johnny to find the shortest number of steps needed to reach the goal state.

-----Input-----
The first line contains t, the number of test cases (about 50). Then t test cases follow. Each test case consists of a 3x3 table describing a puzzle which Johnny would like to solve.
The input data for successive test cases is separated by a blank line.

-----Output-----
For each test case print a single line containing the shortest number of steps needed to solve the corresponding puzzle. If there is no way to reach the final state, print the number -1.

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

7 3 2
4 1 5
6 8 9

9 8 5
2 4 1
3 7 6

Output:
6
-1

-----Output details-----
The possible 6 steps in the first test case are described in the following figure:

# cook your dish here
from collections import deque
primes = {2,3,5,7,11,13,17}
edges = [(0,3),(0,1),(1,2),(1,4),(2,5),(3,4),(3,6),(4,5),(4,7),(5,8),(6,7),(7,8)]
x = [1,2,3,4,5,6,7,8,9]
avail = {tuple(x):0}
q = deque([x])
while q:
    curr = q.popleft();
    for e in edges:
        if curr[e[0]]+curr[e[1]] in primes:
            nxt = curr[0:]
            nxt[e[0]],nxt[e[1]] = nxt[e[1]], nxt[e[0]]
            nxtt = tuple(nxt)
            if nxtt not in avail:
                avail[nxtt] = avail[tuple(curr)]+1
                q.append(nxt)
t = int(input())
# print(avail)
while t:
    inp = input()
    grid = []
    for i in range(3):
        inp = input()
        for j in inp.strip().split(" "):
            grid.append(int(j))
    gridt = tuple(grid)
    if gridt in avail: print(avail[gridt])
    else: print(-1);
    t-= 1# cook your dish here


Solve in Python:
Johnny is a boy who likes to open and close lockers. He loves it so much that one day, when school was out, he snuck in just to play with the lockers.

Each locker can either be open or closed. If a locker is closed when Johnny gets to it, he opens it, and vice versa.

The lockers are numbered sequentially, starting at 1.

Starting at the first locker, Johnny runs down the row, opening each locker.

Then he runs all the way back to the beginning and runs down the row again, this time skipping to every other locker. (2,4,6, etc)

Then he runs all the way back and runs through again, this time skipping two lockers for every locker he opens or closes. (3,6,9, etc)

He continues this until he has finished running past the last locker (i.e. when the number of lockers he skips is greater than the number of lockers he has).

------

The equation could be stated as follows:

> Johnny runs down the row of lockers `n` times, starting at the first locker each run and skipping `i` lockers as he runs, where `n` is the number of lockers there are in total and `i` is the current run.

The goal of this kata is to determine which lockers are open at the end of Johnny's running.

The program accepts an integer giving the total number of lockers, and should output an array filled with the locker numbers of those which are open at the end of his run.

def locker_run(lockers):
    return [n*n for n in range(1,int(lockers**.5+1))]


Solve in Python:
Johnny is a farmer and he annually holds a beet farmers convention "Drop the beet".

Every year he takes photos of farmers handshaking. Johnny knows that no two farmers handshake more than once. He also knows that some of the possible handshake combinations may not happen.

However, Johnny would like to know the minimal amount of people that participated this year just by counting all the handshakes.

Help Johnny by writing a function, that takes the amount of handshakes and returns the minimal amount of people needed to perform these handshakes (a pair of farmers handshake only once).

def get_participants(handshakes):
    farmers = 1
    maxshakes = 0
    while maxshakes < handshakes:
        maxshakes += farmers
        farmers += 1
    return farmers


Solve in Python:
Johnny was asked by his math teacher to compute nn (n to the power of n, where n is an integer), and has to read his answer out loud. This is a bit of a tiring task, since the result is probably an extremely large number, and would certainly keep Johnny occupied for a while if he were to do it honestly. But Johnny knows that the teacher will certainly get bored when listening to his answer, and will sleep through most of it! So, Johnny feels he will get away with reading only the first k digits of the result before the teacher falls asleep, and then the last k digits when the teacher wakes up.

Write a program to help Johnny to compute the digits he will need to read out.

-----Input-----
The first line contains t, the number of test cases (about 30000). Then t test cases follow.
Each test case consists of one line containing two numbers n and k (1 ≤ n ≤ 109, 1 ≤ k ≤ 9). It is guaranteed that k is not more than the number of digits of nn.

-----Output-----
For each test case, print out one line containing two numbers, separated by a space, which are the first and the last k digits of nn.

-----Example-----
Input
2
4 2
9 3

Output
25 56
387 489

from math import log10
from decimal import Decimal
def solve(n,k):

 mod=10**k
 x=Decimal(n)
 y=x*(x.log10())%1
 p=str(pow(10,y))
 c=0
 first=''
 for v in p:
  if c==k:
   break
  if v==".":
   continue
  first+=v
  c+=1
 last=str(pow(n,n,mod)).zfill(k)
 return (first,last)
queries=[]
for _ in range(int(input())):
 n,k=list(map(int,input().split( )))
 queries.append((n,k))
for n,k in queries:
 print("%s %s"%(solve(n,k)))


Solve in Python:
Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least $\frac{p_{i} - \epsilon}{2000}$, where ε < 10^{ - 7}.

To better prepare himself, he wants to know the answer for q different values of p_{i}. Since he is busy designing the battle strategy with Sam, he asks you for your help.

-----Input-----

First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively.

Each of the next q lines contain a single integer p_{i} (1 ≤ p_{i} ≤ 1000) — i-th query.

-----Output-----

Output q lines. On i-th of them output single integer — answer for i-th query.

-----Examples-----
Input
1 1
1

Output
1

Input
2 2
1
2

Output
2
2


Solve in Python:
Jon and Joe have received equal marks in the school examination. But, they won't reconcile in peace when equated with each other. To prove his might, Jon challenges Joe to write a program to find all possible number combos that sum to a given number. While unsure whether he would be able to accomplish this feat or not, Joe accpets the challenge. Being Joe's friend, your task is to help him out.

# Task

Create a function `combos`, that accepts a single positive integer `num` (30 > `num` > 0) and returns an array of arrays of positive integers that sum to `num`.

# Notes
1. Sub-arrays may or may not have their elements sorted.
2. The order of sub-arrays inside the main array does not matter.
3. For an optimal solution, the following operation should complete within 6000ms.

# Sample

def combos(n):
    def partition(residue, acc):
        if residue == 0:
            yield acc[1:]
        else:
            for part in range(acc[-1], residue + 1):
                for result in partition(residue - part, acc + [part]):
                    yield result

    return list(partition(n, [1]))


Solve in Python:
Jump is a simple one-player game:

You are initially at the first cell of an array of cells containing non-negative integers;

At each step you can jump ahead in the array as far as the integer at the current cell, or any smaller number of cells.
You win if there is a path that allows you to jump from one cell to another, eventually jumping past the end of the array, otherwise you lose.

For instance, if the array contains the integers

`[2, 0, 3, 5, 0, 0, 3, 0, 0, 3, 1, 0]`,

you can win by jumping from **2**, to **3**, to **5**, to **3**, to **3**, then past the end of the array.

You can also directly jump from from the initial cell(first cell) past the end of the array if they are integers to the right of that cell.

E.g

`[6, 1, 1]` is winnable

`[6]` is **not** winnable

Note: You can **not** jump from the last cell!

`[1, 1, 3]` is **not** winnable

## -----

Your task is to complete the function `canJump()`  that determines if a given game is winnable.

### More Examples

``` javascript
canJump([5]) //=> false
canJump([2, 5]) //=> true
canJump([3, 0, 2, 3]) //=> true (3 to 2 then past end of array)
canJump([4, 1, 2, 0, 1]) //=> false
canJump([5, 0, 0, 0]) //=> true
canJump([1, 1]) //=> false
```

def can_jump(arr):
    length = len(arr)
    i = length - 2
    while i >= 0:
      if arr[i] + i >= length:
        length = i
      i-=1
    return length == 0


Solve in Python:
Just another day in the world of Minecraft, Steve is getting ready to start his next exciting project -- building a railway system!

![Alt text](http://static.planetminecraft.com/files/resource_media/screenshot/1506/2015-02-02_0156508603066.jpg)

But first, Steve needs to melt some iron ores in the furnace to get the main building blocks of rails -- iron ingots. ![Alt text](http://www.blocksandgold.com/media/catalog/product/cache/3/image/35x/cbcbef48e5e3bcce7c7ed908f20bc5b4/i/r/ironingot_icon32.png)

Each iron ingot takes 11 seconds* to produce. Steve needs a lot of them, and he has the following fuel options to add into the furnace:

* Buckets of lava, each lasts 800 seconds* ![Alt text](http://www.minecraftguides.org/images/items/bucketL.gif)
* Blaze rod, each lasts 120 seconds ![Alt text](http://www.minecraftguides.org/images/items/blazerod.gif)
* Coals, each lasts 80 seconds ![Alt text](http://www.minecraftguides.org/images/items/coal.gif)
* Blocks of Wood, each lasts 15 seconds ![Alt text](http://www.minecraftguides.org/images/itemGifs/logs.gif)
* Sticks, each lasts 1 second* ![Alt text](http://www.minecraftguides.org/images/items/stick.gif)

In Ruby:
Write a function `calc_fuel` that calculates the **minimum** amount of fuel needed to produce a certain number of iron ingots. This function should return a hash of the form `{:lava => 2, :blaze_rod => 1, :coal => 1, :wood => 0, :stick => 0}`
In JavaScript:
Write a function `calcFuel` that calculates the **minimum** amount of fuel needed to produce a certain number of iron ingots. This function should return an object of the form `{lava: 2, blazeRod: 1, coal: 1, wood: 0, stick: 0}`
In Python:
Write a function `calc_fuel` that calculates the **minimum** amount of fuel needed to produce a certain number of iron ingots. This function should return a dictionary of the form `{"lava": 2, "blaze rod": 1, "coal": 1, "wood": 0, "stick": 0}`

---
*fictional values

To all the Minecraft players out there:
feel free to expand this series or let me know if you have...

def calc_fuel(n):
    result={}
    wholeTime=n*11
    result["lava"]=wholeTime//800
    wholeTime-=800*result["lava"]
    result["blaze rod"]=wholeTime//120
    wholeTime-=120*result["blaze rod"]
    result["coal"]=wholeTime//80
    wholeTime-=80*result["coal"]
    result["wood"]=wholeTime//15
    wholeTime-=15*result["wood"]
    result["stick"]=wholeTime//1
    return result


Solve in Python:
Just another day in the world of Minecraft, Steve is working on his new project -- building a beacon pyramid in front of his house.

![Beacon pyramid](http://www.minecraft101.net/reference/images/beacon_pyramid_thb.jpg)

Steve has already obtained the beacon (the glass wrapped blue thingy on the top), he just needs to build the pyramid. Each level of the pyramid is built using one of the following four kinds of block: gold, diamond, emerald, and iron. Since these four kinds of blocks are relatively hard to collect, Steve needs to know exactly how many of each kind is required to build a pyramid of level N.

Assume that the top level of the pyramid uses gold blocks, the second level uses diamond blocks, the third level uses emerald blocks, the fourth level uses iron blocks, and the fifth level uses gold blocks, etc. (if you are a Minecraft player, you know it's not neccessary the right way to build the pyramid. Let's just assume it is for the sake of this kata ;-))

Implement a function that takes one argument which is the number of levels of the pyramid, and returns an object of the form: `{total: 9, gold: 9, diamond: 0, emerald: 0, iron: 0}`.

---

To all the Minecraft players out there:
feel free to expand this series or let me know if you have any ideas related to Minecraft that can be turned into codewars puzzles. Some ideas I have that might potentially be turned into katas:

* distance traveled in real world vs. in Nether
* shortest path problems related to mining diamonds/gold/goodies that appears in different levels under ground
* growth of animal population from breeding
* redstone stuff?!

If you do end up expanding this series, please send me a link of your kata so I can check it out and include a link to your kata here :-)

* [Minecraft Series #2: Minimum amount of fuel needed to get some iron ingots](https://www.codewars.com/kata/minecraft-series-number-2-minimum-amount-of-fuel-needed-to-get-some-iron-ingots/ruby)
* [Minecraft Series #3: Lava is amazing!...


Solve in Python:
Just like in the ["father" kata](http://www.codewars.com/kata/find-fibonacci-last-digit/), you will have to return the last digit of the nth element in the Fibonacci sequence (starting with 1,1, to be extra clear, not with 0,1 or other numbers).

You will just get much bigger numbers, so good luck bruteforcing your way through it ;)
```python
last_fib_digit(1) == 1
last_fib_digit(2) == 1
last_fib_digit(3) == 2
last_fib_digit(1000) == 5
last_fib_digit(1000000) == 5
```
``` haskell
lastFibDigit       1 == 1
lastFibDigit       2 == 1
lastFibDigit       3 == 2
lastFibDigit    1000 == 5
lastFibDigit 1000000 == 5
```

def last_fib_digit(n):
    n = (n-1) % 60
    a, b = 1, 1
    for i in range(n):
        a, b = b, (a + b) % 10
    return a


Solve in Python:
Just to remind, girls in Arpa's land are really nice.

Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight w_{i} and some beauty b_{i}. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a_1, a_2, ..., a_{k} such that a_{i} and a_{i} + 1 are friends for each 1 ≤ i < k, and a_1 = x and a_{k} = y.

 [Image]

Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it.

Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w.

-----Input-----

The first line contains integers n, m and w (1  ≤  n  ≤  1000, $0 \leq m \leq \operatorname{min}(\frac{n \cdot(n - 1)}{2}, 10^{5})$, 1 ≤ w ≤ 1000) — the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited.

The second line contains n integers w_1, w_2, ..., w_{n} (1 ≤ w_{i} ≤ 1000) — the weights of the Hoses.

The third line contains n integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 10^6) — the beauties of the Hoses.

The next m lines contain pairs of friends, the i-th of them contains two integers x_{i} and y_{i} (1 ≤ x_{i}, y_{i} ≤ n, x_{i} ≠ y_{i}), meaning that Hoses x_{i} and y_{i} are friends. Note that friendship is bidirectional. All pairs (x_{i}, y_{i}) are distinct.

-----Output-----

Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w.

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

Output
6

Input
4 2 11
2 4 6 6
6 4 2 1
1 2
2...

f = lambda: list(map(int, input().split()))

n, m, w = f()

wb = [(0, 0)] + list(zip(f(), f()))

t = list(range(n + 1))

def g(x):

    if x == t[x]: return x

    t[x] = g(t[x])

    return t[x]

for i in range(m):

    x, y = f()

    x, y = g(x), g(y)

    if x != y: t[y] = x

p = [[] for j in range(n + 1)]

for i in range(1, n + 1): p[g(i)].append(i)

d = [1] + [0] * w

for q in p:

    if len(q) > 1:

        WB = [wb[i] for i in q]

        SW = sum(q[0] for q in WB)

        SB = sum(q[1] for q in WB)

        for D in range(w, -1, -1):

            if d[D]:

                if D + SW <= w: d[D + SW] = max(d[D + SW], d[D] + SB)

                for W, B in WB:

                    if D + W <= w: d[D + W] = max(d[D + W], d[D] + B)

    elif len(q) == 1:

        W, B = wb[q[0]]

        for D in range(w - W, -1, -1):

            if d[D]: d[D + W] = max(d[D + W], d[D] + B)

print(max(d) - 1)

# Made By Mostafa_Khaled


Solve in Python:
Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store.

Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group.

Jzzhu wonders how to get the maximum possible number of groups. Can you help him?

-----Input-----

A single integer n (1 ≤ n ≤ 10^5), the number of the apples.

-----Output-----

The first line must contain a single integer m, representing the maximum number of groups he can get. Each of the next m lines must contain two integers — the numbers of apples in the current group.

If there are several optimal answers you can print any of them.

-----Examples-----
Input
6

Output
2
6 3
2 4

Input
9

Output
3
9 3
2 4
6 8

Input
2

Output
0

"""
Codeforces Round 257 Div 1 Problem C

Author  : chaotic_iak
Language: Python 3.3.4
"""

def read(mode=2):
    # 0: String
    # 1: List of strings
    # 2: List of integers
    inputs = input().strip()
    if mode == 0:
        return inputs
    if mode == 1:
        return inputs.split()
    if mode == 2:
        return [int(x) for x in inputs.split()]

def write(s="\n"):
    if isinstance(s, list): s = " ".join(map(str,s))
    s = str(s)
    print(s, end="")

################################################### SOLUTION

# croft algorithm to generate primes
# from pyprimes library, not built-in, just google it
from itertools import compress
import itertools
def croft():
    """Yield prime integers using the Croft Spiral sieve.

    This is a variant of wheel factorisation modulo 30.
    """
    # Implementation is based on erat3 from here:
    #   http://stackoverflow.com/q/2211990
    # and this website:
    #   http://www.primesdemystified.com/
    # Memory usage increases roughly linearly with the number of primes seen.
    # dict ``roots`` stores an entry x:p for every prime p.
    for p in (2, 3, 5):
        yield p
    roots = {9: 3, 25: 5}  # Map d**2 -> d.
    primeroots = frozenset((1, 7, 11, 13, 17, 19, 23, 29))
    selectors = (1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0)
    for q in compress(
            # Iterate over prime candidates 7, 9, 11, 13, ...
            itertools.islice(itertools.count(7), 0, None, 2),
            # Mask out those that can't possibly be prime.
            itertools.cycle(selectors)
            ):
        # Using dict membership testing instead of pop gives a
        # 5-10% speedup over the first three million primes.
        if q in roots:
            p = roots[q]
            del roots[q]
            x = q + 2*p
            while x in roots or (x % 30) not in primeroots:
                x += 2*p
            roots[x] = p
        else:
            roots[q*q] = q
            yield q

n, = read()
cr = croft()
primes = []
for i in cr:
    if i < n:
       ...


Solve in Python:
Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city u_{i} to v_{i} (and vise versa) using the i-th road, the length of this road is x_{i}. Finally, there are k train routes in the country. One can use the i-th train route to go from capital of the country to city s_{i} (and vise versa), the length of this route is y_{i}.

Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change.

-----Input-----

The first line contains three integers n, m, k (2 ≤ n ≤ 10^5; 1 ≤ m ≤ 3·10^5; 1 ≤ k ≤ 10^5).

Each of the next m lines contains three integers u_{i}, v_{i}, x_{i} (1 ≤ u_{i}, v_{i} ≤ n; u_{i} ≠ v_{i}; 1 ≤ x_{i} ≤ 10^9).

Each of the next k lines contains two integers s_{i} and y_{i} (2 ≤ s_{i} ≤ n; 1 ≤ y_{i} ≤ 10^9).

It is guaranteed that there is at least one way from every city to the capital. Note, that there can be multiple roads between two cities. Also, there can be multiple routes going to the same city from the capital.

-----Output-----

Output a single integer representing the maximum number of the train routes which can be closed.

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

Output
2

Input
2 2 3
1 2 2
2 1 3
2 1
2 2
2 3

Output
2

#===============================================================================================
#importing some useful libraries.

from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from functools import cmp_to_key

# from itertools import *
from heapq import *
from math import gcd, factorial,floor,ceil,sqrt

from copy import deepcopy
from collections import deque

from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect

#==============================================================================================
#fast I/O region
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda:...


Solve in Python:
KISS stands for Keep It Simple Stupid.
It is a design principle for keeping things simple rather than complex.

You are the boss of Joe.

Joe is submitting words to you to publish to a blog. He likes to complicate things.

Define a function that determines if Joe's work is simple or complex.

Input will be non emtpy strings with no punctuation.

It is simple if:
``` the length of each word does not exceed the amount of words in the string ```
(See example test cases)

Otherwise it is complex.

If complex:
```python
return "Keep It Simple Stupid"
```
or if it was kept simple:
```python
return "Good work Joe!"
```

Note: Random test are random and nonsensical. Here is a silly example of a random test:
```python
"jump always mostly is touchy dancing choice is pineapples mostly"
```

def is_kiss(s):
    s = s.split()
    n = len(s)
    return "Good work Joe!" if all(len(x) <= n for x in s) else "Keep It Simple Stupid"


Solve in Python:
Kabir Singh is playing a game on the non-negative side of  x-axis. It takes him $1 second$ to reach from Pth position to (P−1)th position or (P+1)th position.
Kabir never goes to the negative side and also doesn't stop at any moment of time.
The movement can be defined as  :
- At the beginning he is at $x=0$ , at time $0$
- During the first round, he moves towards $x=1$ and comes back to the $x=0$ position.
- In the second round, he moves towards the $x=2$ and comes back again to $x=0$.
- So , at $Kth$ round , he moves to $x=K$ and comes back to $x=0$
So in this way game goes ahead.
For Example, the path of Kabir for $3rd$ round is given below.
$0−1−2−3−2−1−0$
The overall path followed by Kabir would look somewhat like this:
$0−1−0−1−2−1−0−1−2−3−2−1−0−1−2−3−4−3−…$
Now the task is , You are given Two Non-Negative integers $N$ , $K$ .
You have to tell the time at which Kabir arrives at $x=N$ for the $Kth$ time.
Note - Kabir visits all the points , he can not skip or jump over one point.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, two integers $N, K$.

-----Output:-----
For each testcase, output in a single line answer i.e Time Taken by Kabir Singh modulo 1000000007.

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

-----Sample Input:-----
4

0 1
1 1
1 3
4 6

-----Sample Output:-----
0
1
5
46

-----EXPLANATION:-----
Test Case 1:
Kabir starts the journey from the $N=0$ at time $t=0$ and it's the first time$ (K=1)$, he is here. So, the answer is $0$.
Test Case 3:
The path followed by Kabir to reach 1 for the third time is given below.
$0−1−0−1−2−1$
He reaches $1$ for the third time at $ t=5$.

# cook your dish here
"""
Created on Sat May 23 23:48:49 2020

@author: aurouS_EeRiE
"""

def solve(n, k):
    ans = 0
    if n == 0:
        if k == 1:
            return 0
        else:
            return ((k - 1) * (k)) % ((10 ** 9) + 7)
    if k == 1:
        return (n * n) % ((10 ** 9) + 7)
    if k % 2 == 0:
        ans = n * n + n * k + int(int((k - 1) / 2) * int((k - 1) / 2 + 1))
    if k % 2 != 0:
        ans = n * n + (2 * n) * (max(0, int((k - 1) / 2))) + int(int((k - 1) / 2) * int((k - 1) / 2 + 1))
    return ans % ((10 ** 9) + 7)

t = int(input())
for i in range(t):
    n, k=map(int, input().split())
    print(solve(n, k))


Solve in Python:
Kabir likes Tara's smile and wants to look at her smile. They are sitting in the class and you are friends with Kabir. You have to place a mirror (point size)  in the front wall of the class so that Kabir can have a glimpse of Tara's smile.
Consider the front wall as x-axis . You are given the  coordinates of position of Kabir (x1,y1)$(x1,y1)$ and Tara  (x2,y2)$(x2,y2)$. Find the position where the mirror should be placed.

-----Input:-----
- First line will contain T$T$, number of testcases. Then the testcases follow.
- First line of each testcase contains two integers x1,y1$x1, y1$.
- Second line of each testcase contains two integers x2,y2$x2, y2$.

-----Output:-----
For each testcase, print the x-coordinate of the mirror. Absolute error of 10−2$10^{−2}$ is allowed.

-----Constraints:-----
- 1≤T≤1000$1 \leq T \leq 1000$
- 1≤x1,y1,x2,y2≤105$1 \leq x1,y1,x2,y2 \leq 10^5 $

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

4 4

-----Sample Output:-----
1.60

# cook your dish here
t=int(input())
while(t>0):
    x1,y1=input().split()
    x2,y2=input().split()
    x1=int(x1)
    x2=int(x2)
    y1=int(y1)
    y2=int(y2)
    x=min(x1,x2)
    if x==x1:
        ans=(y1*(x2-x1))/(y1+y2)
        ans=x1+ans
    else:
        ans=(y2*(x1-x2))/(y1+y2)
        ans=x2+ans
    print('%.2f'%ans)

    t=t-1


Solve in Python:
Kabir wants to impress Tara by showing her his problem solving skills. He has decided to give the correct answer to the next question which will be asked by his Algorithms teacher.
The question asked is:
Find the sum of alternate consecutive d$d$ odd numbers from the range L$L$ to R$R$ inclusive.
if d$d$ is 3 and L$L$ is 10 and R$R$ is 34, then the odd numbers between 10 and 34 are 11,13,15,17,19,21,23,25,27,29,31,33$11,13,15,17,19,21,23,25,27,29,31,33$, and the d$d$ alternate odd numbers are 11,13,15,23,25,27$11,13,15,23,25,27$.
You are a friend of Kabir, help him solve the question.
Note:$Note:$ Number of odd number between L$L$ and R$R$ (both inclusive) is a multiple of d$d$.

-----Input:-----
- First line will contain T$T$, number of test cases.
- First line of each test case contains one integer d$d$ .
- Second line of each test case contains two space separated integer L$L$ and R$R$.

-----Output:-----
For each test case, print the sum modulo 1000000007.

-----Constraints:-----
- 1≤T≤106$1 \leq T \leq 10^6$
- 1≤d≤103$1 \leq d \leq 10^3$
- 1≤L<R≤106$1 \leq L < R \leq 10^6$

-----Sample Input:-----
1
3

10 33

-----Sample Output:-----
114

-----EXPLANATION:-----
Sum of alternate odd numbers i.e, 11,13,15,23,25,27 is 114

# cook your dish here
t=int(input())
while t>0 :
    d=int(input())
    l,r=map(int,input().split())
    if l%2==1 and r%2==1 :
        num=(r-l)//2+1
    elif l%2==1 or r%2==1 :
        num=(r-l+1)//2
    else :
        num=(r-l)//2
    if l%2==0 :
        l=l+1
    if(num%(2*d)==0) :
        n=num//(2*d)
    else :
        n=num//(2*d)+1
    init=l*d+ d*(d-1)
    su=n*init
    su=su+2*d*d*n*(n-1)
    print(su%1000000007)
    t=t-1


Solve in Python:
Kajaria has an empty bag and 2 types of tiles -
tiles of type $1$ have the number $X$ written and those of type $2$ have the number $Y$ written on them. He has an infinite supply of both type of tiles.
In one move, Kajaria adds exactly $1$ tile to the bag. He adds a tile of type $1$ with probability $p$ and a tile of type $2$ with probability $(1 - p)$.
If $2$ tiles in the bag have the same number written on them (say $Z$), they are merged into a single tile of twice that number ($2Z$).
Find the expected number of moves to reach the first tile with number $S$ written on it.
Notes on merging:
- Consider that the bag contains tiles $(5, 10, 20, 40)$ and if the new tile added is $5$, then it would merge with the existing $5$ and the bag would now contain $(10, 10, 20, 40)$. The tiles $10$ (already present) and $10$ (newly formed) would then merge in the same move to form $(20, 20, 40)$, and that will form $(40, 40)$, which will form $(80)$.
Kajaria guarantees that:
- $X$ and $Y$ are not divisible by each other.
- A tile with number $S$ can be formed.

-----Input-----
- First line contains a single integer $T$ - the total no. of testcases
- Each testcase is described by $2$ lines:
- $X, Y, S$ - $3$ space-separated natural numbers
- $u, v$ - $2$ space-separated natural numbers describing the probability $p$
The value of $p$ is provided as a fraction in its lowest form $u/v$ ($u$ and $v$ are co-prime)

-----Output-----
- For each testcase, if the expected number of moves can be expressed as a fraction $p/q$ in its lowest form, print $(p * q^{-1})$ modulo $10^9 + 7$, where $q^{-1}$ denotes the modular inverse of $q$ wrt $10^9 + 7$.

-----Constraints-----
- $1 \leq T \leq 10^5$
- $2 \leq X, Y \leq 5 * 10^{17}$
- $1 \leq S \leq 10^{18}$
- $1 \leq u < v \leq 10^{9}$

-----Sample Input-----
1
5 3 96
1 3

-----Sample Output-----
48

# cook your dish here
t=int(input())
MOD=1000000007
def mod(n, m=MOD):
 n%=m
 while n<0: n+=m
 return n

def power(n, p):
 res=1
 while p:
  if p%2: res=mod(res*n)
  p//=2
  n=mod(n*n)
 return res

while t:
 ma=input().split()
 x=int(ma[0])
 y=int(ma[1])
 s=int(ma[2])
 ma=input().split()
 u=int(ma[0])
 v=int(ma[1])
 if s%x==0 and ((s // x) & ((s // x) - 1) == 0):
  inv=power(u, MOD-2)
  print(mod(mod(mod(s//x)*v)*inv))
 else:
  inv=power(v-u, MOD-2)
  print(mod(mod(mod(s//y)*v)*inv))
 t-=1


Solve in Python:
Kalila and Dimna are two jackals living in a huge jungle. One day they decided to join a logging factory in order to make money.

The manager of logging factory wants them to go to the jungle and cut n trees with heights a_1, a_2, ..., a_{n}. They bought a chain saw from a shop. Each time they use the chain saw on the tree number i, they can decrease the height of this tree by one unit. Each time that Kalila and Dimna use the chain saw, they need to recharge it. Cost of charging depends on the id of the trees which have been cut completely (a tree is cut completely if its height equal to 0). If the maximum id of a tree which has been cut completely is i (the tree that have height a_{i} in the beginning), then the cost of charging the chain saw would be b_{i}. If no tree is cut completely, Kalila and Dimna cannot charge the chain saw. The chainsaw is charged in the beginning. We know that for each i < j, a_{i} < a_{j} and b_{i} > b_{j} and also b_{n} = 0 and a_1 = 1. Kalila and Dimna want to cut all the trees completely, with minimum cost.

They want you to help them! Will you?

-----Input-----

The first line of input contains an integer n (1 ≤ n ≤ 10^5). The second line of input contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9). The third line of input contains n integers b_1, b_2, ..., b_{n} (0 ≤ b_{i} ≤ 10^9).

It's guaranteed that a_1 = 1, b_{n} = 0, a_1 < a_2 < ... < a_{n} and b_1 > b_2 > ... > b_{n}.

-----Output-----

The only line of output must contain the minimum cost of cutting all the trees completely.

Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

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

Output
25

Input
6
1 2 3 10 20 30
6 5 4 3 2 0

Output
138

from collections import deque

class line:
    def __init__(self, k, b):
        self.k = k
        self.b = b

    def get(self, x):
        return self.k * x + self.b

def check(l1, l2, nl):
    return (nl.b - l2.b) * (l1.k - l2.k) - (nl.k - l2.k) * (l1.b - l2.b) <= 0

n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ans = 0

hull = deque()
hull.append(line(b[0], 0))
for i in range(1, n):
    arg = a[i]
    while len(hull) > 1 and hull[0].get(arg) >= hull[1].get(arg):
        hull.popleft()
    ans = hull[0].get(arg)
    nl = line(b[i], ans)
    while len(hull) > 1 and check(hull[-2], hull[-1], nl):
        hull.pop()
    hull.append(nl)

print(ans)


Solve in Python:
Karan's company makes software that provides different features based on the version of operating system of the user.

For finding which version is more recent, Karan uses the following method:

While this function worked for OS versions 10.6, 10.7, 10.8 and 10.9, the Operating system company just released OS version 10.10.

Karan's function fails for the new version:

```python
compare_versions ("10.9", "10.10");       # returns True, while it should return False
```

Karan now wants to spend some time to right a more robust version comparison function that works for any future version/sub-version updates.

Help Karan write this function. Here are a few sample cases:

```python
compare_versions("11", "10");                    # returns True
compare_versions("11", "11");                    # returns True
compare_versions("10.4.6", "10.4");              # returns True
compare_versions("10.4", "11");                  # returns False
compare_versions("10.4", "10.10");               # returns False
compare_versions("10.4.9", "10.5");              # returns False
```
```haskell
compareVersions "11" "10"       `shouldBe` GT
compareVersions "10.4.6" "10.4" `shouldBe` GT
compareVersions "10.10" "10.9"  `shouldBe` GT
compareVersions xs xs           `shouldBe` EQ -- xs is an arbitrary version
compareVersions "10" "11"         `shouldBe` LT
compareVersions "10.4" "10.4.6"   `shouldBe` LT
compareVersions "10.99" "10.100"  `shouldBe` LT
```

It can be assumed that version strings are non empty and only contain numeric literals and the character `'.'`.

def compare_versions(version1, version2):
    v1 = version1.split('.')
    v2 = version2.split('.')
    a = max(len(v1), len(v2))
    v1.append('0'*abs(len(v1) - a))
    v2.append('0'*abs(len(v2) - a))
    if v1[-1] == '':
        v1.pop(-1)
    if v2[-1] == '':
        v2.pop(-1)
    k = 0
    for i in v1:
        if int(i) < int(v2[k]):
            return False
        elif int(i) >= int(v2[k]):
            k += 1
    return True


Solve in Python:
Karen has just arrived at school, and she has a math test today! [Image]

The test is about basic addition and subtraction. Unfortunately, the teachers were too busy writing tasks for Codeforces rounds, and had no time to make an actual test. So, they just put one question in the test that is worth all the points.

There are n integers written on a row. Karen must alternately add and subtract each pair of adjacent integers, and write down the sums or differences on the next row. She must repeat this process on the values on the next row, and so on, until only one integer remains. The first operation should be addition.

Note that, if she ended the previous row by adding the integers, she should start the next row by subtracting, and vice versa.

The teachers will simply look at the last integer, and then if it is correct, Karen gets a perfect score, otherwise, she gets a zero for the test.

Karen has studied well for this test, but she is scared that she might make a mistake somewhere and it will cause her final answer to be wrong. If the process is followed, what number can she expect to be written on the last row?

Since this number can be quite large, output only the non-negative remainder after dividing it by 10^9 + 7.

-----Input-----

The first line of input contains a single integer n (1 ≤ n ≤ 200000), the number of numbers written on the first row.

The next line contains n integers. Specifically, the i-th one among these is a_{i} (1 ≤ a_{i} ≤ 10^9), the i-th number on the first row.

-----Output-----

Output a single integer on a line by itself, the number on the final row after performing the process above.

Since this number can be quite large, print only the non-negative remainder after dividing it by 10^9 + 7.

-----Examples-----
Input
5
3 6 9 12 15

Output
36

Input
4
3 7 5 2

Output
1000000006

-----Note-----

In the first test case, the numbers written on the first row are 3, 6, 9, 12 and 15.

Karen performs the operations as follows: [Image]

The non-negative remainder after dividing...

#!/usr/bin/env pypy3

import math

def make_nCr_mod(max_n=2*10**5 + 100, mod=10**9 + 7):
    fact, inv_fact = [0] * (max_n + 1), [0] * (max_n + 1)
    fact[0] = 1
    for i in range(max_n):
        fact[i + 1] = fact[i] * (i + 1) % mod

    inv_fact[-1] = pow(fact[-1], mod - 2, mod)
    for i in reversed(range(max_n)):
        inv_fact[i] = inv_fact[i + 1] * (i + 1) % mod

    def nCr_mod(n, r):
        res = 1
        while n or r:
            a, b = n % mod, r % mod
            if a < b:
                return 0
            res = res * fact[a] % mod * inv_fact[b] % mod * inv_fact[a - b] % mod
            n //= mod
            r //= mod
        return res

    return nCr_mod

nCr_mod = make_nCr_mod()

MODULUS = 10**9+7

input()
A = input().split(' ')
A = list(map(int, A))

if len(A) == 1:
    print(A[0])
    return

if len(A) % 2 == 1:
    new_A = []
    next_plus = True
    for i in range(len(A) - 1):
        if next_plus:
            new_A += [A[i] + A[i+1]]
        else:
            new_A += [A[i] - A[i+1]]
        next_plus = not next_plus
    A = new_A

if len(A) % 4 == 2:
    new_A = []
    for i in range(len(A) // 2):
        new_A += [A[2*i] + A[2*i+1]]
    A = new_A
else:
    new_A = []
    for i in range(len(A) // 2):
        new_A += [A[2*i] - A[2*i+1]]
    A = new_A

# binomial sum

N = len(A)-1

ret = 0

for i in range(N+1):
    ret += A[i]*nCr_mod(N, i)
    ret = ret % MODULUS

print(ret)


Solve in Python:
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $2n$ jars of strawberry and blueberry jam.

All the $2n$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $n$ jars to his left and $n$ jars to his right.

For example, the basement might look like this: [Image]

Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.

Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.

For example, this might be the result: [Image] He has eaten $1$ jar to his left and then $5$ jars to his right. There remained exactly $3$ full jars of both strawberry and blueberry jam.

Jars are numbered from $1$ to $2n$ from left to right, so Karlsson initially stands between jars $n$ and $n+1$.

What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?

Your program should answer $t$ independent test cases.

-----Input-----

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

The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$).

The second line of each test case contains $2n$ integers $a_1, a_2, \dots, a_{2n}$ ($1 \le a_i \le 2$) — $a_i=1$ means that the $i$-th jar from the left is a strawberry jam jar and $a_i=2$ means that it is a blueberry jam jar.

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

-----Output-----

For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.

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

q = int(input())
for rwier in range(q):
	n = int(input())
	l = list(map(int,input().split()))
	j = l.count(1)
	d = l.count(2)
	pr = [0] * n
	le = [0] * n
	pr[0] = (1 if l[n] == 1 else -1)
	le[0] = (1 if l[n-1] == 1 else -1)
	for i in range(1, n):
		pr[i] = pr[i-1] + (1 if l[n+i] == 1 else -1)
		le[i] = le[i-1] + (1 if l[n-i-1] == 1 else -1)
	#print(pr,le)
	if j - d < 0:
		for i in range(n):
			pr[i] = -pr[i]
			le[i] = -le[i]
	ab = abs(j-d)
	if ab == 0:
		print(0)
	else:
		#suma = abs
		najwp = [123456789] * (2*n+1)
		najwl = [123456789] * (2*n+1)
		le = [0] + le
		pr = [0] + pr
		for i in range(n+1):
			if pr[i] >= 0 and najwp[pr[i]] == 123456789:
				najwp[pr[i]] = i
			if le[i] >= 0 and najwl[le[i]] == 123456789:
				najwl[le[i]] = i
		wyn = 41343443143
		for i in range(ab+1):
			if najwp[i] + najwl[ab-i] < wyn:
				wyn = najwp[i] +najwl[ab-i]
		print(wyn)


Solve in Python:
Kate and Michael want to buy a pizza and share it. Depending on the price of the pizza, they are going to divide the costs:

* If the pizza is less than €5,- Michael invites Kate, so Michael pays the full price.
* Otherwise Kate will contribute 1/3 of the price, but no more than €10 (she's broke :-) and Michael pays the rest.

How much is Michael going to pay? Calculate the amount with two decimals, if necessary.

def michael_pays(costs):
    return round(costs, 2) if costs < 5 else round(max(costs-10, costs/3*2), 2)


Solve in Python:
Kate constantly finds herself in some kind of a maze. Help her to find a way out!.

For a given maze and Kate's position find if there is a way out. Your function should return True or False.

Each maze is defined as a list of strings, where each char stays for a single maze "cell". ' ' (space) can be stepped on, '#' means wall and 'k' stays for Kate's starting position. Note that the maze may not always be square or even rectangular.

Kate can move left, up, right or down only.

There should be only one Kate in a maze. In any other case you have to throw an exception.

Example input
=============
```
['# ##',
 '# k#',
 '####']
```

Example output
==============
True

Example input
=============
```
['####'.
 '# k#',
 '####']
```

Example output
==============
False

def has_exit(m):
    maze = [[x for x in row] for row in m]
    if not check_edge(maze):
        return False
    if not check_kate(maze):
        raise Exception("There should no be multiple Kates")

    kate = find_kate(maze)
    return find_way(maze, kate, kate)

def find_way(maze, position, previous_position, trace = []):
    if is_exit(maze, position):
        return True

    possible_ways = find_possible_ways(maze, position, previous_position)

    for possible_way in possible_ways:
        if possible_way not in trace:
            new_maze = move_kate(maze, possible_way, position)
            if find_way(new_maze, possible_way, position, trace + [possible_way]):
                return True

    return False

def find_possible_ways(maze, position, previous_position):
    r, c = position
    possible_ways = []
    for pr, pc in [(r+1, c), (r, c+1), (r-1, c), (r, c-1)]:
        if pr >= 0 and pr < len(maze) and pc >= 0 and pc < len(maze[0]):
            if maze[pr][pc] == ' ' and (pr, pc) != previous_position:
                possible_ways += [(pr, pc)]
    return possible_ways

def find_kate(maze):
    for r in range(len(maze)):
        for c in range(len(maze[0])):
            if maze[r][c] == 'k':
                return (r, c)

def move_kate(maze, new_position, previous_position):
    nr, nc = new_position
    pr, pc = previous_position
    new_m = maze[:pr] + [maze[pr][:pc] + [' '] + maze[pr][pc+1:]] + maze[pr+1:]
    return new_m[:nr] + [new_m[nr][:nc] + ['k'] + new_m[nr][nc+1:]] + new_m[nr+1:]

def check_edge(maze):
    edges = maze[0]+maze[-1]+tr(maze)[0]+tr(maze)[-1]
    if ' ' in edges or 'k' in edges:
        return True
    return False

def check_kate(maze):
    count = 0
    for r in range(len(maze)):
        for c in range(len(maze[0])):
            if maze[r][c] == 'k':
                count += 1
    return count == 1

def is_exit(maze, position):
    width, length = len(maze)-1, len(maze[0])-1
    if width in position or length in position or 0 in...


Solve in Python:
Kate likes to count words in text blocks. By words she means continuous sequences of English alphabetic characters (from a to z ). Here are examples:

`Hello there, little user5453 374 ())$. I’d been using my sphere as a stool. Slow-moving target 839342 was hit by OMGd-63 or K4mp.` contains "words" `['Hello', 'there', 'little', 'user', 'I', 'd', 'been', 'using', 'my','sphere', 'as', 'a', 'stool', 'Slow', 'moving', 'target', 'was', 'hit', 'by', 'OMGd', 'or', 'K', 'mp']`

Kate doesn't like some of words and doesn't count them. Words to be excluded are "a", "the", "on", "at", "of", "upon", "in" and "as", case-insensitive.

Today Kate's too lazy and have decided to teach her computer to count "words" for her.

Example Input 1
-------------
Hello there, little user5453 374 ())$.

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

Example Input 2
-------------

  I’d been using my sphere as a stool. I traced counterclockwise circles on it with my fingertips and it shrank until I could palm it. My bolt had shifted while I’d been sitting. I pulled it up and yanked the pleats straight as I careered around tables, chairs, globes, and slow-moving fraas. I passed under a stone arch into the Scriptorium. The place smelled richly of ink. Maybe it was because an ancient fraa and his two fids were copying out books there. But I wondered how long it would take to stop smelling that way if no one ever used it at all; a lot of ink had been spent there, and the wet smell of it must be deep into everything.

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

112

from re import sub
def word_count(s):
    alpha = sub("(^|\s)(a|the|on|at|of|in|as)(?=(\s|$))", ' ', sub("[^a-z]", ' ', s.lower().replace('æ', 'ae')))
    return len(alpha.split())


Solve in Python:
Kefaa has developed a novel decomposition of a tree. He claims that this decomposition solves many difficult problems related to trees. However, he doesn't know how to find it quickly, so he asks you to help him.
You are given a tree with $N$ vertices numbered $1$ through $N$. Let's denote an edge between vertices $u$ and $v$ by $(u, v)$. The triple-tree decomposition is a partition of edges of the tree into unordered triples of edges $(a, b), (a, c), (a, d)$ such that $a \neq b \neq c \neq d$. Each edge must belong to exactly one triple.
Help Kefaa with this problem — find a triple-tree decomposition of the given tree or determine that no such decomposition exists.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- Each of the following $N-1$ lines contains two space-separated integers $u$ and $v$ describing an edge between vertices $u$ and $v$ of the tree.

-----Output-----
- For each test case, print a line containing the string "YES" if a triple-tree decomposition of the given tree exists or "NO" otherwise.
- If it exists, print $\frac{N-1}{3}$ more lines describing a decomposition.
- Each of these lines should contain four space-separated integers $a$, $b$, $c$ and $d$ describing a triple of edges $(a, b), (a, c), (a, d)$.
If more than one triple-tree decomposition exists, you may output any one.

-----Constraints-----
- $1 \le T \le 100$
- $2 \le N \le 2 \cdot 10^5$
- $1 \le u, v \le N$
- the sum of $N$ over all test cases does not exceed $2 \cdot 10^5$

-----Subtasks-----
Subtask #1 (20 points): $2 \le N \le 10$
Subtask #2 (30 points):$2 \le N \le 5000$ and the sum of $N$ overall testcases doesn't exceed $5000$
Subtask #3 (50 points): original constraints

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

-----Example Output-----
YES
1 2 3 4
NO

test=int(input())
for t in range(test):
 n= int(input())

 adj=[[] for i in range(n+1)]

 for _ in range(n-1):
  a,b=list(map(int,input().split()))
  adj[a].append(b)
  adj[b].append(a)

 #print(adj)
 root=1
 q,s=[root],set([root])

 for x in q:
  adj[x]= [p for p in adj[x] if p not in s]
  q.extend(adj[x])
  s.update(adj[x])

 #print(adj)
 ans=True
 if(n<4):
  ans=False
 for i in range(n+1):
  if(len(adj[i]) %3!=0):
   ans=False
 if(ans):
  print("YES")
  for i in range(n+1):
   while(len(adj[i])):
    print(i,adj[i][0],adj[i][1],adj[i][2])
    adj[i].pop(0)
    adj[i].pop(0)
    adj[i].pop(0)
 else:
  print("NO")


Solve in Python:
Kevin is noticing his space run out! Write a function that removes the spaces from the values and returns an array showing the space decreasing.
For example, running this function on the array ['i', 'have','no','space'] would produce ['i','ihave','ihaveno','ihavenospace'].

from itertools import accumulate
def spacey(array):
    return list(accumulate(array))


Solve in Python:
Kim has broken in to the base, but after walking in circles, perplexed by the unintelligible base design of the JSA, he has found himself in a large, empty, and pure white, room.
The room is a grid with H∗W$H*W$ cells, divided into H$H$ rows and W$W$ columns. The cell (i,j)$(i,j)$ is at height A[i][j]$A[i][j]$. Unfortunately, his advanced sense of smell has allowed him to sense a mercury leak, probably brought in by Jishnu to end his meddling. The mercury leak has a power (which determines what height the mercury can reach before dissipating into harmless quantities) and a source cell. It spreads from cells it has already reached to other cells in the four cardinal directions: north, south, east, and west. (That is, the mercury can spread up, down, right, or left in the grid, but not diagonally.) Mercury can only spread to a cell if the cell's height is strictly less than the power value.
Unfortunately, Kim does not exactly know the starting cell or the power value of the mercury leak. However, his impressive brain has determined that it must be one of Q$Q$ (power, starting cell) combinations. For each combination, he wants to find out how many cells are dangerous for him to go to: that is, how many cells will eventually be reached by the mercury. This will help him determine a suitable cell to stay in and slowly fix the leak from above.
Can you help Kim achieve this objective?
Note: If the starting cell's height is not less than the power level, the mercury immediately dissipates. So, in this case, output 0.

-----Input:-----
- First line will contain T$T$, number of testcases. Then the testcases follow.
- The first line in each testcase contains three integers, H$H$, W$W$, and Q$Q$.
- On the 2$2$nd to (H+1)$(H+1)$th lines of each testcase: The (i+1)$(i+1)$th line contains W$W$ space-separated integers, representing the heights of the cells on the i$i$th row of the grid.
- On the (H+2)$(H+2)$th to (H+Q+1)$(H+Q+1)$th lines of each testcase: The (i+H+1)$(i+H+1)$th line contains 3 space-separated integers,...

# cook your dish here
def solve(l,r,c,row,col,po):
    count=0
    visited=set()
    stack=set()
    stack.add((l[row][col],row,col))
    while stack:
        ele=stack.pop()
        visited.add((ele[1],ele[2]))
        if ele[0]<po:
            count+=1
            if ele[1]-1>=0 and (ele[1]-1,ele[2]) not in visited:
                if l[ele[1]-1][ele[2]]<po:
                    stack.add((l[ele[1]-1][ele[2]],ele[1]-1,ele[2]))
            if ele[1]+1<r and (ele[1]+1,ele[2]) not in visited:
                if l[ele[1]+1][ele[2]]<po:
                    stack.add((l[ele[1]+1][ele[2]],ele[1]+1,ele[2]))
            if ele[2]-1>=0 and (ele[1],ele[2]-1) not in visited:
                if l[ele[1]][ele[2]-1]<po:
                    stack.add((l[ele[1]][ele[2]-1],ele[1],ele[2]-1))
            if ele[2]+1<c and (ele[1],ele[2]+1) not in visited:
                if l[ele[1]][ele[2]+1]<po:
                    stack.add((l[ele[1]][ele[2]+1],ele[1],ele[2]+1))
    return count
for _ in range(int(input())):
    r,c,q=map(int,input().split())
    l=[]
    for i in range(r):
        a=list(map(int,input().split()))
        l.append(a)
    for i in range(q):
        row,col,po=map(int,input().split())
        print(solve(l,r,c,row-1,col-1,po))


Solve in Python:
Kira likes to play with strings very much. Moreover he likes the shape of 'W' very much. He takes a string and try to make a 'W' shape out of it such that each angular point is a '#' character and each sides has same characters. He calls them W strings.
For example, the W string can be formed from "aaaaa#bb#cc#dddd" such as:
a
a             d
a     #     d
a   b c   d
a b   c d
#     #

He also call the strings which can generate a 'W' shape (satisfying the above conditions) W strings.
More formally, a string S is a W string if and only if it satisfies the following conditions (some terms and notations are explained in Note, please see it if you cannot understand):
- The string S contains exactly 3 '#' characters. Let the indexes of all '#' be P1 < P2 < P3 (indexes are 0-origin).
- Each substring of S[0, P1−1], S[P1+1, P2−1], S[P2+1, P3−1], S[P3+1, |S|−1] contains exactly one kind of characters, where S[a, b] denotes the non-empty substring from a+1th character to b+1th character, and |S| denotes the length of string S (See Note for details).
Now, his friend Ryuk gives him a string S and asks him to find the length of the longest W string which is a subsequence of S, with only one condition that there must not be any '#' symbols between the positions of the first and the second '#' symbol he chooses, nor between the second and the third (here the "positions" we are looking at are in S), i.e. suppose the index of the '#'s he chooses to make the W string are P1, P2, P3 (in increasing order) in the original string S, then there must be no index i such that S[i] = '#' where P1 < i < P2 or P2 < i < P3.
Help Kira and he won't write your name in the Death Note.
Note:
For a given string S, let S[k] denote the k+1th character of string S, and let the index of the character S[k] be k. Let |S| denote the length of the string S. And a substring of a string S is a string S[a, b] = S[a] S[a+1] ... S[b], where 0 ≤ a ≤ b < |S|. And a subsequence of a string S is a string S[i0] S[i1] ... S[in−1], where 0 ≤ i0 < i1 < ... <...

def frequency(s,n):
    f=[[0 for i in range(26)]for j in range(n+1)]
    count=0
    for i in range(n):
        if s[i]!="#":
            f[count][ord(s[i])-97]+=1
        else:
            count+=1
            for j in range(26):
                f[count][j]=f[count-1][j]
    return (f,count)

def solve(s):
    n=len(s)
    f,count=frequency(s,n)
    if count<3:
        return 0
    ans=0
    index=[]
    for i in range(n-1,-1,-1):
        if s[i]=="#":
            index.append(i)

    for c in range(1,count-2+1):
        if index[-2]==index[-1]+1 or index[-3]==index[-2]+1:
            index.pop()
            continue
        left=max(f[c-1])
        mid1=0
        mid2=0
        right=0
        for j in range(26):
            mid1=max(mid1,f[c][j]-f[c-1][j])
            mid2=max(mid2,f[c+1][j]-f[c][j])
            right=max(right,f[count][j]-f[c+1][j])
        if left and mid1 and mid2 and right:
            ans=max(ans,left+mid1+mid2+right)
        index.pop()
    return ans

for _ in range(int(input())):
    s=input()
    ans=solve(s)
    if ans:
        print(ans+3)
    else:
        print(0)


Solve in Python:
Koa the Koala and her best friend want to play a game.

The game starts with an array $a$ of length $n$ consisting of non-negative integers. Koa and her best friend move in turns and each have initially a score equal to $0$. Koa starts.

Let's describe a move in the game:  During his move, a player chooses any element of the array and removes it from this array, xor-ing it with the current score of the player.

 More formally: if the current score of the player is $x$ and the chosen element is $y$, his new score will be $x \oplus y$. Here $\oplus$ denotes bitwise XOR operation.

 Note that after a move element $y$ is removed from $a$.

  The game ends when the array is empty.

At the end of the game the winner is the player with the maximum score. If both players have the same score then it's a draw.

If both players play optimally find out whether Koa will win, lose or draw the game.

-----Input-----

Each test contains multiple test cases. The first line contains $t$ ($1 \le t \le 10^4$) — the number of test cases. Description of the test cases follows.

The first line of each test case contains the integer $n$ ($1 \le n \le 10^5$) — the length of $a$.

The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$) — elements of $a$.

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

-----Output-----

For each test case print:  WIN if Koa will win the game.  LOSE if Koa will lose the game.  DRAW if the game ends in a draw.

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

Output
WIN
LOSE
DRAW

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

Output
WIN
WIN
DRAW
WIN

-----Note-----

In testcase $1$ of the first sample we have:

$a = [1, 2, 2]$. Here Koa chooses $1$, other player has to choose $2$, Koa chooses another $2$. Score for Koa is $1 \oplus 2 = 3$ and score for other player is $2$ so Koa wins.

def solve():
    n = int(input())
    a = list(map(int, input().split()))
    for i in range(31, -1, -1):
        k = 1 << i
        u, v = 0, 0
        for j in a:
            if j & k:
                u += 1
            else:
                v += 1
        if v % 2 == 1:
            if u % 2 == 1:
                print('WIN')
                return
        else:
            if u % 4 == 1:
                print('WIN')
                return
            elif u % 4 == 3:
                print('LOSE')
                return
    print('DRAW')

t = int(input())
for _ in range(t):
    solve()


Solve in Python:
Koa the Koala has a binary string $s$ of length $n$. Koa can perform no more than $n-1$ (possibly zero) operations of the following form:

In one operation Koa selects positions $i$ and $i+1$ for some $i$ with $1 \le i < |s|$ and sets $s_i$ to $max(s_i, s_{i+1})$. Then Koa deletes position $i+1$ from $s$ (after the removal, the remaining parts are concatenated).

Note that after every operation the length of $s$ decreases by $1$.

How many different binary strings can Koa obtain by doing no more than $n-1$ (possibly zero) operations modulo $10^9+7$ ($1000000007$)?

-----Input-----

The only line of input contains binary string $s$ ($1 \le |s| \le 10^6$). For all $i$ ($1 \le i \le |s|$) $s_i = 0$ or $s_i = 1$.

-----Output-----

On a single line print the answer to the problem modulo $10^9+7$ ($1000000007$).

-----Examples-----
Input
000

Output
3

Input
0101

Output
6

Input
0001111

Output
16

Input
00101100011100

Output
477

-----Note-----

In the first sample Koa can obtain binary strings: $0$, $00$ and $000$.

In the second sample Koa can obtain binary strings: $1$, $01$, $11$, $011$, $101$ and $0101$. For example:  to obtain $01$ from $0101$ Koa can operate as follows: $0101 \rightarrow 0(10)1 \rightarrow 011 \rightarrow 0(11) \rightarrow 01$.  to obtain $11$ from $0101$ Koa can operate as follows: $0101 \rightarrow (01)01 \rightarrow 101 \rightarrow 1(01) \rightarrow 11$.

Parentheses denote the two positions Koa selected in each operation.

MOD = 1000000007
def main():
    s = input()
    n = len(s)
    zero = [0] * n
    for i in range(n):
        if s[i] == '0':
            zero[i] = zero[i-1] + 1 if i else 1
    nxt, dp = [0] * (n+2), [0] * (n+2)
    for i in range(n+1):
        nxt[i] = n
    for i in range(n-1, -1, -1):
        dp[i] = ((zero[i] <= zero[n-1]) + dp[nxt[0]] + dp[nxt[zero[i] + 1]]) % MOD
        nxt[zero[i]] = i
    ans = n if nxt[0] >= n else dp[nxt[0]] * (nxt[0] + 1) % MOD
    print(ans)

main()


Solve in Python:
Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours.
Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour.
Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back.
Return the minimum integer K such that she can eat all the bananas within H hours.

Example 1:
Input: piles = [3,6,7,11], H = 8
Output: 4
Example 2:
Input: piles = [30,11,23,4,20], H = 5
Output: 30
Example 3:
Input: piles = [30,11,23,4,20], H = 6
Output: 23

Constraints:

1 <= piles.length <= 10^4
piles.length <= H <= 10^9
1 <= piles[i] <= 10^9

class Solution:
    def minEatingSpeed(self, piles: List[int], H: int) -> int:
        min_speed = 1
        max_speed = max(piles)
        while min_speed <=max_speed :
            pivot = min_speed + (max_speed - min_speed)//2
            r = sum([math.ceil(x/pivot) for x in piles])
            #r=sum(hours)
            if r == H:
                return pivot
            elif min_speed==max_speed and r>=H:
                return pivot+1
            elif r < H:
                max_speed = pivot-1
            elif r > H:
                min_speed = pivot+1

        return pivot


Solve in Python:
Konrad is a Human Relations consultant working for VoltModder, a large electrical equipment producer. Today, he has been tasked with evaluating the level of happiness in the company.

There are $n$ people working for VoltModder, numbered from $1$ to $n$. Each employee earns a different amount of money in the company — initially, the $i$-th person earns $i$ rubles per day.

On each of $q$ following days, the salaries will be revised. At the end of the $i$-th day, employee $v_i$ will start earning $n+i$ rubles per day and will become the best-paid person in the company. The employee will keep his new salary until it gets revised again.

Some pairs of people don't like each other. This creates a great psychological danger in the company. Formally, if two people $a$ and $b$ dislike each other and $a$ earns more money than $b$, employee $a$ will brag about this to $b$. A dangerous triple is a triple of three employees $a$, $b$ and $c$, such that $a$ brags to $b$, who in turn brags to $c$. If $a$ dislikes $b$, then $b$ dislikes $a$.

At the beginning of each day, Konrad needs to evaluate the number of dangerous triples in the company. Can you help him do it?

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n \le 100\,000$, $0 \le m \le 100\,000$) — the number of employees in the company and the number of pairs of people who don't like each other. Each of the following $m$ lines contains two integers $a_i$, $b_i$ ($1 \le a_i, b_i \le n$, $a_i \neq b_i$) denoting that employees $a_i$ and $b_i$ hate each other (that is, $a_i$ dislikes $b_i$ and $b_i$ dislikes $a_i$). Each such relationship will be mentioned exactly once.

The next line contains an integer $q$ ($0 \le q \le 100\,000$) — the number of salary revisions. The $i$-th of the following $q$ lines contains a single integer $v_i$ ($1 \le v_i \le n$) denoting that at the end of the $i$-th day, employee $v_i$ will earn the most.

-----Output-----

Output $q + 1$ integers. The $i$-th of them should contain the number of dangerous triples...

n, m = map(int, input().split())
out, inp =[0]*(n+1), [0]*(n+1)
inset = [[] for i in range(n+1)]

for i in range(m):
    x, y = map(int, input().split())

    if x > y:
        z = x
        x = y
        y = z

    out[y] += 1
    inp[x] += 1
    inset[x].append(y)

q = int(input())

res = 0
for ind in range(1, n+1):
    res += inp[ind] * out[ind]

print(res)
for i in range(q):
    best = int(input())

    res -= out[best] * inp[best]
    for pred_ind in inset[best]:
        res += -out[pred_ind] * inp[pred_ind] + ((out[pred_ind] - 1) * (inp[pred_ind] + 1))
        out[pred_ind] -= 1
        inp[pred_ind] += 1
        inset[pred_ind].append(best)

    out[best] += inp[best]
    inp[best] = 0
    inset[best] = []

    print(res)


Solve in Python:
Kontti language is a finnish word play game.

You add `-kontti` to the end of each word and then swap their characters until and including the first vowel ("aeiouy");

For example the word `tame` becomes `kome-tantti`; `fruity` becomes `koity-fruntti` and so on.

If no vowel is present, the word stays the same.

Write a string method that turns a sentence into kontti language!

def kontti(stg):
    return " ".join(k_w(word) for word in stg.split())

def k_w(stg):
    i = next((i for i, c in enumerate(stg.lower()) if c in "aeiouy"), -1)
    return f"ko{stg[i+1:]}-{stg[:i+1]}ntti" if i > -1 else stg


Solve in Python:
Kostya likes the number 4 much. Of course! This number has such a lot of properties, like:

- Four is the smallest composite number;
- It is also the smallest Smith number;
- The smallest non-cyclic group has four elements;
- Four is the maximal degree of the equation that can be solved in radicals;
- There is four-color theorem that states that any map can be colored in no more than four colors in such a way that no two adjacent regions are colored in the same color;
- Lagrange's four-square theorem states that every positive integer can be written as the sum of at most four square numbers;
- Four is the maximum number of dimensions of a real division algebra;
- In bases 6 and 12, 4 is a 1-automorphic number;
- And there are a lot more cool stuff about this number!

Impressed by the power of this number, Kostya has begun to look for occurrences of four anywhere. He has a list of T integers, for each of them he wants to calculate the number of occurrences of the digit 4 in the decimal representation. He is too busy now, so please help him.

-----Input-----
The first line of input consists of a single integer T, denoting the number of integers in Kostya's list.
Then, there are T lines, each of them contain a single integer from the list.

-----Output-----
Output T lines. Each of these lines should contain the number of occurences of the digit 4 in the respective integer from Kostya's list.

-----Constraints-----
- 1 ≤ T ≤ 105
- (Subtask 1): 0 ≤ Numbers from the list  ≤ 9 - 33 points.
- (Subtask 2): 0 ≤ Numbers from the list  ≤ 109 - 67 points.

-----Example-----
Input:
5
447474
228
6664
40
81

Output:
4
0
1
1
0

a=str(4)
for _ in range(int(input())):
    n=str(input())
    count=0
    for i in n:
        if i==a:
            count+=1
    print(count)


Solve in Python:
Kshitij has recently started solving problems on codechef. As he is real problem solving enthusiast, he wants continuous growth in number of problems solved per day.
He started with $a$  problems on first day.
He solves $d$ problems more than previous day. But after every $k$ days , he increases $d$ by
$inc$ .
Can you guess how many questions he will solve on $nth $ day ?

-----Input:-----
- First line  contains $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input,five integers $a, d, k, n, inc$.

-----Output:-----
For each testcase, output in a single line number of questions solved on $nth$ day.

-----Constraints-----
- $1 \leq T \leq 15$
- $1 \leq a \leq 99$
- $1 \leq d \leq 100$
- $1 \leq n \leq 10000$
- $1 \leq k \leq n$
- $0 \leq inc \leq 99$

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

-----Sample Output:-----
43

-----EXPLANATION:-----
The number of questions solved in first 8 days is :
$1$ $5$ $9$ $15$ $21$ $27$ $35$ $43$ .
On first day he solved 1 problem . Here $d$ is  4 for first 3 days.
Then after 3 days $d$ increases by 2 (that is 6).

import sys,math,collections
from collections import defaultdict

#from itertools import permutations,combinations

def file():
    sys.stdin = open('input.py', 'r')
    sys.stdout = open('output.py', 'w')
def get_array():
    l=list(map(int, input().split()))
    return l
def get_ints():
    return map(int, input().split())
    #return a,b
def get_3_ints():
    a,b,c=map(int, input().split())
    return a,b,c
def sod(n):
    n,c=str(n),0
    for i in n:
        c+=int(i)
    return c
def isPrime(n):
    if (n <= 1):
        return False
    if (n <= 3):
        return True
    if (n % 2 == 0 or n % 3 == 0):
        return False
    i = 5
    while(i * i <= n):
        if (n % i == 0 or n % (i + 2) == 0):
            return False
        i = i + 6

    return True
def getFloor(A, x):

    (left, right) = (0, len(A) - 1)

    floor = -1
    while left <= right:
        mid = (left + right) // 2
        if A[mid] == x:
            return A[mid]
        elif x < A[mid]:
            right = mid - 1
        else:
            floor = A[mid]
            left = mid + 1

    return floor
def chk(aa,bb):
	f=0
	for i in aa:
		for j in bb:
			if(j[0]>=i[0] and j[1]<=i[1]):
				f+=1
			elif(j[0]<=i[0] and j[1]>=i[1]):
				f+=1
			elif(i[0]==j[1] or i[1]==j[0]):
				f+=1
			else:
				continue
	return f

#file()
def main():
	for tt in range(int(input())):
		a,d,k,n,inc=get_ints()
		j=1
		for i in range(n-1):
			if(j==k):
				d+=inc
				j=1
			else:
				j+=1
			a=a+d
		print(a)

           ...


Solve in Python:
Kuroni has $n$ daughters. As gifts for them, he bought $n$ necklaces and $n$ bracelets:  the $i$-th necklace has a brightness $a_i$, where all the $a_i$ are pairwise distinct (i.e. all $a_i$ are different),  the $i$-th bracelet has a brightness $b_i$, where all the $b_i$ are pairwise distinct (i.e. all $b_i$ are different).

Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the $i$-th daughter receives a necklace with brightness $x_i$ and a bracelet with brightness $y_i$, then the sums $x_i + y_i$ should be pairwise distinct. Help Kuroni to distribute the gifts.

For example, if the brightnesses are $a = [1, 7, 5]$ and $b = [6, 1, 2]$, then we may distribute the gifts as follows:  Give the third necklace and the first bracelet to the first daughter, for a total brightness of $a_3 + b_1 = 11$. Give the first necklace and the third bracelet to the second daughter, for a total brightness of $a_1 + b_3 = 3$. Give the second necklace and the second bracelet to the third daughter, for a total brightness of $a_2 + b_2 = 8$.

Here is an example of an invalid distribution:   Give the first necklace and the first bracelet to the first daughter, for a total brightness of $a_1 + b_1 = 7$. Give the second necklace and the second bracelet to the second daughter, for a total brightness of $a_2 + b_2 = 8$. Give the third necklace and the third bracelet to the third daughter, for a total brightness of $a_3 + b_3 = 7$.

This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!

-----Input-----

The input consists of multiple test cases. The first line contains an integer $t$ ($1 \le t \le 100$)  — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer $n$ ($1 \le n \le...

import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__

def solve():
    n = int(input())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    a.sort()
    b.sort()
    print(*a)
    print(*b)

t = int(input())
for i in range(t):
    solve()


Solve in Python:
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.

-----Input-----

The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors.

Then, k lines will follow. The i-th line will contain c_{i}, the number of balls of the i-th color (1 ≤ c_{i} ≤ 1000).

The total number of balls doesn't exceed 1000.

-----Output-----

A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.

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

Output
3

Input
4
1
2
3
4

Output
1680

-----Note-----

In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are:

1 2 1 2 3

1 1 2 2 3

2 1 1 2 3

k = int(input())

h = []

for i in range(k):
    h.append(int(input()))

ffs = [1]
def f(n):
    if n < len(ffs):
        return ffs[n]
    v = n * f(n-1)
    ffs.append(v)
    return v

def c(k, n):
    return f(n) // (f(k) * f(n-k))

def cc(k, n):
    return c(n-1, n + k-1)

def solve(h):
    if len(h) == 1:
        return 1

    hh = h[:-1]
    hh_len = sum(hh)

    return solve(hh) * cc(h[-1] -1, hh_len + 1)

r = 1
for i in range(len(h)):
    r *= cc(h[i] -1, sum(h[:i]) + 1)

print(r % 1000000007)


Solve in Python:
Late last night in the Tanner household, ALF was repairing his spaceship so he might get back to Melmac. Unfortunately for him, he forgot to put on the parking brake, and the spaceship took off during repair. Now it's hovering in space.

ALF has the technology to bring the spaceship home if he can lock on to its location.

Given a map:

````
..........
..........
..........
.......X..
..........
..........
````

The map will be given in the form of a string with \n separating new lines. The bottom left of the map is [0, 0]. X is ALF's spaceship.

In this example:

If you cannot find the spaceship, the result should be

```
"Spaceship lost forever."
```

Can you help ALF?

Check out my other 80's Kids Katas:

80's Kids #1: How Many Licks Does It Take
80's Kids #2: Help Alf Find His Spaceship
80's Kids #3: Punky Brewster's Socks
80's Kids #4: Legends of the Hidden Temple
80's Kids #5: You Can't Do That on Television
80's Kids #6: Rock 'Em, Sock 'Em Robots
80's Kids #7: She's a Small Wonder
80's Kids #8: The Secret World of Alex Mack
80's Kids #9: Down in Fraggle Rock
80's Kids #10: Captain Planet

def find_spaceship(astromap):
    lines = astromap.splitlines()
    for y, line in enumerate(lines):
        x = line.find('X')
        if x != -1:
            return [x, len(lines) - 1 - y]
    return 'Spaceship lost forever.'