Solve in Python:
Mr. X stays in a mansion whose door opens in the North. He travels every morning to meet his friend Ms. Y walking a predefined path.

To cut the distance short, one day he decides to construct a skywalk from his place to his friend’s place. Help him to find the shortest distance between the two residences.

-----Input-----

The first line contains a single positive integer T <= 100, the number of test cases. T test cases follow. The only line of each test case contains a string which is the path from X to Y. The integer value represents the distance. The character R or L represents a Right or a Left respectively.

-----Output-----

For each test case, output a single line containing the minimum distance and the direction(N,S,W,E,NE,NW,SE,SW) of Y’s residence with respect to X’s residence. The output distance should have only 1 decimal place with no approximation. Print “0.0” if X’s and Y’s residence coincide.

-----Example-----
Input:
1
2 L 2 R 2 L 1

Output:
5.0NW

Explanation
Mr. X travels 2units and then takes a Left, and then he travels 2units and takes a Right, then after travelling 2units he takes a Left and finally travels 1unit to reach Y’s residence.
(Unlike Input, Output does not have spaces between the distance and direction)

#Program question at: http://www.codechef.com/COZL2012/problems/RBX12R01
import math,sys
dir_ = 'UDLR'
left = 'LRDU'
right = 'RLUD'

t = int(input())
while t>0:
 t -= 1
 x=0; y=0;
 dr = ''; cur='U';
 s = input().split()
 l = len(s)
 for i in range(l):
  if i % 2 == 1:
   dr = s[i]
   if dr == 'L': cur = left[dir_.find(cur)]
   else: cur = right[dir_.find(cur)]
  else:
   steps = int(s[i])
   if cur == 'U': y += steps
   elif cur == 'D': y -= steps
   elif cur == 'L': x -= steps
   elif cur == 'R': x += steps

 dist = str(math.sqrt(x*x + y*y))
 i = dist.find('.')
 sys.stdout.write(dist[0:i+2])
 if x==0:
  sys.stdout.write( ('N' if y>0 else 'S') + '\n')
 elif y==0:
  sys.stdout.write( ('E' if x>0 else 'W') + '\n')
 elif x>0:
  sys.stdout.write( ('NE' if y>0 else 'SE') + '\n')
 elif x<0:
   sys.stdout.write( ('NW' if y>0 else 'SW') + '\n')


Solve in Python:
Mrs Jefferson is a great teacher. One of her strategies that helped her to reach astonishing results in the learning process is to have some fun with her students. At school, she wants to make an arrangement of her class to play a certain game with her pupils. For that, she needs to create the arrangement with **the minimum amount of groups that have consecutive sizes**.

Let's see. She has      ```14``` students. After trying a bit she could do the needed arrangement:
        ```[5, 4, 3, 2]```
- one group of  ```5``` students
- another group of      ```4``` students
- then, another one of  ```3```
- and finally, the smallest group of    ```2``` students.

As the game was a success, she was asked to help to the other classes to teach and show the game. That's why she desperately needs some help to make this required arrangements that make her spend a lot of time.

To make things worse, she found out that there are some classes with some special number of students that is impossible to get that arrangement.

Please, help this teacher!

Your code will receive the number of students of the class. It should output the arrangement as an array with the consecutive sizes of the groups in decreasing order.

For the special case that no arrangement of the required feature is possible the code should output     ```[-1] ```

The value of n is unknown and may be pretty high because some classes joined to to have fun with the game.

You may see more example tests in the Example Tests Cases Box.

def shortest_arrang(n):
    a = n // 2
    b = a + 1

    while a:
        total = sum(range(a, b+1))
        if total == n:
            return list(range(b, a-1, -1))

        if total > n:
            b -= 1
            a = b-1
        else:
            a -= 1
    else:
        return [-1]


Solve in Python:
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!

The only thing Mrs. Smith remembered was that any permutation of $n$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.

The sequence of $n$ integers is called a permutation if it contains all integers from $1$ to $n$ exactly once.

The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS).

A subsequence $a_{i_1}, a_{i_2}, \ldots, a_{i_k}$ where $1\leq i_1 < i_2 < \ldots < i_k\leq n$ is called increasing if $a_{i_1} < a_{i_2} < a_{i_3} < \ldots < a_{i_k}$. If $a_{i_1} > a_{i_2} > a_{i_3} > \ldots > a_{i_k}$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.

For example, if there is a permutation $[6, 4, 1, 7, 2, 3, 5]$, LIS of this permutation will be $[1, 2, 3, 5]$, so the length of LIS is equal to $4$. LDS can be $[6, 4, 1]$, $[6, 4, 2]$, or $[6, 4, 3]$, so the length of LDS is $3$.

Note, the lengths of LIS and LDS can be different.

So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.

-----Input-----

The only line contains one integer $n$ ($1 \le n \le 10^5$) — the length of permutation that you need to build.

-----Output-----

Print a permutation that gives a minimum sum of lengths of LIS and LDS.

If there are multiple answers, print any.

-----Examples-----
Input
4

Output
3 4 1 2

Input
2

Output
2 1

-----Note-----

In the first sample, you can build a permutation $[3, 4, 1, 2]$. LIS is $[3, 4]$ (or $[1, 2]$), so the length of LIS is equal to $2$. LDS can be ony of $[3, 1]$, $[4, 2]$, $[3, 2]$, or $[4, 1]$. The length of LDS is also equal to $2$. The sum is equal to $4$. Note that $[3, 4, 1, 2]$ is not the only permutation that is valid.

In the second sample,...

from math import sqrt
n = int(input())
k = int(sqrt(n))
b = []
last = 0
while last < n:
    b.append([last + j for j in range(k)])
    last = b[-1][-1] + 1
k = len(b)
for i in range(k - 1, -1, -1):
    for j in b[i]:
        if j < n:
            print(1 + j, end=' ')
print()


Solve in Python:
Ms. E.T. came from planet Hex. She has 8 fingers in each hand which makes her count in hexadecimal way. When she meets you, she tells you that she came from 7E light years from the planet Earth. You see she means that it is 126 light years far away and she is telling you the numbers in hexadecimal. Now, you are in trouble to understand what those numbers really mean. Therefore, you have to convert the hexadecimal numbers to decimals.

Input:

First line of code contain T test cases.

every line of text case contain a Hex-value

Output:

Every line of output contain a decimal conversion of given nunmber

Sample Input:

3

A

1A23

2C2A

Sample Output:

10

6691

11306


Solve in Python:
Much cooler than your run-of-the-mill Fibonacci numbers, the Triple Shiftian are so defined: `T[n] = 4 * T[n-1] - 5 * T[n-2] + 3 * T[n-3]`.

You are asked to create a function which accept a base with the first 3 numbers and then returns the nth element.
```python
triple_shiftian([1,1,1],25) == 1219856746
triple_shiftian([1,2,3],25) == 2052198929
triple_shiftian([6,7,2],25) == -2575238999
triple_shiftian([3,2,1],35) == 23471258855679
triple_shiftian([1,9,2],2) ==  2
```
*Note: this is meant to be an interview quiz, so the description is scarce in detail on purpose*

Special thanks to the [first person I met in person here in London just because of CW](http://www.codewars.com/users/webtechalex) and that assisted me during the creation of this kata ;)

def triple_shiftian(base,n):
  a, b, c = base
  i = 0
  while (i < n):
    a, b, c = b, c, 4 * c - 5 * b + 3 * a
    i += 1
  return a


Solve in Python:
Mutation is a genetic operator used to maintain genetic diversity from one generation of a population of genetic algorithm chromosomes to the next.

![Mutation](http://i.imgur.com/HngmxNN.gif)

A mutation here may happen on zero or more positions in a chromosome. It is going to check every position and by a given probability it will decide if a mutation will occur.

A mutation is the change from `0` to `1` or from `1` to `0`.

***Note:*** *Some tests are random. If you think your algorithm is correct but the result fails, trying again should work.*

# See other katas from this series

  - [Genetic Algorithm Series - #1 Generate](http://www.codewars.com/kata/genetic-algorithm-series-number-1-generate)
  - **Genetic Algorithm Series - #2 Mutation**
  - [Genetic Algorithm Series - #3 Crossover](http://www.codewars.com/kata/genetic-algorithm-series-number-3-crossover)
  - [Genetic Algorithm Series - #4 Get population and fitnesses](http://www.codewars.com/kata/genetic-algorithm-series-number-4-get-population-and-fitnesses)
  - [Genetic Algorithm Series - #5 Roulette wheel selection](http://www.codewars.com/kata/genetic-algorithm-series-number-5-roulette-wheel-selection)

from random import random
def mutate(ch, p):
    return ''.join([str(1-int(i)) if random()<=p else i for i in ch])


Solve in Python:
Mutual Recursion allows us to take the fun of regular recursion (where a function calls itself until a terminating condition) and apply it to multiple functions calling each other!

Let's use the Hofstadter Female and Male sequences to demonstrate this technique. You'll want to create two functions `F` and `M` such that the following equations are true:

```
F(0) = 1
M(0) = 0
F(n) = n - M(F(n - 1))
M(n) = n - F(M(n - 1))
```

Don't worry about negative numbers, `n` will always be greater than or equal to zero.

~~~if:php,csharp
You *do* have to worry about performance though, mutual recursion uses up a lot of stack space (and is highly inefficient) so you may have to find a way to make your solution consume less stack space (and time).  Good luck :)
~~~

Hofstadter Wikipedia Reference http://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Female_and_Male_sequences

def f(n):
    if n: return n - m(f(n-1))
    return 1

def m(n):
    if n: return n - f(m(n-1))
    return 0


Solve in Python:
My 5th kata, and 1st in a planned series of rock climbing themed katas.

In rock climbing ([bouldering](https://en.wikipedia.org/wiki/Bouldering) specifically), the V/Vermin (USA) climbing grades start at `'VB'` (the easiest grade), and then go `'V0'`, `'V0+'`, `'V1'`, `'V2'`, `'V3'`, `'V4'`, `'V5'` etc. up to `'V17'` (the hardest grade). You will be given a `list` (`lst`) of climbing grades and you have to write a function (`sort_grades`) to `return` a `list` of the grades sorted easiest to hardest.

If the input is an empty `list`, `return` an empty `list`; otherwise the input will always be a valid `list` of one or more grades.

Please do vote, rank, and provide any feedback on the kata.

def sort_grades(lst):
    grades = ['VB', 'V0', 'V0+'] + ['V' + str(i) for i in range(1, 18)]
    return [i for i in grades if i in lst]


Solve in Python:
My friend John and I are members of the "Fat to Fit Club (FFC)". John is worried because
each month a list with the weights of members is published and each month he is the last on the list
which means he is the heaviest.

I am the one who establishes the list so I told him:
"Don't worry any more, I will modify the order of the list".
It was decided to attribute a "weight" to numbers. The weight of a number will be from now on
the sum of its digits.

For example `99` will have "weight" `18`, `100` will have "weight"
`1` so in the list `100` will come before `99`.
Given a string with the weights of FFC members in normal order can you give this string ordered by "weights" of these numbers?

# Example:

`"56 65 74 100 99 68 86 180 90"` ordered by numbers weights becomes:
`"100 180 90 56 65 74 68 86 99"`

When two numbers have the same "weight", let us class them as if they were strings (alphabetical ordering) and not numbers:
`100` is before `180` because its "weight" (1) is less than the one of `180` (9)
and `180` is before `90` since, having the same "weight" (9),  it comes before as a *string*.

All numbers in the list are positive numbers and the list can be empty.

# Notes

- it may happen that the input string have leading, trailing whitespaces and more than a unique whitespace between two consecutive numbers
- Don't modify the input
- For C: The result is freed.

order_weight=lambda s:' '.join(sorted(s.split(),key=lambda s:(sum(map(int,s)),s)))


Solve in Python:
My friend John likes to go to the cinema. He can choose between system A and system B.
```
System A : he buys a ticket (15 dollars) every time
System B : he buys a card (500 dollars) and a first ticket for 0.90 times the ticket price,
then for each additional ticket he pays 0.90 times the price paid for the previous ticket.
```
#Example:
If John goes to the cinema 3 times:
```
System A : 15 * 3 = 45
System B : 500 + 15 * 0.90 + (15 * 0.90) * 0.90 + (15 * 0.90 * 0.90) * 0.90 ( = 536.5849999999999, no rounding for each ticket)
```
John wants to know how many times he must go to the cinema so that the *final result* of System B, when rounded *up* to the next dollar, will be cheaper than System A.

The function `movie` has 3 parameters: `card` (price of the card), `ticket` (normal price of
a ticket), `perc` (fraction of what he paid for the previous ticket) and returns the first `n` such that
```
ceil(price of System B) < price of System A.
```
More examples:
```
movie(500, 15, 0.9) should return 43
    (with card the total price is 634, with tickets 645)
movie(100, 10, 0.95) should return 24
    (with card the total price is 235, with tickets 240)
```

from math import *
def movie(card, ticket, perc):
    n = 1
    while ceil(card + ticket*perc*(1-perc**n)/(1-perc)) >= ticket*n: n += 1
    return n


Solve in Python:
My friend wants a new band name for her band. She like bands that use the formula: "The" + a noun with the first letter capitalized, for example:

`"dolphin" -> "The Dolphin"`

However, when a noun STARTS and ENDS with the same letter, she likes to repeat the noun twice and connect them together with the first and last letter, combined into one word (WITHOUT "The" in front), like this:

`"alaska" -> "Alaskalaska"`

Complete the function that takes a noun as a string, and returns her preferred band name written as a string.

def band_name_generator(s):
    return (('The ' if s[0] != s[-1] else s[:-1]) + s).title()


Solve in Python:
My grandfather always predicted how old people would get, and right before he passed away he revealed his secret!

In honor of my grandfather's memory we will write a function using his formula!

* Take a list of ages when each of your great-grandparent died.
* Multiply each number by itself.
* Add them all together.
* Take the square root of the result.
* Divide by two.

## Example

```R
predict_age(65, 60, 75, 55, 60, 63, 64, 45) == 86
```
```python
predict_age(65, 60, 75, 55, 60, 63, 64, 45) == 86
```

Note: the result should be rounded down to the nearest integer.

Some random tests might fail due to a bug in the JavaScript implementation. Simply resubmit if that happens to you.

import math

def predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):
    arr=[age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]
    result=int((math.sqrt(sum([i ** 2 for i in arr])))/2)
    return result


Solve in Python:
My little sister came back home from school with the following task:
given a squared sheet of paper she has to cut it in pieces
which, when assembled, give squares the sides of which form
an increasing sequence of numbers.
At the beginning it was lot of fun but little by little we were tired of seeing the pile of torn paper.
So we decided to write a program that could help us and protects trees.

## Task

Given a positive integral number n, return a **strictly increasing** sequence (list/array/string depending on the language) of numbers, so that the sum of the squares is equal to n².

If there are multiple solutions (and there will be), return as far as possible the result with the largest possible values:

## Examples

`decompose(11)` must return `[1,2,4,10]`. Note that there are actually two ways to decompose 11²,
11² = 121 = 1 + 4 + 16 + 100 = 1² + 2² + 4² + 10² but don't return `[2,6,9]`, since 9 is smaller than 10.

For `decompose(50)` don't return `[1, 1, 4, 9, 49]` but `[1, 3, 5, 8, 49]` since `[1, 1, 4, 9, 49]`
doesn't form a strictly increasing sequence.

## Note
Neither `[n]` nor `[1,1,1,…,1]` are valid solutions. If no valid solution exists, return `nil`, `null`, `Nothing`, `None` (depending on the language) or `"[]"` (C) ,`{}` (C++), `[]` (Swift, Go).

The function "decompose" will take a positive integer n
and return the decomposition of N = n² as:

- [x1 ... xk]
or
- "x1 ... xk"
or
- Just [x1 ... xk]
or
- Some [x1 ... xk]
or
- {x1 ... xk}
or
- "[x1,x2, ... ,xk]"

depending on the language (see "Sample tests")

# Note for Bash
```
decompose 50 returns "1,3,5,8,49"
decompose 4  returns "Nothing"
```
# Hint

Very often `xk` will be `n-1`.

def decompose(n):
    total = 0
    answer = [n]
    while len(answer):
        temp = answer.pop()
        total += temp ** 2
        for i in range(temp - 1, 0, -1):
            if total - (i ** 2) >= 0:
                total -= i ** 2
                answer.append(i)
                if total == 0:
                    return sorted(answer)
    return None


Solve in Python:
My third kata, write a function `check_generator` that examines the status of a Python generator expression `gen` and returns `'Created'`, `'Started'` or `'Finished'`. For example:

`gen = (i for i in range(1))` >>> returns `'Created'` (the generator has been initiated)

`gen = (i for i in range(1)); next(gen, None)` >>> returns `'Started'` (the generator has yielded a value)

`gen = (i for i in range(1)); next(gen, None); next(gen, None)` >>> returns `'Finished'` (the generator has been exhuasted)

For an introduction to Python generators, read: https://wiki.python.org/moin/Generators.

Please do vote and rank the kata, and provide any feedback.

Hint: you can solve this if you know the right module to use.

from inspect import getgeneratorstate as gt
d = {'GEN_CREATED':'Created', 'GEN_SUSPENDED':'Started'}
def check_generator(gen):
    return d.get(gt(gen), 'Finished')


Solve in Python:
My washing machine uses ```water``` amount of water to wash ```clothes``` amount of clothes. You are given a ```load``` amount of clothes to wash.  For each single item of load above the standard amount of clothes, the washing machine will use 10% more water (multiplicative) to clean.
For example, if the amount of clothes is ```10```, the amount of water it requires is ```5``` and the load is  ```14```, then you need ```5 * 1.1 ^ (14 - 10)``` amount of water.

Write a function ```howMuchWater``` (JS)/```how_much_water``` (Python) to work out how much water is needed if you have a ```clothes``` amount of clothes.  The function will accept 3 parameters - ```howMuchWater(water, load, clothes)``` / ```how_much_water(water, load, clothes)```

My washing machine is an old model that can only handle double the amount of ```load```.  If the amount of ```clothes``` is more than 2 times the standard amount of ```load```, return ```'Too much clothes'```.  The washing machine also cannot handle any amount of clothes less than ```load```.  If that is the case, return ```'Not enough clothes'```.

The answer should be rounded to the nearest 2 decimal places.

def how_much_water(water, load, clothes):
    if clothes > load * 2:
        return 'Too much clothes'
    elif clothes < load:
        return 'Not enough clothes'
    else:
        return round(water * 1.1 ** (clothes - load), 2)


Solve in Python:
Mysterious Chefland… Recently, Chef realised that Discuss, the educational system of Chefland, is out of date. Therefore, he is trying to find ways to update the infrastructure in the country. One possible way is to move all materials from Discuss to Discourse.
Chef will have access to Discourse if his knowledge and power become exactly equal to $N$ and $M$ respectively. Initially, he has power $1$ and knowledge $1$.
Chef can perform actions of the following types to improve his skills:
- solve a problem — increase his knowledge by $X$
- do a push-up — increase his power by $Y$
- install ShareChat to keep in touch with friends — increase both knowledge and power by $1$
Chef can only install ShareChat at most once. The remaining actions may be performed any number of times and the actions may be performed in any order.
Help Chef find out whether it is possible to move from Discuss to Discourse.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains four space-separated integers $N$, $M$, $X$ and $Y$.

-----Output-----
For each test case, print a single line containing the string "Chefirnemo" if it is possible to reach the required knowledge and power or "Pofik" if it is impossible.

-----Constraints-----
- $1 \le T \le 1,000$
- $1 \le N, M, X, Y \le 10^9$

-----Subtasks-----
Subtask #1 (30 points): $1 \le N, M, X, Y \le 100$
Subtask #2 (70 points): original constraints

-----Example Input-----
5
2 2 1 2
11 10 5 9
11 11 5 9
12 11 5 9
1 2 1 100

-----Example Output-----
Chefirnemo
Chefirnemo
Pofik
Chefirnemo
Pofik

-----Explanation-----
Example case 2: We add $Y=9$ once to the power to get power $10$. We add $X=5$ twice to the knowledge to get knowledge $11$.
Example case 3: We can see that it is impossible to reach power $M=11$ no matter which or how many operations we do. Note that the ShareChat operation will increase both knowledge and power by $1$, and...

t = int(input())
for _ in range(t):
 n,m,x,y = map(int,input().strip().split(" "))
 n-=1
 m-=1
 rx=n%x
 ry=m%y
 if (rx==0 and ry==0) or (rx==1 and ry==1):
  print("Chefirnemo")
 elif (x==1 and ry==1 and n>0) or (m>0 and y==1 and rx==1):
  print("Chefirnemo")
 else:
  print("Pofik")


Solve in Python:
N Soldiers are lined up for a memory test. They are numbered from 0 to N-1 from left to right.

In the test, there are M rounds. In each round, Captain selects one position. Soldier at that position will be numbered 0. All the soldiers to the right of selected position will be numbered one greater than the soldier to his left. All the soldiers to the left of selected position will be numbered one greater than the soldier to his right.

eg. if N = 6 and selected position is 3, then the numbering will be [3, 2, 1, 0, 1, 2].

After M rounds, Captain asked each soldier to shout out the greatest number he was assigned during the M rounds. In order to check the correctness, Captain asked you to produce the correct values for each soldier (That is the correct value each soldier should shout out).

-----Input-----
The first line of the input contains an integer T denoting the number of test cases.
First line of each test case contains two integers, N and M.
Second line of each test case contains M integers, the positions selected by Captain, in that order.

-----Output-----
For each test case, output one line with N space separated integers.

-----Constraints-----
- 1 ≤ T ≤ 10^4
- 1 ≤ N ≤ 10^5
- 1 ≤ M ≤ 10^5
- 1 ≤ Sum of N over all testcases ≤ 10^5
- 1 ≤ Sum of M over all testcases ≤ 10^5
- 0 ≤ Positions selected by captain ≤ N-1

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

Output
1 0 1 2
3 2 1 1 2 3

import sys
input=sys.stdin.readline
for i in range(int(input())):
 n,m = (int(i) for i in input().split())
 li = [int(i) for i in input().split()]
 ma,mi = max(li),min(li)
 for i in range(n):
  print(max(ma-i,i-mi),end=' ')
 print()


Solve in Python:
N cars are going to the same destination along a one lane road.  The destination is target miles away.
Each car i has a constant speed speed[i] (in miles per hour), and initial position position[i] miles towards the target along the road.
A car can never pass another car ahead of it, but it can catch up to it, and drive bumper to bumper at the same speed.
The distance between these two cars is ignored - they are assumed to have the same position.
A car fleet is some non-empty set of cars driving at the same position and same speed.  Note that a single car is also a car fleet.
If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet.

How many car fleets will arrive at the destination?

Example 1:
Input: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]
Output: 3
Explanation:
The cars starting at 10 and 8 become a fleet, meeting each other at 12.
The car starting at 0 doesn't catch up to any other car, so it is a fleet by itself.
The cars starting at 5 and 3 become a fleet, meeting each other at 6.
Note that no other cars meet these fleets before the destination, so the answer is 3.

Note:

0 <= N <= 10 ^ 4
0 < target <= 10 ^ 6
0 < speed[i] <= 10 ^ 6
0 <= position[i] < target
All initial positions are different.

class Solution:
    def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
        N = len(position)
        cars = sorted((s,p) for s,p in zip(speed, position))
        seen = set()
        res = 0
        # print(cars)
        for i in range(N):
            if i in seen: continue
            seen.add(i)
            res += 1

            for j in range(i+1, N):
                if j in seen or cars[j][0]==cars[i][0]: continue
                t = (cars[i][1]-cars[j][1])/(cars[j][0]-cars[i][0])
                if t<0 or t*cars[i][0]+cars[i][1]>target: continue
                seen.add(j)

        return res


Solve in Python:
N hotels are located on a straight line. The coordinate of the i-th hotel (1 \leq i \leq N) is x_i.
Tak the traveler has the following two personal principles:
 - He never travels a distance of more than L in a single day.
 - He never sleeps in the open. That is, he must stay at a hotel at the end of a day.
You are given Q queries. The j-th (1 \leq j \leq Q) query is described by two distinct integers a_j and b_j.
For each query, find the minimum number of days that Tak needs to travel from the a_j-th hotel to the b_j-th hotel following his principles.
It is guaranteed that he can always travel from the a_j-th hotel to the b_j-th hotel, in any given input.

-----Constraints-----
 - 2 \leq N \leq 10^5
 - 1 \leq L \leq 10^9
 - 1 \leq Q \leq 10^5
 - 1 \leq x_i < x_2 < ... < x_N \leq 10^9
 - x_{i+1} - x_i \leq L
 - 1 \leq a_j,b_j \leq N
 - a_j \neq b_j
 - N,\,L,\,Q,\,x_i,\,a_j,\,b_j are integers.

-----Partial Score-----
 - 200 points will be awarded for passing the test set satisfying N \leq 10^3 and Q \leq 10^3.

-----Input-----
The input is given from Standard Input in the following format:
N
x_1 x_2 ... x_N
L
Q
a_1 b_1
a_2 b_2
:
a_Q b_Q

-----Output-----
Print Q lines.
The j-th line (1 \leq j \leq Q) should contain the minimum number of days that Tak needs to travel from the a_j-th hotel to the b_j-th hotel.

-----Sample Input-----
9
1 3 6 13 15 18 19 29 31
10
4
1 8
7 3
6 7
8 5

-----Sample Output-----
4
2
1
2

For the 1-st query, he can travel from the 1-st hotel to the 8-th hotel in 4 days, as follows:
 - Day 1: Travel from the 1-st hotel to the 2-nd hotel. The distance traveled is 2.
 - Day 2: Travel from the 2-nd hotel to the 4-th hotel. The distance traveled is 10.
 - Day 3: Travel from the 4-th hotel to the 7-th hotel. The distance traveled is 6.
 - Day 4: Travel from the 7-th hotel to the 8-th hotel. The distance traveled is 10.

def inpl(): return [int(i) for i in input().split()]
def hmd(a, b):
    ctr = -1
    while H[ctr+1][a] < b:
        ctr += 1
    vn = H[ctr][a]
    if (vn == b and ctr == 0) or ctr == -1:
        return 1
    return 2**ctr + hmd(vn,b)
N = int(input())
x = inpl() + [10**10]
L = int(input())
H = []
G = [N-1]*N
b = 0
for a in range(N):
    while x[b+1] - x[a] <= L:
        if b == N-1:
            break
        b += 1
    G[a] = b
H.append(G)
while G[0] != N-1:
    G = [G[i] for i in G]
    H.append(G)
H.append([10**10]*N)
Q = int(input())
for _ in range(Q):
    a, b = sorted(inpl())
    print(hmd(a-1,b-1))


Solve in Python:
NOTE: It is recommended you complete [Introduction to Esolangs](https://www.codewars.com/kata/esolang-interpreters-number-1-introduction-to-esolangs-and-my-first-interpreter-ministringfuck/) or [MiniBitFlip](https://www.codewars.com/kata/esolang-minibitflip/) before solving this one.
Task:
Make an interpreter for an esoteric language called Ticker. Ticker is a descendant of [Tick](https://www.codewars.com/kata/esolang-tick). Your language has the following commands:

`>`: increment the selector by 1

`<`: decrement the selector by 1

`*`: add the ascii value of selected cell to the output tape

`+`: increment selected cell data by 1. If 256, then it is 0

`-`: increment selected cell data by -1. If less than 0, then 255

`/`: set selected cell data to 0

`!`: add new data cell to the end of the array

You start with selector at `0` and one cell with a value of `0`. If selector goes out of bounds, assume 0 for that cell but do not add it to the memory. If a + or - is being made do not change the value of the assumed cell. It will always stay 0 unless it is added to the memory

In other words:

```
data: start 0 end
selector:   ^
data start 1 2 4 end
selector:        ^
Assume that cell is zero.
```

Examples:
Consider the following...

def interpreter(tape):
    dct, selector, out = {0:0}, 0, ''
    for l in tape:
        if l == '>': selector += 1
        if l == '<': selector -= 1
        if l == '*': out += chr(dct.get(selector,0))
        if selector in dct:
            if l == '+': dct[selector] = (dct[selector] + 1) % 256
            if l == '-': dct[selector] = (dct[selector] - 1) % 256
            if l == '/': dct[selector] = 0
        if l == '!': dct[ max(dct)+1 ] = 0
    return out


Solve in Python:
Nadaca is a country with N$N$ cities. These cities are numbered 1$1$ through N$N$ and connected by M$M$ bidirectional roads. Each city can be reached from every other city using these roads.
Initially, Ryan is in city 1$1$. At each of the following K$K$ seconds, he may move from his current city to an adjacent city (a city connected by a road to his current city) or stay at his current city. Ryan also has Q$Q$ conditions (a1,b1),(a2,b2),…,(aQ,bQ)$(a_1, b_1), (a_2, b_2), \ldots, (a_Q, b_Q)$ meaning that during this K$K$-second trip, for each valid i$i$, he wants to be in city ai$a_i$ after exactly bi$b_i$ seconds.
Since you are very good with directions, Ryan asked you to tell him how many different trips he could make while satisfying all conditions. Compute this number modulo 109+7$10^9 + 7$. A trip is a sequence of Ryan's current cities after 1,2,…,K$1, 2, \ldots, K$ seconds.

-----Input-----
- The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows.
- The first line of each test case contains three space-separated integers N$N$, M$M$ and K$K$.
- Each of the next M$M$ lines contains two space-separated integers u$u$ and v$v$ denoting a road between cities u$u$ and v$v$.
- The next line contains a single integer Q$Q$.
- Q$Q$ lines follow. For each i$i$ (1≤i≤Q$1 \le i \le Q$), the i$i$-th of these lines contains two space-separated integers ai$a_i$ and bi$b_i$.

-----Output-----
For each test case, print a single line containing one integer — the number of trips Ryan can make, modulo 109+7$10^9+7$.

-----Constraints-----
- 1≤T≤50$1 \le T \le 50$
- 1≤N,M,K,Q≤9,000$1 \le N, M, K, Q \le 9,000$
- 1≤ui,vi≤N$1 \le u_i, v_i \le N$ for each valid i$i$
- ui≠vi$u_i \neq v_i$ for each valid i$i$
- there is at most one road between each pair of cities
- each city is reachable from every other city
- 1≤ai≤N$1 \le a_i \le N$ for each valid i$i$
- 0≤bi≤K$0 \le b_i \le K$ for each valid i$i$
- the sum of N$N$ over all test cases does not exceed...

T = int(input())
for _ in range(T):
    N, M, K = [int(x) for x in input().split()]
    UV = [[int(x) for x in input().split()] for _ in range(M)]
    Q = int(input())
    AB = [[int(x) for x in input().split()] for _ in range(Q)]

    X = [[i] for i in range(N)]
    for u, v in UV:
     X[u - 1] += [v - 1]
     X[v - 1] += [u - 1]

    A = [[1 if i > 0 or j == 0 else 0 for j in range(N)] for i in range(K + 1)]
    for a, b in AB:
     A[b] = [1 if i == a - 1 else 0 for i in range(N)]

    if A[0][0] == 1:
     for k in range(K - 1, -1, -1):
      for i in range(N):
       if A[k][i] != 0:
        A[k][i] = sum(A[k + 1][j] for j in X[i])

    print(A[0][0])


Solve in Python:
Naman owns a very famous Ice Cream parlour in Pune. He has a wide range of flavours with different pricing.

Every flavour costs ₹ X per gram and quantity of each flavour in the parlour is indefinite. Now, Naman has

received an order for a party wherein he is asked to prepare each Ice Cream with N number of flavours.

He needs to prepare each Ice Cream of W grams and at the same time has to keep the cost minimum.

Can you help him out?

Note: If it is not possible to prepare such an Ice Cream, print “Not Possible”.

-----Input:-----

First line contains an integer T denoting the number of test cases.

First line of every test case contains an integer N denoting the number of flavours.

The second line of every test case by N space separated integers denoting the cost per gram of each flavour.

Second line of every test case contains two space separated integers W and Y denoting the weight

of Ice Cream in grams and the number of flavours to be used respectively.

-----Output:-----

For each test case, print the total cost of the Ice Cream in a single line.

-----Constraints:-----
1 ≤ T ≤ 100
1 ≤ N,W,Y ≤ 40000

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

18

Not Possible

-----Explanation:-----

In the first test case to achieve the minimum cost, the Ice Cream will consist of 8 grams

of flavour costing ₹1, 1 gram of flavour costing ₹4 and 1 gram of flavour costing ₹6.

In the second test case it is not possible to make an ice-cream weighing 1 gram using 2 flavours.

test = int(input())
for i in range(test):
 flavor = int(input())
 rate = input()
 gaf = input()
 gaf = gaf.split()
 gaf = [int(x) for x in gaf]
 rate = rate.split()
 rate = [int(x) for x in rate]
 rate.sort()
 c = gaf[0] - gaf[1]
 sum = rate[0]*c
 t = True
 if gaf[0] < gaf[1]:
  t = False
 j = 0
 while(j<gaf[1] and t):
  sum = sum + rate[j]
  j = j + 1
 if t :
  print(sum)
 else:
  print("Not Possible")


Solve in Python:
Naming multiple files can be a pain sometimes.

#### Task:

Your job here is to create a function that will take three parameters, `fmt`, `nbr` and `start`, and create an array of `nbr` elements formatted according to `frm` with the starting index `start`. `fmt` will have `` inserted at various locations; this is where the file index number goes in each file.

#### Description of edge cases:

1. If `nbr` is less than or equal to 0, or not whole, return an empty array.
2. If `fmt` does not contain `''`, just return an array with `nbr` elements that are all equal to `fmt`.
3. If `start` is not an integer, return an empty array.

#### What each parameter looks like:

```python
type(frm) #=> str
  : "text_to_stay_constant_from_file_to_file "
type(nbr) #=> int
  : number_of_files
type(start) #=> int
  : index_no_of_first_file
type(name_file(frm, nbr, start)) #=> list
```

#### Some examples:

```python
name_file("IMG ", 4, 1)
  #=> ["IMG 1", "IMG 2", "IMG 3", "IMG 4"])
name_file("image #.jpg", 3, 7)
  #=> ["image #7.jpg", "image #8.jpg", "image #9.jpg"]
name_file("# #", 3, -2)
  #=> ["#-2 #-2", "#-1 #-1", "#0 #0"]
```

Also check out my other creations — [Elections: Weighted Average](https://www.codewars.com/kata/elections-weighted-average), [Identify Case](https://www.codewars.com/kata/identify-case), [Split Without Loss](https://www.codewars.com/kata/split-without-loss), [Adding Fractions](https://www.codewars.com/kata/adding-fractions),
[Random Integers](https://www.codewars.com/kata/random-integers), [Implement String#transpose](https://www.codewars.com/kata/implement-string-number-transpose), [Implement Array#transpose!](https://www.codewars.com/kata/implement-array-number-transpose), [Arrays and Procs #1](https://www.codewars.com/kata/arrays-and-procs-number-1), and [Arrays and Procs #2](https://www.codewars.com/kata/arrays-and-procs-number-2).

If you notice any issues or have any suggestions/comments whatsoever, please don't hesitate to mark an issue or just comment. Thanks!

name_file=lambda f, n, s: [f.replace("<index_no>",str(i+s)) for i in range(n)] if n%1==0 and s%1==0 else []


Solve in Python:
Naturally, the magical girl is very good at performing magic. She recently met her master wizard Devu, who gifted her R potions of red liquid,
B potions of blue liquid, and G potions of green liquid.

-
The red liquid potions have liquid amounts given by r[1], ..., r[R] liters.

-
The green liquid potions have liquid amounts given by g[1], ..., g[G] liters.

-
The blue liquid potions have liquid amounts given by b[1], ..., b[B] liters.

She want to play with the potions by applying magic tricks on them. In a single magic trick, she will choose a particular color. Then she will pick all the potions of the chosen color and decrease the amount of liquid in them to half (i.e. if initial amount
of liquid is x, then the amount after decrement will be x / 2  where division is integer division, e.g. 3 / 2 = 1 and 4 / 2 = 2).

Because she has to go out of station to meet her uncle Churu, a wannabe wizard, only M minutes are left for her. In a single minute, she can perform at most one magic trick. Hence, she can perform at most M magic tricks.

She would like to minimize the maximum amount of liquid among all of Red, Green and Blue colored potions. Formally Let v be the maximum value of amount of liquid in any potion. We want to minimize the value of v.
Please help her.

-----Input-----

First line of the input contains an integer T denoting the number of test cases.
Then for each test case, we have four lines.

The first line contains four space separated integers R, G, B, M. The next 3 lines will describe the amount of different color liquids (r, g, b), which are separated by space.

-----Output-----
For each test case, print a single integer denoting the answer of the problem.

-----Constraints-----
-  1 ≤ T ≤ 1000
-  1 ≤ R, G, B, M ≤ 100
-  1 ≤ r[i], g[i], b[i] ≤ 10^9

-----Example-----
Input:
3
1 1 1 1
1
2
3
1 1 1 1
2
4
6
3 2 2 2
1 2 3
2 4
6 8
Output:
2
4
4

-----Explanation-----
Example case 1. Magical girl can pick the blue potion and make its liquid amount half. So the potions will now have amounts...

for _ in range(int(input())):
 r, g, b, m = map(int, input().split())
 R = max(list(map(int, input().split())))
 G = max(list(map(int, input().split())))
 B = max(list(map(int, input().split())))

 cur = [R, G, B]

 while m > 0:
  m -= 1
  index = cur.index(max(cur))
  cur[index] //= 2

 print(max(cur))


Solve in Python:
Nature photographing may be fun for tourists, but it is one of the most complicated things for photographers. To capture all the facets of a bird, you might need more than one cameras. You recently encountered such a situation.
There are $n$ photographers, so there are $n$ cameras in a line on the x-axis. All the cameras are at distinct coordinates.
You want to pair up these cameras ($n$ is even) in such a way that the sum of angles subtended on the bird by the pair of cameras is maximized. Formally, let A, B be two cameras, and let P be the bird to be captured by these two cameras. The angle will APB.
Note: All angles are in radians.

-----Input-----
- The first line of the input contains an integer $T$ denoting the number of test cases. The description of the test cases follows.
- The first line of each test case contains an integer $n$.
- The second line of each test case contains $n$ space-separated integers denoting the $x_i$ coordinates of the cameras.
- The third line of each test case contains two space-separated integers $P, Q$ denoting the x and y coordinates of the bird respectively.

-----Output-----
For each test case, output your answer in a single line. Your answer would be considered correct if its absolute error is less than or equal to 1e-6 of the actual answer.

-----Constraints-----
- $1 \le T \le 10$
- $2 \le n \leq  100$
- $1 \le x_i \leq 300$
- $0 \le P \leq 300$
- $1 \le Q \leq 300$

-----Example Input-----
2
2
0 1
0 1
2
0 1
100 1

-----Example Output-----
0.785398163397
0.000100999899

-----Explanation-----
Note: $1 \leq x_i$ is not being satisfied by the sample input, but will be satisfied in the actual test data.
Testcase 1: There are only 2 cameras, so they have to paired up with each other. And the angle subtended by then is 45 degrees. Converting this to radians gives the output.

import math
for _ in range(int(input())):
    n = int(input())
    cameras = list(map(int,input().split()))
    p,q = map(int,input().split())
    cameras.sort()
    sumA = 0
    # radians  c**2 = a**2 + b**2 -2ac(Cos(degree))
    for i in range(n//2):
        p1 = cameras[i]
        p2 = cameras[n-1-i]
        p12 = p2-p1
        # print(p1,p2)
        sideA = math.sqrt((p-p1)**2 + q**2)
        sideB = math.sqrt((p-p2)**2 + q**2)
        # print('sideA:',sideA,'sideB:',sideB)
        radians = math.acos(((p12**2)-sideA**2 - sideB**2 )/(-2*sideA*sideB))
        sumA +=radians

    print(sumA)


Solve in Python:
Nauuo is a girl who loves drawing circles.

One day she has drawn a circle and wanted to draw a tree on it.

The tree is a connected undirected graph consisting of $n$ nodes and $n-1$ edges. The nodes are numbered from $1$ to $n$.

Nauuo wants to draw a tree on the circle, the nodes of the tree should be in $n$ distinct points on the circle, and the edges should be straight without crossing each other.

"Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges.

Nauuo wants to draw the tree using a permutation of $n$ elements. A permutation of $n$ elements is a sequence of integers $p_1,p_2,\ldots,p_n$ in which every integer from $1$ to $n$ appears exactly once.

After a permutation is chosen Nauuo draws the $i$-th node in the $p_i$-th point on the circle, then draws the edges connecting the nodes.

The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo $998244353$, can you help her?

It is obvious that whether a permutation is valid or not does not depend on which $n$ points on the circle are chosen.

-----Input-----

The first line contains a single integer $n$ ($2\le n\le 2\cdot 10^5$) — the number of nodes in the tree.

Each of the next $n-1$ lines contains two integers $u$ and $v$ ($1\le u,v\le n$), denoting there is an edge between $u$ and $v$.

It is guaranteed that the given edges form a tree.

-----Output-----

The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo $998244353$.

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

Output
16
Input
4
1 2
1 3
1 4

Output
24

-----Note-----

Example 1

All valid permutations and their spanning trees are as follows.

[Image]

Here is an example of invalid permutation: the edges $(1,3)$ and $(2,4)$ are crossed.

[Image]

Example 2

Every permutation leads to a...

mod=998244353
n=int(input())
deg=[0]*(n+1)
fac=[1]*(n+1)
for i in range(1,n+1):
    fac[i]=(fac[i-1]*i)%mod
for i in range(n-1):
    a,b=list(map(int,input().split()))
    deg[a]+=1
    deg[b]+=1
s=1
for i in range(1,n+1):
    s=(s*(fac[deg[i]]))%mod
s=(s*n)%mod
print(s)


Solve in Python:
Navnit is a college student and there are $N$ students in his college .Students are numbered from $1$ to $N$.
You are given $M$ facts that "Student $A_i$ and $B_i$".The same fact can be given multiple times .If $A_i$ is a friend of $B_i$ ,then $B_i$ is also a friend of $A_i$ . If $A_i$ is a friend of $B_i$ and $B_i$ is a friend of $C_i$ then $A_i$ is also a friend of $C_i$.
Find number of ways in which two students can be selected in such a way that they are not friends.

-----Input:-----
- First line will contain two integers $N$ and $M$.
- Then $M$ lines follow. Each line contains two integers $A_i$ and $B_i$ denoting the students who are friends.

-----Output:-----
For each testcase, output the number of ways in which  two students can be selected in such a way that they are friends.

-----Constraints-----
- $2 \leq N \leq 200000$
- $0 \leq M \leq 200000$
- $1 \leq A_i,B_i \leq N$

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

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

-----EXPLANATION:-----
Groups of friend are $[1,2,5]$ and $[3,4]$.Hence the answer is  3 X 2 =6.

# cook your dish here
from collections import defaultdict
d=defaultdict(list)
def dfs(i):
    p=0
    nonlocal v
    e=[i]
    while(e!=[]):
        p+=1
        x=e.pop(0)
        v[x]=1
        for i in d[x]:
            if v[i]==-1:
                v[i]=1
                e.append(i)
    return p

n,m=list(map(int,input().split()))
for i in range(n+1):
    d[i]=[]
for _ in range(m):
	a,b=list(map(int,input().split()))
	d[a].append(b)
	d[b].append(a)
v=[]
for i in range(n+1):
    v.append(-1)
c=0
p=[]
for i in range(1,n+1):
    if v[i]==-1:
        c+=1
        p.append(dfs(i))
an=0
s=0
for i in range(c):
    s+=p[i]
    an+=p[i]*(n-s)
print(an)


Solve in Python:
Nexus 4.O is going to be organized by ASME, GLA University. Shubhanshu, Head of Finance Team is working for it. He has $N$ number of bills of different values as $a$$1$,$ a$$2$, $a$$3$…$a$$n$.
He is interested in a game in which one has to do the addition of the bills. But due to privacy concerns, he cannot share the details with others.
He can only trust his best friend Avani with such a confidential thing. So, he asked her to play this game.
Rules of the game :
- Avani needs to answer $Q$ queries.
- Every $Q$$i$ query has 2 values $X$$i$ and $Y$$i$.
- Avani needs to find the sum of the values between $X$$i$ and $Y$$i$ (inclusive).
So, you need to help Avani in answering the $Q$ queries

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- The first line of each test case contains the value $N$ and $Q$.
- The second line of each test case contains the $N$ space-separated values as $a$$1$,$ a$$2$, $a$$3$…$a$$n$.
- The next line of each test case containing $Q$ query with $X$$i$ and $Y$$i$.

-----Output:-----
For each test case, Print the total amount between $X$$i$ and $Y$$i$ for $Q$ number of queries.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq N \leq 10^5$
- $1 \leq Q \leq 10^5$
- $1 \leq a$$i$$ \leq 10^9$

-----Subtasks (25 points) :-----
- $1 \leq N \leq 10^2$.
- $1 \leq Q \leq 10^2$.
- $1 \leq a$$i$$ \leq 10^5$.

-----Subtasks (25 points) :-----
- $1 \leq N \leq 10^3$.
- $1 \leq Q \leq 10^3$.
- $1 \leq a$$i$$ \leq 10^5$.

-----Subtasks (50 points) :-----
- $Original  Constraints$.

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

-----Sample Output:-----
5
21
26

-----EXPLANATION:-----
$Q$$1$ : (2,3) 2+3=5
$Q$$2$ : (1,6) 1+2+3+4+5+6=21
$Q$$3$ : (5,8) 5+6+7+8=26

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

 p = [0]

 for i in a:
  p.append(p[-1] + i)

 for _ in range(q):
  x, y = map(int, input().split())

  print(p[y] - p[x - 1])


Solve in Python:
Nickname Generator

Write a function, `nicknameGenerator` that takes a string name as an argument and returns the first 3 or 4 letters as a nickname.

If the 3rd letter is a consonant, return the first 3 letters.

If the 3rd letter is a vowel, return the first 4 letters.

If the string is less than 4 characters, return "Error: Name too short".

**Notes:**

- Vowels are "aeiou", so discount the letter "y".
- Input will always be a string.
- Input will always have the first letter capitalised and the rest lowercase (e.g. Sam).
- The input can be modified

def nickname_generator(name):
        if len(name) > 3:
            return name[:4] if name[2] in 'aeiou' else name[:3]
        else:
            return 'Error: Name too short'


Solve in Python:
Nikita likes tasks on order statistics, for example, he can easily find the $k$-th number in increasing order on a segment of an array. But now Nikita wonders how many segments of an array there are such that a given number $x$ is the $k$-th number in increasing order on this segment. In other words, you should find the number of segments of a given array such that there are exactly $k$ numbers of this segment which are less than $x$.

Nikita wants to get answer for this question for each $k$ from $0$ to $n$, where $n$ is the size of the array.

-----Input-----

The first line contains two integers $n$ and $x$ $(1 \le n \le 2 \cdot 10^5, -10^9 \le x \le 10^9)$.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ $(-10^9 \le a_i \le 10^9)$ — the given array.

-----Output-----

Print $n+1$ integers, where the $i$-th number is the answer for Nikita's question for $k=i-1$.

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

Output
6 5 4 0 0 0
Input
2 6
-5 9

Output
1 2 0
Input
6 99
-1 -1 -1 -1 -1 -1

Output
0 6 5 4 3 2 1

from math import pi
from cmath import exp
def fft(a, lgN, rot=1): # rot=-1 for ifft
  N = 1<<lgN
  assert len(a)==N
  rev = [0]*N
  for i in range(N):
    rev[i] = (rev[i>>1]>>1)+(i&1)*(N>>1)
  A = [a[rev[i]] for i in range(N)]
  h = 1
  while h<N:
    w_m = exp((0+1j) * rot * (pi / h))
    for k in range(0, N, h<<1):
      w = 1
      for j in range(h):
        t = w * A[k+j+h]
        A[k+j+h] = A[k+j]-t
        A[k+j] = A[k+j]+t
        w *= w_m
    h = h<<1
  return A if rot==1 else [x/N for x in A]

import sys
ints = (int(x) for x in sys.stdin.read().split())

n, x = (next(ints) for i in range(2))
r = [next(ints) for i in range(n)]
ac = [0]*(n+1)
for i in range(n): ac[i+1] = (r[i]<x) + ac[i]

# Multiset addition
min_A, min_B = 0, -ac[-1]
max_A, max_B = ac[-1], 0
N, lgN, m = 1, 0, 2*max(max_A-min_A+1, max_B-min_B+1)
while N<m: N,lgN = N<<1,lgN+1
a, b = [0]*N, [0]*N
for x in ac:
  a[x-min_A] += 1
  b[-x-min_B] += 1
c = zip(fft(a, lgN), fft(b, lgN))
c = fft([x*y for x,y in c], lgN, rot=-1)
c = [round(x.real) for x in c][-min_A-min_B:][:n+1]
c[0] = sum((x*(x-1))//2 for x in a)
print(*c, *(0 for i in range(n+1-len(c))), flush=True)


Solve in Python:
Nitika was once reading a history book and wanted to analyze it. So she asked her brother to create a list of names of the various famous personalities in the book. Her brother gave Nitika the list. Nitika was furious when she saw the list. The names of the people were not properly formatted. She doesn't like this and would like to properly format it.
A name can have at most three parts: first name, middle name and last name. It will have at least one part. The last name is always present. The rules of formatting a name are very simple:

- Only the first letter of each part of the name should be capital.
- All the parts of the name except the last part should be represented by only two characters. The first character should be the first letter of the part and should be capitalized. The second character should be ".".

Let us look at some examples of formatting according to these rules:
- gandhi -> Gandhi

- mahatma gandhI -> M. Gandhi
- Mohndas KaramChand ganDhi -> M. K. Gandhi

-----Input-----
The first line of the input contains an integer T denoting the number of test cases.
The only line of each test case contains the space separated parts of the name.

-----Output-----
For each case, output the properly formatted name.

-----Constraints-----
- 1 ≤ T ≤ 100
- 2 ≤ Length of each part of the name ≤ 10
- Each part of the name contains the letters from lower and upper case English alphabets (i.e. from 'a' to 'z', or 'A' to 'Z')

-----Subtasks-----
Subtask #1 (40 points)
- There is exactly one part in the name.

Subtask #2 (60 points)
- Original constraints.

-----Example-----
Input:
3
gandhi
mahatma gandhI
Mohndas KaramChand gandhi

Output:
Gandhi
M. Gandhi
M. K. Gandhi

-----Explanation-----
The examples are already explained in the problem statement.

# cook your dish here
x= int(input())
for i in range(x):
    y = list(map(str, input().split()))
    j= 0
    while j<len(y)-1:
        print((y[j][0]).capitalize()+".", end=' ')
        j+= 1
    print(y[len(y)-1].capitalize())


Solve in Python:
Niwel is a little golden bear. As everyone knows, bears live in forests, but Niwel got tired of seeing all the trees so he decided to move to the city.

In the city, Niwel took on a job managing bears to deliver goods. The city that he lives in can be represented as a directed graph with n nodes and m edges. Each edge has a weight capacity. A delivery consists of a bear carrying weights with their bear hands on a simple path from node 1 to node n. The total weight that travels across a particular edge must not exceed the weight capacity of that edge.

Niwel has exactly x bears. In the interest of fairness, no bear can rest, and the weight that each bear carries must be exactly the same. However, each bear may take different paths if they like.

Niwel would like to determine, what is the maximum amount of weight he can deliver (it's the sum of weights carried by bears). Find the maximum weight.

-----Input-----

The first line contains three integers n, m and x (2 ≤ n ≤ 50, 1 ≤ m ≤ 500, 1 ≤ x ≤ 100 000) — the number of nodes, the number of directed edges and the number of bears, respectively.

Each of the following m lines contains three integers a_{i}, b_{i} and c_{i} (1 ≤ a_{i}, b_{i} ≤ n, a_{i} ≠ b_{i}, 1 ≤ c_{i} ≤ 1 000 000). This represents a directed edge from node a_{i} to b_{i} with weight capacity c_{i}. There are no self loops and no multiple edges from one city to the other city. More formally, for each i and j that i ≠ j it's guaranteed that a_{i} ≠ a_{j} or b_{i} ≠ b_{j}. It is also guaranteed that there is at least one path from node 1 to node n.

-----Output-----

Print one real value on a single line — the maximum amount of weight Niwel can deliver if he uses exactly x bears. Your answer will be considered correct if its absolute or relative error does not exceed 10^{ - 6}.

Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if $\frac{|a - b|}{\operatorname{max}(1, b)} \leq 10^{-6}$.

-----Examples-----
Input
4 4...

from collections import deque

class Dinic():
    def __init__(self, listEdge, s, t):
        self.s = s
        self.t = t
        self.graph    = {}
        self.maxCap   = 1000000
        # dict các node lân cận

        # e[0]: from,  e[1]: to,  e[2]: dung luong
        for e in listEdge:

            if e[0] not in self.graph:
                self.graph[e[0]] = []

            if e[1] not in self.graph:
                self.graph[e[1]] = []
                                   #to     #cap   #reveser edge
            self.graph[e[0]].append([e[1], e[2],  len(self.graph[e[1]])])
            self.graph[e[1]].append([e[0],    0,  len(self.graph[e[0]])-1])

        self.N = len(self.graph.keys())

    def bfs(self):
        self.dist    = {}
        self.dist[self.s] = 0
        self.curIter = {node:[] for node in self.graph}

        Q = deque([self.s])

        while(len(Q) > 0):
            cur = Q.popleft()

            for index,e in enumerate(self.graph[cur]):
                # Chỉ add vào các node kế tiếp nếu dung lượng cạnh > 0 và chưa được visit trước đấy
                if e[1] > 0 and e[0] not in self.dist:
                    self.dist[e[0]] = self.dist[cur] + 1
                    # add vào danh sách node kế tiếp của node hiện tại
                    self.curIter[cur].append(index)
                    Q.append(e[0])

    def findPath(self, cur, f):
        if cur == self.t:
            return f

        while len(self.curIter[cur]) > 0:
            indexEdge    = self.curIter[cur][-1]
            nextNode     = self.graph[cur][indexEdge][0]
            remainCap    = self.graph[cur][indexEdge][1]
            indexPreEdge = self.graph[cur][indexEdge][2]

            if remainCap > 0 and self.dist[nextNode] > self.dist[cur]:
                #self.next[cur] = indexEdge
                flow = self.findPath(nextNode,  min(f, remainCap))

                if flow > 0:
      ...


Solve in Python:
No Story

No Description

Only by Thinking and Testing

Look at the results of the testcases, and guess the code!

---

## Series:

01. [A and B?](http://www.codewars.com/kata/56d904db9963e9cf5000037d)
02. [Incomplete string](http://www.codewars.com/kata/56d9292cc11bcc3629000533)
03. [True or False](http://www.codewars.com/kata/56d931ecc443d475d5000003)
04. [Something capitalized](http://www.codewars.com/kata/56d93f249c844788bc000002)
05. [Uniq or not Uniq](http://www.codewars.com/kata/56d949281b5fdc7666000004)
06. [Spatiotemporal index](http://www.codewars.com/kata/56d98b555492513acf00077d)
07. [Math of Primary School](http://www.codewars.com/kata/56d9b46113f38864b8000c5a)
08. [Math of Middle school](http://www.codewars.com/kata/56d9c274c550b4a5c2000d92)
09. [From nothingness To nothingness](http://www.codewars.com/kata/56d9cfd3f3928b4edd000021)
10. [Not perfect? Throw away!](http://www.codewars.com/kata/56dae2913cb6f5d428000f77)
11. [Welcome to take the bus](http://www.codewars.com/kata/56db19703cb6f5ec3e001393)
12. [A happy day will come](http://www.codewars.com/kata/56dc41173e5dd65179001167)
13. [Sum of 15(Hetu Luosliu)](http://www.codewars.com/kata/56dc5a773e5dd6dcf7001356)
14. [Nebula or Vortex](http://www.codewars.com/kata/56dd3dd94c9055a413000b22)
15. [Sport Star](http://www.codewars.com/kata/56dd927e4c9055f8470013a5)
16. [Falsetto Rap Concert](http://www.codewars.com/kata/56de38c1c54a9248dd0006e4)
17. [Wind whispers](http://www.codewars.com/kata/56de4d58301c1156170008ff)
18. [Mobile phone simulator](http://www.codewars.com/kata/56de82fb9905a1c3e6000b52)
19. [Join but not join](http://www.codewars.com/kata/56dfce76b832927775000027)
20. [I hate big and small](http://www.codewars.com/kata/56dfd5dfd28ffd52c6000bb7)
21. [I want to become diabetic ;-)](http://www.codewars.com/kata/56e0e065ef93568edb000731)
22. [How many blocks?](http://www.codewars.com/kata/56e0f1dc09eb083b07000028)
23. [Operator hidden in a string](http://www.codewars.com/kata/56e1161fef93568228000aad)
24. [Substring...

def mystery(n):
    return [i for i in range(1, n + 1) if n%i == 0 and i%2]


Solve in Python:
No description!!!

Input  :: [10,20,25,0]

Output :: ["+0", "+10", "+15", "-10"]

`Show some love, rank and upvote!`

def equalize(arr):
    return ['{:+d}'.format(n - arr[0]) for n in arr]


Solve in Python:
Nobody knows, but $N$ frogs live in Chef's garden.
Now they are siting on the X-axis and want to speak to each other. One frog can send a message to another one if the distance between them is less or equal to $K$.
Chef knows all $P$ pairs of frogs, which want to send messages. Help him to define can they or not!
Note : More than $1$ frog can be on the same point on the X-axis.

-----Input-----
- The first line contains three integers $N$, $K$ and $P$.
- The second line contains $N$ space-separated integers $A_1$, $A_2$, …, $A_N$ denoting the x-coordinates of frogs".
- Each of the next $P$ lines contains two integers $A$ and $B$ denoting the numbers of frogs according to the input.

-----Output-----
For each pair print "Yes" without a brackets if frogs can speak and "No" if they cannot.

-----Constraints-----
- $1 \le N, P \le 10^5$
- $0 \le A_i, K \le 10^9$
- $1 \le A, B \le N$

-----Example-----

-----Sample Input:-----
5 3 3
0 3 8 5 12
1 2
1 3
2 5

-----Sample Output:-----
Yes
Yes
No

-----Explanation-----
-
For pair $(1, 2)$ frog $1$ can directly speak to the frog $2$ as the distance between them is $3 - 0 = 3 \le K$ .
-
For pair $(1, 3)$ frog $1$ can send a message to frog $2$, frog $2$ can send it to frog $4$ and it can send it to frog $3$.
-
For pair $(2, 5)$ frogs can't send a message under current constraints.

class union_find:
 def __init__(self,N):
  self.parent = {}
  self.rank = []
  for i in range(N):
   self.parent[i] = i
   self.rank.append(0)

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

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

N,K,P = [int(i) for i in input().split()]
X = [int(i) for i in input().split()]
ans = []

uf = union_find(N)

Y = []
for i in range(N):
 Y.append((X[i],i))
Y.sort()

for i in range(N-1):
 if(Y[i+1][0]-Y[i][0]<=K):
  uf.union(Y[i][1],Y[i+1][1])

A = []
B = []

for i in range(P):
 a,b = [int(i) for i in input().split()]
 A.append(a-1)
 B.append(b-1)

for i in range(P):
 pa = uf.find(A[i])
 pb = uf.find(B[i])
 if(pa==pb):
  ans.append('Yes')
 else:
  ans.append('No')

for i in ans:
 print(i)


Solve in Python:
Nobody outside the cooking community knows that Chef is a big fan of Chefgram™ — a social network where chefs and cooks upload their secret kitchen photos.
Recently Chef clicked a beautiful photo, which is represented using 10 pixels in a single row. Respecting Chefgram™'s boolean roots, every pixel is either white or black.

Chefgram™ has N filters. Every filter is a string containing 10 symbols. Every symbol is either '+' or '-'.

- A '+' at the ith position in a filter means that if Chef applies this filter to his photo, the ith pixel will be inverted: it becomes black if it was originally white, and vice versa.
- A '-' at the ith position in a filter string means that if Chef applies this filter to his photo, the ith pixel will remain unchanged.

Chef can apply as many filters as he wants from a list. He can pick any subset of filters and consequently apply them to a photo.

For example:

- Imagine that Chef has a photo "bbwwbbwwbb" (where 'b' stands for black and 'w' stands for white).
- He applies filters "++--++--++", "-+-+-+-+-+".
- Applying the first filter will transform his picture to "wwwwwwwwww".
- Applying the second filter on the transformed picture will give Chef the picture "wbwbwbwbwb".

Even if Chefgram™ has two or more identical filters, they are still considered different!

Chef is extremely interested in knowing how many different subsets of all the Chefgram™ filters can he apply to transform his photo into 10 black pixels?

-----Input-----
- The first line of input contains a single integer T — the number of test cases.
- First line of each test case contains a string S. Each symbol is either 'b' or 'w'. This is Chef's photo.
- Second line of each test case contains a single integer N — the number of Chefgram™ filters.
- Each of the next N lines contains a single string Fi, each symbol of which is either '+' or '-'. This string is the ith Chefgram™ filter.

-----Output-----
- For each test case, output a single line containing a single integer — answer to Chef's question modulo...

def evaluate(a, b):
	ans = ''
	for i in range(0, len(a)):
		if a[i] == b[i]:
			ans += '-'
		else:
			ans += '+'
	return ans

def dp(p_bar, n, s):
	mod = 10**7 + 9
	if n == 0:
		return 0
	elif n == 1:
		k = 0
		if p_bar == s[0]:
			k += 1
		if p_bar == "----------":
			k += 1
		return k
	else:
		return (dp(p_bar, n-1, s)%mod + dp(evaluate(p_bar, s[n-1]), n-1, s))%mod

t = int(input())

for i in range(0, t):
	p = input()
	n = int(input())
	s = []
	for j in range(0, n):
		temp = input()
		s.append(temp)
	p_bar = ''
	for j in p:
		if j == 'w':
			p_bar += '+'
		else:
			p_bar += '-'
	print(dp(p_bar, n, s))


Solve in Python:
Normally, the factorial of a positive integer n is the product of all positive integers less than or equal to n.  For example, factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1.
We instead make a clumsy factorial: using the integers in decreasing order, we swap out the multiply operations for a fixed rotation of operations: multiply (*), divide (/), add (+) and subtract (-) in this order.
For example, clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1.  However, these operations are still applied using the usual order of operations of arithmetic: we do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right.
Additionally, the division that we use is floor division such that 10 * 9 / 8 equals 11.  This guarantees the result is an integer.
Implement the clumsy function as defined above: given an integer N, it returns the clumsy factorial of N.

Example 1:
Input: 4
Output: 7
Explanation: 7 = 4 * 3 / 2 + 1

Example 2:
Input: 10
Output: 12
Explanation: 12 = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1

Note:

1 <= N <= 10000
-2^31 <= answer <= 2^31 - 1  (The answer is guaranteed to fit within a 32-bit integer.)

class Solution:
    def clumsy(self, N: int) -> int:

        res = 0
        for i in range(N, 0, -4):
            if i >= 4:
                if i == N:
                    res += i * (i-1) // (i-2) + (i-3)
                else:
                    res -= i * (i-1) // (i-2) - (i-3)
            #print(res)

        neg = [1, -1][int(N >= 4)]

        if N % 4 == 3:
            res += 6 * neg
        elif N % 4 == 2:
            res += 2 * neg
        elif N % 4 == 1:
            res += 1 * neg
        return int(res)


Solve in Python:
Normally, we decompose a number into binary digits by assigning it with powers of 2, with a coefficient of `0` or `1` for each term:

`25 = 1*16 + 1*8 + 0*4 + 0*2 + 1*1`

The choice of `0` and `1` is... not very binary. We shall perform the *true* binary expansion by expanding with powers of 2, but with a coefficient of `1` or `-1` instead:

`25 = 1*16 + 1*8 + 1*4 - 1*2 - 1*1`

Now *this* looks binary.

---

Given any positive number `n`, expand it using the true binary expansion, and return the result as an array, from the most significant digit to the least significant digit.

`true_binary(25) == [1,1,1,-1,-1]`

It should be trivial (the proofs are left as an exercise to the reader) to see that:

- Every odd number has infinitely many true binary expansions
- Every even number has no true binary expansions

Hence, `n` will always be an odd number, and you should return the *least* true binary expansion for any `n`.

Also, note that `n` can be very, very large, so your code should be very efficient.

def true_binary(n):
    temp=bin(n)[2:]
    res=[]
    for i in temp[-1]+temp[:-1]:
        res.append(1) if i=="1" else res.append(-1)
    return res


Solve in Python:
Not considering number 1, the integer 153 is the first integer having this property:
the sum of the third-power of each of its digits  is equal to 153. Take a look:
153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153

The next number that experiments this particular behaviour is 370 with the same power.

Write the function `eq_sum_powdig()`, that finds the numbers below a given upper limit `hMax` that fulfill this property but with different exponents as a power for the digits.

eq_sum_powdig(hMax, exp): ----> sequence of numbers (sorted list) (Number one should not be considered).

Let's see some cases:
```python
eq_sum_powdig(100, 2) ----> []

eq_sum_powdig(1000, 2) ----> []

eq_sum_powdig(200, 3) ----> [153]

eq_sum_powdig(370, 3) ----> [153, 370]
```
Enjoy it !!

def eq_sum_powdig(hMax, exp):
    ret = []
    for i in range(10, hMax + 1):
        if i == sum(int(j) ** exp for j in str(i)):
            ret.append(i)
    return ret


Solve in Python:
Not everyone probably knows that Chef has younder brother Jeff. Currently Jeff learns to read.
He knows some subset of the letter of Latin alphabet. In order to help Jeff to study, Chef gave him a book with the text consisting of N words. Jeff can read a word iff it consists only of the letters he knows.
Now Chef is curious about which words his brother will be able to read, and which are not. Please help him!

-----Input-----
The first line of the input contains a lowercase Latin letter string S, consisting of the letters Jeff can read. Every letter will appear in S no more than once.
The second line of the input contains an integer N denoting the number of words in the book.
Each of the following N lines contains a single lowecase Latin letter string Wi, denoting the ith word in the book.

-----Output-----
For each of the words, output "Yes" (without quotes) in case Jeff can read it, and "No" (without quotes) otherwise.

-----Constraints-----
- 1 ≤ |S| ≤ 26
- 1 ≤ N ≤ 1000
- 1 ≤ |Wi| ≤ 12
- Each letter will appear in S no more than once.
- S, Wi consist only of lowercase Latin letters.

-----Subtasks-----
- Subtask #1 (31 point): |S| = 1, i.e. Jeff knows only one letter.
- Subtask #2 (69 point)	: no additional constraints

-----Example-----
Input:act
2
cat
dog

Output:Yes
No

-----Explanation-----
The first word can be read.
The second word contains the letters d, o and g that aren't known by Jeff.

def correct_string(s):
 a = set(s)
 if len(a) == len(s):
  return 1
 return 0

s = input()
if correct_string(s):
 s = sorted(s)
 s1 = "".join(s)
 n = int(input())
 if (n >= 1 and n <= 1000):
  for x in range(0,n):
   v = input()
   v = set(v)
   lw = len(v)
   if lw >= 1 and lw <= 12:
    v = sorted(v)
    s2 = "".join(v)
    if s1 == s2:
     print("Yes")
    else:
     print("No")
   pass


Solve in Python:
Note : Issues Fixed with python 2.7.6 , Use any one you like :D , ( Thanks to

Time , time , time . Your task is to write a function that will return the degrees on a analog clock from a digital time that is passed in as parameter . The digital time is type string and will be in the format 00:00 . You also need to return the degrees on the analog clock in type string and format 360:360 . Remember to round of the degrees . Remeber the basic time rules and format like 24:00 = 00:00 and 12:60 = 13:00 . Create your own validation that should return "Check your time !" in any case the time is incorrect or the format is wrong , remember this includes passing in negatives times like "-01:-10".
```
A few examples :
clock_degree("00:00") will return : "360:360"
clock_degree("01:01") will return : "30:6"
clock_degree("00:01") will return : "360:6"
clock_degree("01:00") will return : "30:360"
clock_degree("01:30") will return : "30:180"
clock_degree("24:00") will return : "Check your time !"
clock_degree("13:60") will return : "Check your time !"
clock_degree("20:34") will return : "240:204"
```
Remember that discrete hour hand movement is required - snapping to each hour position and also coterminal angles are not allowed. Goodluck and Enjoy !

def clock_degree(s) :
    hours, minutes = map(lambda str: int(str), s.split(':'))
    if hours < 0 or minutes < 0 or hours > 23 or minutes > 59:
        return "Check your time !"

    return  str((hours % 12 or 12) * 30) + ':' + str((minutes or 60) * 6)


Solve in Python:
Note : This question carries $100$ $points$
CodeLand is celebrating a festival by baking cakes! In order to avoid wastage, families follow a unique way of distributing cakes.
For $T$ families in the locality, $i$-th family (1 <= $i$ <= $T$) has $N$ members. They baked $S$ slices of cakes. The smallest member of the family gets $K$ slices of cakes. Each family has a lucky number of $R$ and they agree to distribute the slices such that the member gets $R$ times more slices than the member just smaller than them. Since the family is busy in festival preparations, find out if the number of slices would be sufficient for the family or not. Also, find how many extra slices they have or how many slices are they short of.
Also, the locality is kind and believes in sharing. So, you also need to determine if each family would have sufficient slices if families shared their cakes among each other!

-----Input :-----
- First line of input will have a single integer $T$ i.e. the number of families in the locality
- For next $T$ lines, each line will describe one family through 4 integers i.e. $S$, $N$, $K$, $R$ separated by spaces

-----Output-----
- First $T$ lines of output will show if slices are enough for the family or not, followed by extra or required slices. For example, if slices are sufficient, the output would be $POSSIBLE$ $10$ which implies 10 slices are extra. If slices are insufficient, the output would be $IMPOSSIBLE$ $15$ which implies 15 slices are required to fulfill the requirement.
- Last line of output would be $IMPOSSIBLE$ or $POSSIBLE$ depending on whether each family would get enough slices after sharing.

-----Constraints:-----
- 1 ≤ $T$ ≤ 50
- 1 ≤ $N$ ≤ 15
- 1 ≤ $S$ ≤ 10^9
- 1 ≤ $K$ ≤ 5
- 1 ≤ $R$ ≤ 5

-----Sample Input:-----
5
100 4 2 2
100 4 3 2
100 4 3 3
200 4 4 2
10 3 2 2

-----Sample Output:-----
POSSIBLE 70
POSSIBLE 55
IMPOSSIBLE 20
POSSIBLE 140
IMPOSSIBLE 4
POSSIBLE

-----Explanation-----
For the first home, the youngest member has got 2 slices, the one older than them gets 2 times more...

# cook your dish here
t=int(input())
extra=0
required=0
while t>0:
    s,n,k,r=list(map(int,input().split()))
    sum1=k
    pro=k
    for i in range(1,n):
        pro=pro*r
        sum1+=pro
    z=s-sum1
    if z>=0:
        extra+=z
        print("POSSIBLE",z)
    else:
        z=z*(-1)
        required+=z
        print("IMPOSSIBLE",z)
    t-=1
if extra-required>=0:
    print("POSSIBLE")
else:
    print("IMPOSSIBLE")


Solve in Python:
Note : This question carries $150$ $points$
There is an outcry in Middle Earth, as the greatest war between Orgs of Dark Lord Sauron and Frodo Baggins is about to begin. To end the war, Frodo decides to destroy the ring in the volcano of Mordor. There are many ships that lead Frodo to Mordor, and he is confused about which one he should board.  Given two-ship numbers $M$ and $N$, Frodo has to solve a problem to find the ship which he should board.
Find the number of pairs (x, y), such that $1<=x<=M$ and $1<=y<=N$, for which $x*y + x+ y = string(x)+string(y)$ is true.
Also, calculate the number of distinct x satisfying the given condition.  The number of pairs and the number of distinct x will help select Frodo the boat he should board. Help Frodo defeat Sauron.

-----Input :-----
- First line contains $T$ as number of test cases
- Each test case contains two integers $M$ and $N$

-----Output :-----
- For each test case, print two integers - the number of such pairs (x,y) and the number of distinct x

-----Constraints :-----
- 1 ≤ T ≤ 5000
- 1 ≤  M, N ≤ 10^9

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

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

-----Explanation :-----
For test case two M=1 and N=9  Pair (1,9) satisfies the above condition 1*9+1+9= “19” and only x=1 satisfies the equation.

for i in range(int(input())):
    m,n = list(map(int,input().split()))
    if n<9:
        print(0,0)
        continue
    k = len(str(n))
    if n==int(str(9)*k):
        ans = k
    else:
        ans = k-1
    print(m*ans,m)
    #     res = min(m,n)
    #     res1 = res
    #     k+=1
    # else:
    #     res1 =

    # n = n//10
    # j = 1
    # while n>0:
    #     if ans==0:
    #         ans = 9*(k-j)
    #     else:
    #         temp = (ans*10+9)*(k-j)
    #         ans = ans+ min(temp,m)
    #     j+=1
    #     n = n//10
    # ans = ans+res
    # print(ans)


Solve in Python:
Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $y$ Koa selects must be strictly greater alphabetically than $x$ (read statement for better understanding). You can make hacks in these problems independently.

Koa the Koala has two strings $A$ and $B$ of the same length $n$ ($|A|=|B|=n$) consisting of the first $20$ lowercase English alphabet letters (ie. from a to t).

In one move Koa:

  selects some subset of positions $p_1, p_2, \ldots, p_k$ ($k \ge 1; 1 \le p_i \le n; p_i \neq p_j$ if $i \neq j$) of $A$ such that $A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$ (ie. all letters on this positions are equal to some letter $x$).

  selects a letter $y$ (from the first $20$ lowercase letters in English alphabet) such that $y>x$ (ie. letter $y$ is strictly greater alphabetically than $x$).

  sets each letter in positions $p_1, p_2, \ldots, p_k$ to letter $y$. More formally: for each $i$ ($1 \le i \le k$) Koa sets $A_{p_i} = y$.

 Note that you can only modify letters in string $A$.

Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($A = B$) or to determine that there is no way to make them equal. Help her!

-----Input-----

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

The first line of each test case contains one integer $n$ ($1 \le n \le 10^5$) — the length of strings $A$ and $B$.

The second line of each test case contains string $A$ ($|A|=n$).

The third line of each test case contains string $B$ ($|B|=n$).

Both strings consists of the first $20$ lowercase English alphabet letters (ie. from a to t).

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

-----Output-----

For each test case:

Print on a single line the smallest number of moves she has to do to make strings equal to each other ($A = B$) or $-1$ if there is no way to...

import sys
input = sys.stdin.readline

t=int(input())
for tests in range(t):
    n=int(input())
    A=input().strip()
    B=input().strip()

    for i in range(n):
        if A[i]>B[i]:
            print(-1)
            break
    else:
        DICT=dict()

        for i in range(n):
            a=A[i]
            b=B[i]

            if a==b:
                continue

            if a in DICT:
                DICT[a].add(b)
            else:
                DICT[a]={b}

        #print(DICT)

        ANS=0

        for x in "abcdefghijklmnopqrst":
            if x in DICT and DICT[x]!=set():
                ANS+=1
                MIN=min(DICT[x])
                if MIN in DICT:
                    DICT[MIN]=DICT[MIN]|DICT[x]-{MIN}
                else:
                    DICT[MIN]=DICT[x]-{MIN}
        print(ANS)


Solve in Python:
Note: This kata is inspired by [Convert a Number to a String!](http://www.codewars.com/kata/convert-a-number-to-a-string/). Try that one too.

## Description

We need a function that can transform a string into a number. What ways of achieving this do you know?

Note: Don't worry, all inputs will be strings, and every string is a perfectly valid representation of an integral number.

## Examples

```python
stringToNumber("1234") == 1234
stringToNumber("605" ) == 605
stringToNumber("1405") == 1405
stringToNumber("-7"  ) == -7
```


Solve in Python:
Now that Chef has finished baking and frosting his cupcakes, it's time to package them. Chef has N cupcakes, and needs to decide how many cupcakes to place in each package. Each package must contain the same number of cupcakes. Chef will choose an integer A between 1 and N, inclusive, and place exactly A cupcakes into each package.  Chef makes as many packages as possible. Chef then gets to eat the remaining cupcakes. Chef enjoys eating cupcakes very much. Help Chef choose the package size A that will let him eat as many cupcakes as possible.

-----Input-----

Input begins with an integer T, the number of test cases. Each test case consists of a single integer N, the number of cupcakes.

-----Output-----

For each test case, output the package size that will maximize the number of leftover cupcakes. If multiple package sizes will result in the same number of leftover cupcakes, print the largest such size.

-----Constraints-----
- 1 ≤ T ≤ 1000
- 2 ≤ N ≤ 100000000 (108)

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

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

-----Explanation-----

In the first test case, there will be no leftover cupcakes regardless of the size Chef chooses, so he chooses the largest possible size.  In the second test case, there will be 2 leftover cupcakes.

for _ in range (int(input())):
    n = int(input())
    print(n//2+1)


Solve in Python:
Now that Heidi has made sure her Zombie Contamination level checker works, it's time to strike! This time, the zombie lair is a strictly convex polygon on the lattice. Each vertex of the polygon occupies a point on the lattice. For each cell of the lattice, Heidi knows the level of Zombie Contamination – the number of corners of the cell that are inside or on the border of the lair.

Given this information, Heidi wants to know the exact shape of the lair to rain destruction on the zombies. Help her!

[Image]

-----Input-----

The input contains multiple test cases.

The first line of each test case contains one integer N, the size of the lattice grid (5 ≤ N ≤ 500). The next N lines each contain N characters, describing the level of Zombie Contamination of each cell in the lattice. Every character of every line is a digit between 0 and 4.

Cells are given in the same order as they are shown in the picture above: rows go in the decreasing value of y coordinate, and in one row cells go in the order of increasing x coordinate. This means that the first row corresponds to cells with coordinates (1, N), ..., (N, N) and the last row corresponds to cells with coordinates (1, 1), ..., (N, 1).

The last line of the file contains a zero. This line should not be treated as a test case. The sum of the N values for all tests in one file will not exceed 5000.

-----Output-----

For each test case, give the following output:

The first line of the output should contain one integer V, the number of vertices of the polygon that is the secret lair. The next V lines each should contain two integers, denoting the vertices of the polygon in the clockwise order, starting from the lexicographically smallest vertex.

-----Examples-----
Input
8
00000000
00000110
00012210
01234200
02444200
01223200
00001100
00000000
5
00000
01210
02420
01210
00000
7
0000000
0122100
0134200
0013200
0002200
0001100
0000000
0

Output
4
2 3
2 4
6 6
5 2
4
2 2
2 3
3 3
3 2
3
2 5
4 5
4 2

-----Note-----

It is guaranteed that the solution always exists...

import math

def lexComp(a, b):
    if a[0] != b[0]:
        return -1 if a[0] < b[0] else 1
    if a[1] != b[1]:
        return -1 if a[1] < b[1] else 1
    return 0

def turn(a, b, c):
    return (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0])

def dist2(a, b):
    return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2

def solve(n):
    a = [list(map(int, input())) for _ in range(n)]
    points = []
    for i in range(n):
        for j in range(n):
            if a[i][j] == 1:
                curPoints = []
                for dx in range(0, 2):
                    for dy in range(0, 2):
                        ok = True
                        for ddx in range(0, 2):
                            for ddy in range(0, 2):
                                x, y = i - 1 + dx + ddx, j - 1 + dy + ddy
                                if 0 <= x < n and 0 <= y < n and a[x][y] == 0:
                                    ok = False
                        if ok:
                            curPoints.append((i + dx, j + dy))
                points.append(curPoints[0])
    points = list(set(points))
    for i in range(1, len(points)):
        if lexComp(points[0], points[i]) > 0:
            points[0], points[i] = points[i], points[0]
    points[1:] = sorted(points[1:], key=lambda p: (math.atan2(p[1] - points[0][1], p[0] - points[0][0]), dist2(p, points[0])))
    hull = []
    for p in points:
        while len(hull) >= 2 and turn(hull[-2], hull[-1], p) <= 0:
            hull.pop()
        hull.append(p)
    hull = [(p[1], n - p[0]) for p in hull]
    hull = hull[::-1]
    start = 0
    for i in range(1, len(hull)):
        if lexComp(hull[i], hull[start]) < 0:
            start = i
    newHull = hull[start:]
    newHull.extend(hull[:start])
    hull = newHull
    print(len(hull))
    for p in hull:
        print(p[0], p[1])

while True:
    n = int(input())
    if n == 0:
        break
    solve(n)


Solve in Python:
Now we will confect a reagent. There are eight materials to choose from, numbered 1,2,..., 8 respectively.

We know the rules of confect:
```
material1 and material2 cannot be selected at the same time
material3 and material4 cannot be selected at the same time
material5 and material6 must be selected at the same time
material7 or  material8 must be selected(at least one, or both)
```

# Task

You are given a integer array `formula`. Array contains only digits 1-8 that represents material 1-8. Your task is to determine if the formula is valid. Returns `true` if it's valid, `false` otherwise.

# Example

For `formula = [1,3,7]`, The output should be `true`.

For `formula = [7,1,2,3]`, The output should be `false`.

For `formula = [1,3,5,7]`, The output should be `false`.

For `formula = [1,5,6,7,3]`, The output should be `true`.

For `formula = [5,6,7]`, The output should be `true`.

For `formula = [5,6,7,8]`, The output should be `true`.

For `formula = [6,7,8]`, The output should be `false`.

For `formula = [7,8]`, The output should be `true`.

# Note

- All inputs are valid. Array contains at least 1 digit. Each digit appears at most once.

- Happy Coding `^_^`

def isValid(formula):
    m = [0, 1, 2, 3, 4, 5, 6, 7, 8]
    t = []

    def mat1_mat2():
        ## material1 and material2 cannot be selected at the same time
        count = 0
        for i in formula:
            if i == 1:
                count+=1
            if i == 2:
                count+=1
        if count == 0:
            t.append(True)
        elif count == 1:
            t.append(True)
        else:
            t.append(False)

    def mat3_mat4():
        ## material3 and material4 cannot be selected at the same time
        count = 0
        for i in formula:
            if i == 3:
                count+=1
            if i == 4:
                count+=1
        if count == 0:
            t.append(True)
        elif count == 1:
            t.append(True)
        else:
            t.append(False)

    def mat5_mat6():
        # material5 and material6 must be selected at the same time
        count = 0
        for i in formula:
            if i == 5:
                count+=1
            if i == 6:
                count+=1
        if count == 0:
            t.append(True)
        elif count == 1:
            t.append(False)
        else:
            t.append(True)

    def mat7_mat8():
        # material7 or material8 must be selected(at least one, or both)
        count = 0
        for i in formula:
            if i == 7:
                count+=1
            if i == 8:
                count+=1
        if count == 1:
            t.append(True)
        elif count == 2:
            t.append(True)
        else:
            t.append(False)

    mat1_mat2()
    mat3_mat4()
    mat5_mat6()
    mat7_mat8()

    return all(t)


Solve in Python:
Now you have to write a function that takes an argument and returns the square of it.

def square(n):
    return int(n) * int(n)


Solve in Python:
Now-a-days, Manish is becoming  famous for bank robbery in the country because of his cleverness, he never robs own his own.He has four workers A , B, C, and D , all working under him.All of the four take some amount for that. There are total N banks in the country and Manish wants to rob all the banks with minimum

amount spent on workers.Only one worker is allowed to rob the ith bank but following a condition that if one worker robs ith bank, then he can't rob (i+1) th bank.

So ,Manish wants you to calculate minimum amount that he has to spend on all workers to rob all N banks.

-----Input Format-----
First line consists number of test cases T.For each test case,

first line consists an integer N, number of banks in the country

and the next N line consists 4 integers amount taken by A,B,C and D respectively to rob ith bank.

-----Output format-----
For each test case ,output an integer, minimum amount paid  by Manish in separate line .

-----Constraint-----
- 1<=T<=1000
- 1<=N<=100000
- 1<=amount<=100000

-----Subtasks-----
Subtask-1 (10 points)
- 1<=T<=5
- 1<=N<=10
- 1<=amount<=10
Subtask-1 (30 points)
- 1<=T<=100
- 1<=N<=1000
- 1<=amount<=1000
Subtask-1 (60 points)
Original Constraints
Sample Input
1
3
4 7 2 9
5 6 4 7
2 6 4 3

Sample Output
10

for t in range( eval(input()) ) :
 dp = [ [0 for i in range(4)] for j in range(2) ]
 ret = 1
 for u in range( eval(input()) ) :
  c = list(map( int, input().split() ))
  for i in range( 4 ) :
   dp[u&1][i] = 1e18
   for j in range( 4 ) :
    if j != i :
     dp[u&1][i] = min( dp[u&1][i], c[j] + dp[1-(u&1)][j])
     ret = min(dp[u&1])
 print(ret)


Solve in Python:
Number is a palindrome if it is equal to the number with digits in reversed order.
For example, 5, 44, 171, 4884 are palindromes and 43, 194, 4773 are not palindromes.

Write a method `palindrome_chain_length` which takes a positive number and returns the number of special steps needed to obtain a palindrome. The special step is: "reverse the digits, and add to the original number". If the resulting number is not a  palindrome, repeat the procedure with the sum until the resulting number is a palindrome.

If the input number is already a palindrome, the number of steps is 0.

Input will always be a positive integer.

For example, start with 87:

87 + 78 = 165;
165 + 561 = 726;
 726 + 627 = 1353;
1353 + 3531 = 4884

4884 is a palindrome and we needed 4 steps to obtain it, so `palindrome_chain_length(87) == 4`

def palindrome_chain_length(n):
    run = 0
    word = str(n)
    revers = word[::-1]
    while word != revers:
        word = str(int(word) + int(word[::-1]))
        revers = word[::-1]
        run += 1
    return run


Solve in Python:
Numbers $1, 2, 3, \dots n$ (each integer from $1$ to $n$ once) are written on a board. In one operation you can erase any two numbers $a$ and $b$ from the board and write one integer $\frac{a + b}{2}$ rounded up instead.

You should perform the given operation $n - 1$ times and make the resulting number that will be left on the board as small as possible.

For example, if $n = 4$, the following course of action is optimal:  choose $a = 4$ and $b = 2$, so the new number is $3$, and the whiteboard contains $[1, 3, 3]$;  choose $a = 3$ and $b = 3$, so the new number is $3$, and the whiteboard contains $[1, 3]$;  choose $a = 1$ and $b = 3$, so the new number is $2$, and the whiteboard contains $[2]$.

It's easy to see that after $n - 1$ operations, there will be left only one number. Your goal is to minimize it.

-----Input-----

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

The only line of each test case contains one integer $n$ ($2 \le n \le 2 \cdot 10^5$) — the number of integers written on the board initially.

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

-----Output-----

For each test case, in the first line, print the minimum possible number left on the board after $n - 1$ operations. Each of the next $n - 1$ lines should contain two integers — numbers $a$ and $b$ chosen and erased in each operation.

-----Example-----
Input
1
4

Output
2
2 4
3 3
3 1

#dt = {} for i in x: dt[i] = dt.get(i,0)+1
import sys;input = sys.stdin.readline
#import io,os; input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline #for pypy
inp,ip = lambda :int(input()),lambda :[int(w) for w in input().split()]

for _ in range(inp()):
    n = inp()
    prev = n
    print(2)
    for i in range(n-1,0,-1):
        print(i,prev)
        prev = (i+prev-1)//2 +1


Solve in Python:
OK, my warriors! Now that you beat the big BOSS, you can unlock three new skills. (Does it sound like we're playing an RPG? ;-)

## The Arrow Function (JS only)

The first skill is the arrow function. Let's look at some examples to see how it works:

```python
#ignore this part, it is just for JS
```
As you can see, its syntax is:

```python
#ignore this part, it is just for JS
```
If only one parameter exists on the left side of the arrow, the bracket can be omitted. If only one expression exists on the right side of the arrow, the curly braces can also be omitted. The example below shows a function with the () and {} omitted.

```python
#ignore this part, it is just for JS
```
If the right side of the arrow is a complex statement, you must use curly braces:

```python
#ignore this part, it is just for JS
```
So far, our examples have used function assignment. However, an arrow function can also be used as a parameter to a function call, as well. When used as a parameter, the arrow function does not require a name. Let's rewrite the string.replace() example we saw from a previous training using our new skill:

```python
#ignore this part, it is just for JS
```
String.replace takes a regular expression and a function. The function is invoked on each substring matching the regex, and return the string replacement of that match. In this case, the arrow function takes the matched string as the parameter ```x```, and returns the upper cased value of ```x```.

In the soon to learn the arrayObject and its methods, there are many applications on the arrow function, which is the reason we first learn the arrow function. The arrow function has more complex usage and usage restrictions, but we don't need to learn to be so deep, so we only learn the contents of the above.

## The Spread Operator

The second skill is the ```spread operator```. The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

It looks...

shuffle_it = si = lambda l, *a: l if not a or len(a[0]) == 0 else si([x if not i in a[0] else l[a[0][0]] if i == a[0][1] else l[a[0][1]] for i, x in enumerate(l)],*a[1:])


Solve in Python:
Oh no!  You have stumbled upon a mysterious signal consisting of beeps of various lengths, and it is of utmost importance that you find out the secret message hidden in the beeps.  There are long and short beeps, the longer ones roughly three times as long as the shorter ones.  Hmm... that sounds familiar.

That's right: your job is to implement a decoder for the Morse alphabet.  Rather than dealing with actual beeps, we will use a common string encoding of Morse.  A long beep is represened by a dash (`-`) and a short beep by a dot (`.`).  A series of long and short beeps make up a letter, and letters are separated by spaces (` `).  Words are separated by double spaces.

You should implement the International Morse Alphabet.  You need to support letters a-z and digits 0-9 as follows:

    a .-      h ....    o ---     u ..-      1 .----     6 -....
    b -...    i ..      p .--.    v ...-     2 ..---     7 --...
    c -.-.    j .---    q --.-    w .--      3 ...--     8 ---..
    d -..     k -.-     r .-.     x -..-     4 ....-     9 ----.
    e .       l .-..    s ...     y -.--     5 .....     0 -----
    f ..-.    m --      t -       z --..
    g --.     n -.

## Examples

    .... . .-.. .-.. ---  .-- --- .-. .-.. -..   → "hello world"
    .---- ... -  .- -. -..  ..--- -. -..         → "1st and 2nd"

```if:python
A dictionnary `TOME` is preloaded for you, with the information above to convert morse code to letters.
```
```if:javascrip
An object `TOME` is preloaded for you, with the information above to convert morse code to letters.
```
```if:ruby
A Hashmap `$dict` is preloaded for you, with the information above to convert morse code to letters.
```


Solve in Python:
Oh no! Ghosts have reportedly swarmed the city. It's your job to get rid of them and save the day!

In this kata, strings represent buildings while whitespaces within those strings represent ghosts.

So what are you waiting for? Return the building(string) without any ghosts(whitespaces)!

Example:

Should return:

If the building contains no ghosts, return the string:

def ghostbusters(building):
    stripped = building.replace(' ', '')
    return stripped if building != stripped else "You just wanted my autograph didn't you?"


Solve in Python:
Oleg the bank client and Igor the analyst are arguing again. This time, they want to pick a gift as a present for their friend, ZS the coder. After a long thought, they decided that their friend loves to eat carrots the most and thus they want to pick the best carrot as their present.

There are n carrots arranged in a line. The i-th carrot from the left has juiciness a_{i}. Oleg thinks ZS loves juicy carrots whereas Igor thinks that he hates juicy carrots. Thus, Oleg would like to maximize the juiciness of the carrot they choose while Igor would like to minimize the juiciness of the carrot they choose.

To settle this issue, they decided to play a game again. Oleg and Igor take turns to play the game. In each turn, a player can choose a carrot from either end of the line, and eat it. The game ends when only one carrot remains. Oleg moves first. The last remaining carrot will be the carrot that they will give their friend, ZS.

Oleg is a sneaky bank client. When Igor goes to a restroom, he performs k moves before the start of the game. Each move is the same as above (eat a carrot from either end of the line). After Igor returns, they start the game with Oleg still going first.

Oleg wonders: for each k such that 0 ≤ k ≤ n - 1, what is the juiciness of the carrot they will give to ZS if he makes k extra moves beforehand and both players play optimally?

-----Input-----

The first line of input contains a single integer n (1 ≤ n ≤ 3·10^5) — the total number of carrots.

The next line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9). Here a_{i} denotes the juiciness of the i-th carrot from the left of the line.

-----Output-----

Output n space-separated integers x_0, x_1, ..., x_{n} - 1. Here, x_{i} denotes the juiciness of the carrot the friends will present to ZS if k = i.

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

Output
3 3 5 5

Input
5
1000000000 1000000000 1000000000 1000000000 1

Output
1000000000 1000000000 1000000000 1000000000 1000000000

-----Note-----

For the first...

def evens(A):
    n = len(A)
    l = n//2-1; r = n//2
    if len(A)%2 == 1: l+= 1
    ans = [max(A[l], A[r])]
    while r < n-1:
        l-= 1; r+= 1
        ans.append(max(ans[-1], A[l], A[r]))
    return ans

def interleave(A, B):
    q = []
    for i in range(len(B)): q+= [A[i], B[i]]
    if len(A) != len(B): q.append(A[-1])
    return q

n = int(input())
A = list(map(int,input().split()))
M = [min(A[i],A[i+1]) for i in range(n-1)]
ansA = evens(A)
ansM = evens(M) if n>1 else []
if n%2 == 0: print(*interleave(ansA, ansM[1:]), max(A))
else: print(*interleave(ansM, ansA[1:]), max(A))