Solve in Python:
Suzuki needs help lining up his students!

Today Suzuki will be interviewing his students to ensure they are progressing in their training. He decided to schedule the interviews based on the length of the students name in descending order. The students will line up and wait for their turn.

You will be given a string of student names. Sort them and return a list of names in descending order.

Here is an example input:
```python
string = 'Tadashi Takahiro Takao Takashi Takayuki Takehiko Takeo Takeshi Takeshi'
```
Here is an example return from your function:

```python
 lst = ['Takehiko',
        'Takayuki',
        'Takahiro',
        'Takeshi',
        'Takeshi',
        'Takashi',
        'Tadashi',
        'Takeo',
        'Takao']
```

Names of equal length will be returned in reverse alphabetical order (Z->A) such that:

```python
string = "xxa xxb xxc xxd xa xb xc xd"

```
Returns

```python
['xxd', 'xxc', 'xxb', 'xxa', 'xd', 'xc', 'xb', 'xa']

```
Please also try the other Kata in this series..

* [Help Suzuki count his vegetables...](https://www.codewars.com/kata/56ff1667cc08cacf4b00171b)
* [Help Suzuki purchase his Tofu!](https://www.codewars.com/kata/57d4ecb8164a67b97c00003c)
* [Help Suzuki pack his coal basket!](https://www.codewars.com/kata/57f09d0bcedb892791000255)
* [Help Suzuki rake his garden!](https://www.codewars.com/kata/571c1e847beb0a8f8900153d)
* [How many stairs will Suzuki climb in 20 years?](https://www.codewars.com/kata/56fc55cd1f5a93d68a001d4e)

def lineup_students(names):
    return sorted(names.split(), key=lambda s: (len(s), s), reverse=True)


Solve in Python:
Switch/Case - Bug Fixing #6

Oh no! Timmy's evalObject function doesn't work. He uses Switch/Cases to evaluate the given properties of an object, can you fix timmy's function?

def eval_object(v):

    if v['operation'] == "+":
        return v['a']+v['b']
    elif v['operation'] == "-":
        return v['a']-v['b']
    elif v['operation'] == "/":
        return v['a']/v['b']
    elif v['operation'] == '*':
        return v['a']*v['b']
    elif v['operation'] == '%':
        return v['a']%v['b']
    elif v['operation'] == "**":
        return v['a']**v['b']


Solve in Python:
T is playing a game with his friend, HL.

There are $n$ piles of stones, the $i$-th pile initially has $a_i$ stones.

T and HL will take alternating turns, with T going first. In each turn, a player chooses a non-empty pile and then removes a single stone from it. However, one cannot choose a pile that has been chosen in the previous turn (the pile that was chosen by the other player, or if the current turn is the first turn then the player can choose any non-empty pile). The player who cannot choose a pile in his turn loses, and the game ends.

Assuming both players play optimally, given the starting configuration of $t$ games, determine the winner of each game.

-----Input-----

The first line of the input contains a single integer $t$ $(1 \le t \le 100)$ — the number of games. The description of the games follows. Each description contains two lines:

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

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ $(1 \le a_i \le 100)$.

-----Output-----

For each game, print on a single line the name of the winner, "T" or "HL" (without quotes)

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

Output
T
HL

-----Note-----

In the first game, T removes a single stone from the only pile in his first turn. After that, although the pile still contains $1$ stone, HL cannot choose from this pile because it has been chosen by T in the previous turn. Therefore, T is the winner.

t=int(input())
for _ in range(t):
  n=int(input())
  a=list(map(int,input().split()))
  t=sum(a)
  flag=0
  for i in range(n):
    if 2*a[i]>t:
      flag=1
      break
  if t%2==1:
    flag=1
  if flag==1:
    print('T')
  else:
    print('HL')


Solve in Python:
Takahashi has an ability to generate a tree using a permutation (p_1,p_2,...,p_n) of (1,2,...,n), in the following process:
First, prepare Vertex 1, Vertex 2, ..., Vertex N.
For each i=1,2,...,n, perform the following operation:
 - If p_i = 1, do nothing.
 - If p_i \neq 1, let j' be the largest j such that p_j < p_i. Span an edge between Vertex i and Vertex j'.
Takahashi is trying to make his favorite tree with this ability.
His favorite tree has n vertices from Vertex 1 through Vertex n, and its i-th edge connects Vertex v_i and w_i.
Determine if he can make a tree isomorphic to his favorite tree by using a proper permutation.
If he can do so, find the lexicographically smallest such permutation.

-----Notes-----
For the definition of isomorphism of trees, see wikipedia. Intuitively, two trees are isomorphic when they are the "same" if we disregard the indices of their vertices.

-----Constraints-----
 - 2 \leq n \leq 10^5
 - 1 \leq v_i, w_i \leq n
 - The given graph is a tree.

-----Input-----
Input is given from Standard Input in the following format:
n
v_1 w_1
v_2 w_2
:
v_{n-1} w_{n-1}

-----Output-----
If there is no permutation that can generate a tree isomorphic to Takahashi's favorite tree, print -1.
If it exists, print the lexicographically smallest such permutation, with spaces in between.

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

-----Sample Output-----
1 2 4 5 3 6

If the permutation (1, 2, 4, 5, 3, 6) is used to generate a tree, it looks as follows:

This is isomorphic to the given graph.

#!/usr/bin/env python3

def solve(n, adj_list, d):

    s = []
    path_adj_list = [[] for _ in range(n)]
    for v in range(n):
        if 1 < d[v]:
            p = path_adj_list[v]
            for w in adj_list[v]:
                if 1 < d[w]:
                    p.append(w)
            if 2 < len(p):
                print((-1))
                return
            if len(p) == 1:
                s.append(v)

    if len(s) == 0:
        ans = [1] + [v for v in range(3, n)] + [2]
        if 2 < n:
            ans += [n]
        print((' '.join(list(map(str, ans)))))
        return

    visited = [False] * n
    v, w = s
    while v != w and d[v] == d[w]:
        visited[v] = True
        visited[w] = True
        f = False
        for nv in path_adj_list[v]:
            if not visited[nv]:
                f = True
                v = nv
                break
        if not f:
            break
        f = False
        for nw in path_adj_list[w]:
            if not visited[nw]:
                f = True
                w = nw
                break
        if not f:
            break

    if d[v] > d[w]:
        v = s[1]
    else:
        v = s[0]

    visited = [False] * n
    visited[v] = True
    ans = [1] + [w for w in range(3, d[v] + 1)] + [2]
    c = d[v]
    v = path_adj_list[v][0]
    while True:
        visited[v] = True
        ans += [w for w in range(c + 2, c + d[v])] + [c + 1]
        c += d[v] - 1
        f = False
        for nv in path_adj_list[v]:
            if not visited[nv]:
                f = True
                v = nv
                break
        if not f:
            break

    ans += [n]

    print((' '.join(list(map(str, ans)))))
    return

def main():
    n = input()
    n = int(n)
    adj_list = [[] for _ in range(n)]
    d = [0] * n
    for _ in range(n - 1):
        v, w = input().split()
        v = int(v) - 1
        w = int(w) - 1
        adj_list[v].append(w)
        adj_list[w].append(v)
        d[v] += 1
        d[w] += 1

    solve(n, adj_list, d)

def...


Solve in Python:
Takaki Tono is a Computer Programmer in Tokyo. His boss at work shows him an online puzzle, which if solved would earn the solver a full expense paid trip to Los Angeles, California. Takaki really wants to solve this, as the love of his life, Akari, lives in Los Angeles and he hasn't met her since four years. Upon reading the puzzle he realizes that it is a query based problem. The problem is as follows :-

You are given a Tree T with N nodes numbered from 1 to N, with each node numbered z having a positive integer Az written on it. This integer denotes the value of the node. You have to process Q queries, of the following forms :-
1) C x y : Report the closest two values in the unique path from x to y i.e compute min(|Ap - Aq|) where p and q are two distinct nodes on the unique path from x to y.

2) F x y : Report the farthest two values in the unique path from x to y i.e. compute max(|Ap - Aq|) where p and q are two distinct nodes on the unique path from x to y.

It is also mentioned that x is not equal to y in any query and that no two nodes have the same value printed on them. Also, |x| denotes the absolute value of x.

Takaki is perplexed and requires your help to solve this task? Can you help him out?

-----Input-----
The first line of the input contains an integer N denoting the number of nodes in tree T.
The second line comprises N space separated integers denoting A, where the i-th integer denotes Ai.
The next N-1 lines each comprise two space separated integers u and v, denoting that node u and node v
are connected by an edge. It is guaranteed that the final graph will be a connected tree.
The next line contains a single integer Q, denoting number of queries.
The next Q lines comprise the queries. Each such line is of the format C x y or F x y.

-----Output-----
For each query, print the required output as mentioned above.

-----Constraints-----
- 2 ≤ N ≤ 35000
- 1 ≤ Ai ≤ 109
- 1 ≤ Q ≤ 35000
- 1 ≤ u, v ≤ N
- No two nodes have the same value printed on them.
- x is not equal to y in any...

MAXX = 10**9+1
N = eval(input())
nodes = list(map(int, input().split(" ")))
edges = [set() for _ in range(N)]
for _ in range(N-1):
    a, b = list(map(int, input().split(" ")))
    edges[a-1].add(b-1)
    edges[b-1].add(a-1)
path = [[] for _ in range(N)]
visited, tovisit = set(), [(0, 0)]
while tovisit:
    p, v = tovisit.pop()
    if v not in visited:
        path[v] = path[p] + [v]
        visited.add(v)
        news = edges[v] - visited
        tovisit.extend([(v, x) for x in news])
# print path

Q = eval(input())
for _ in range(Q):
    q, a, b = input().split(" ")
    a, b = int(a)-1, int(b)-1
    i = 1
    while i < min(len(path[a]), len(path[b])):
        if path[a][i] != path[b][i]: break
        i += 1
    s = path[a][i-1:] + path[b][i:]

    # print s
    if q == "C":
        s = sorted([nodes[i] for i in s])
        d = s[-1] - s[0]
        for i in range(len(s)-1):
            d = min(d, s[i+1]-s[i])
        print(d)
    else:
        M = 0
        m = MAXX
        for i in range(len(s)):
            M = max(M, nodes[s[i]])
            m = min(m, nodes[s[i]])
        print(M - m)
    # print M[(s, l)] - m[(s, l)]


Solve in Python:
Take 2 strings `s1` and `s2` including only letters from `a`to `z`.
Return a new **sorted** string, the longest possible, containing distinct letters,
- each taken only once - coming from s1 or s2.

# Examples:
```
a = "xyaabbbccccdefww"
b = "xxxxyyyyabklmopq"
longest(a, b) -> "abcdefklmopqwxy"

a = "abcdefghijklmnopqrstuvwxyz"
longest(a, a) -> "abcdefghijklmnopqrstuvwxyz"
```

def longest(a1, a2):
    return "".join(sorted(set(a1 + a2)))


Solve in Python:
Take a sentence (string) and reverse each word in the sentence. Do not reverse the order of the words, just the letters in each word.

If there is punctuation, it should be interpreted as a regular character; no special rules.

If there is spacing before/after the input string, leave them there.

String will not be empty.

## Examples

```
"Hi mom" => "iH mom"
" A fun little challenge! " => " A nuf elttil !egnellahc "
```

def reverser(sentence):
    emt = " "
    split_it = sentence.split(" ")
    for word in split_it:
        emt += word[::-1] + " "
    return emt[1:-1]


Solve in Python:
Take a string and return a hash with all the ascii values of the characters in the string.
Returns nil if the string is empty.
The key is the character, and the value is the ascii value of the character.
Repeated characters are to be ignored and non-alphebetic characters as well.

def char_to_ascii(s):
    if s: return {c: ord(c) for c in set(s) if c.isalpha()}


Solve in Python:
Take an input string and return a string that is made up of the number of occurences of each english letter in the input followed by that letter, sorted alphabetically. The output string shouldn't contain chars missing from input (chars with 0 occurence); leave them out.

An empty string, or one with no letters, should return an empty string.

Notes:

* the input will always be valid;
* treat letters as **case-insensitive**

## Examples

```
"This is a test sentence."  ==>  "1a1c4e1h2i2n4s4t"
""                          ==>  ""
"555"                       ==>  ""
```

from collections import Counter

def string_letter_count(s):
    cnt = Counter(c for c in s.lower() if c.isalpha())
    return ''.join(str(n)+c for c,n in sorted(cnt.items()))


Solve in Python:
Take an integer `n (n >= 0)` and a digit `d (0 <= d <= 9)` as an integer. Square all numbers `k (0 <= k <= n)` between 0 and n. Count the numbers of
digits `d` used in the writing of all the `k**2`. Call `nb_dig` (or nbDig or ...) the function taking `n` and `d` as parameters and returning this count.

#Examples:
```
n = 10, d = 1, the k*k are 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100
We are using the digit 1 in 1, 16, 81, 100. The total count is then 4.

nb_dig(25, 1):
the numbers of interest are
1, 4, 9, 10, 11, 12, 13, 14, 19, 21 which squared are 1, 16, 81, 100, 121, 144, 169, 196, 361, 441
so there are 11 digits `1` for the squares of numbers between 0 and 25.
```
Note that `121` has twice the digit `1`.

def nb_dig(n, d):
    l=[]
    for i in range(n+1):
        l.append(str(i**2))
    return ''.join(l).count(str(d))


Solve in Python:
Take debugging to a whole new level:

Given a string, remove every *single* bug.

This means you must remove all instances of the word 'bug' from within a given string, *unless* the word is plural ('bugs').

For example, given 'obugobugobuoobugsoo', you should return 'ooobuoobugsoo'.

Another example: given 'obbugugo', you should return 'obugo'.

Note that all characters will be lowercase.

Happy squishing!

import re

def debug(string):
    return re.sub("bug(?!s)", "", string)


Solve in Python:
Take the following IPv4 address:  128.32.10.1
This address has 4 octets where each octet is a single byte (or 8 bits).

* 1st octet 128 has the binary representation: 10000000
* 2nd octet 32 has the binary representation: 00100000
* 3rd octet 10 has the binary representation: 00001010
* 4th octet 1 has the binary representation: 00000001

So 128.32.10.1 == 10000000.00100000.00001010.00000001

Because the above IP address has 32 bits, we can represent it as the 32
bit number: 2149583361.

Write a function ip_to_int32(ip) ( **JS**: `ipToInt32(ip)` ) that takes an IPv4 address and returns
a 32 bit number.

```python
  ip_to_int32("128.32.10.1") => 2149583361
```

def ip_to_int32(ip):
    """
    Take the following IPv4 address: 128.32.10.1 This address has 4 octets
    where each octet is a single byte (or 8 bits).

    1st octet 128 has the binary representation: 10000000
    2nd octet 32 has the binary representation: 00100000
    3rd octet 10 has the binary representation: 00001010
    4th octet 1 has the binary representation: 00000001
    So 128.32.10.1 == 10000000.00100000.00001010.00000001

    Because the above IP address has 32 bits, we can represent it as
    the 32 bit number: 2149583361.

    Write a function ip_to_int32(ip) ( JS: ipToInt32(ip) ) that takes
    an IPv4 address and returns a 32 bit number.

    ip_to_int32("128.32.10.1") => 2149583361

    """
    addr = ip.split(".")
    res = int(addr[0]) << 24
    res += int(addr[1]) << 16
    res += int(addr[2]) << 8
    res += int(addr[3])
    return res


Solve in Python:
Take the following IPv4 address: `128.32.10.1`

This address has 4 octets where each octet is a single byte (or 8 bits).

* 1st octet `128` has the binary representation: `10000000`
* 2nd octet `32` has the binary representation: `00100000`
* 3rd octet `10` has the binary representation: `00001010`
* 4th octet `1` has the binary representation: `00000001`

So `128.32.10.1` == `10000000.00100000.00001010.00000001`

Because the above IP address has 32 bits, we can represent it as the unsigned 32 bit number: `2149583361`

Complete the function that takes an unsigned 32 bit number and returns a string representation of its IPv4 address.

## Examples
```
2149583361 ==> "128.32.10.1"
32         ==> "0.0.0.32"
0          ==> "0.0.0.0"
```

def int32_to_ip(int32):
    """
    The solution involves bitwise AND of int32 and a mask that we can shift around.
    Say we have the number 17194 (0b0100001100101010). This can be divided into 2
    bytes: 01000011 and 00101010.
    We can AND this with a byte that is filled with 1s - 255 (0b11111111), shifted
    left by a certain amount of bytes to get the digits in that byte:
    01000011 00101010 # 17194
    11111111 00000000 # 255 << 8
    01000011 00000000 # 17194 & 255 << 8
    However, we need to shift this value *back* to get a number within (0,255)
    inclusive, as required, so shift right by the same amount.
    """
    first = (int32 & (255 << 24)) >> 24
    second = (int32 & (255 << 16)) >> 16
    third = (int32 & (255 << 8)) >> 8
    fourth = int32 & 255
    return f"{first}.{second}.{third}.{fourth}"


Solve in Python:
Taking into consideration the [3.5 edition rules](http://www.dandwiki.com/wiki/SRD:Ability_Scores#Table:_Ability_Modifiers_and_Bonus_Spells), your goal is to build a function that takes an ability score (worry not about validation: it is always going to be a non negative integer), will return:

* attribute modifier, as indicated on the table of the above link;
* maximum spell level for the spells you can cast (-1 for no spells at all) with that score;
* the eventual extra spells you might get (as an array/list, with elements representing extra spells for 1st, 2nd,... spell level in order; empty array for no extra spells).

The result needs to be an object (associative array in PHP), as shown in the examples:

```python
char_attribute(0) == {"modifier": 0, "maximum_spell_level": -1, "extra_spells": []}
char_attribute(1) == {"modifier": -5, "maximum_spell_level": -1, "extra_spells": []}
char_attribute(5) == {"modifier": -3, "maximum_spell_level": -1, "extra_spells": []}
char_attribute(10) == {"modifier": 0, "maximum_spell_level": 0, "extra_spells": []}
char_attribute(20) == {"modifier": +5, "maximum_spell_level": 9, "extra_spells": [2,1,1,1,1]}
```

*Note: I didn't explain things in detail and just pointed out to the table on purpose, as my goal is also to train the pattern recognition skills of whoever is going to take this challenges, so do not complain about a summary description. Thanks :)*

In the same series:

* [D&D Character generator #1: attribute modifiers and spells](https://www.codewars.com/kata/d-and-d-character-generator-number-1-attribute-modifiers-and-spells/)
* [D&D Character generator #2: psion power points](https://www.codewars.com/kata/d-and-d-character-generator-number-2-psion-power-points/)
* [D&D Character generator #3: carrying capacity](https://www.codewars.com/kata/d-and-d-character-generator-number-3-carrying-capacity/)

def char_attribute(score):
    modifier = score and (score - 10) // 2
    extra_spells = [i//4 for i in reversed(range(score//2-10, score//2-1)) if i > 3]
    maximum_spell_level = min(score-10, 9) if score >= 10 else -1
    return {
        'modifier': modifier,
        'maximum_spell_level': maximum_spell_level,
        'extra_spells': extra_spells,
    }


Solve in Python:
Tanish is the president of the chemistry club at his school. He considers everyone who doesn't like chemistry as his enemy. After years of research, he has invented a lethal poison, which he named success. Now Tanish plans to kill all his enemies with his success. Success is extremely deadly and is untraceable in small concentrations.
Tanish has $\text{N}$ flasks lying on the shelf of his lab. All of these flasks contain the same volume of poison solution. The concentration of poison in the $\text{ith}$ flask is $\mathbf{a_i}$. In one move - Tanish picks up any two flasks, pours half of the contents of each of these flasks into a third initially empty flask, discards the two flasks and places the third flask (which now has the same volume of solution as all other flasks) on the shelf. He performs N-1 such moves to end up with only one flask of poison on the shelf. He wishes to perform these moves such that the concentration of poison in this flask is the minimum possible. What is the minimum concentration of poison that he can achieve?

-----Input-----
First line of the input contains a single integer $\text{T}$ - the number of test cases.
For each test case,
The first line contains a single integer $\text{N}$, the number of bottles.
The second line contains N space-separated integers, the concentrations.

-----Output-----
For each test case, print one line containing the lowest final concentration. The output will be accepted if the absolute error is $\leq 10^{-6}$.

-----Constraints-----
$1 \leq \text{T} \leq 10$
$2 \leq \text{N} \leq 10^4$
$0 \leq \mathbf{a_i} \leq 10^9$

-----Sample Input-----
2
2
9 3
3
3 2 9

-----Sample Output-----
6.00000000
4.00000000

-----Explanation-----
In test 1, Tanish mixes flasks 1 and 2. In test 2, he first mixes flasks 1 and 3 to get a flask of concentration 6 and then mixes this flask with flask 2 to get a flask of poison concentration 4.

-----Note-----
The concentration is given in the unit ppb i.e. parts per billion.
1 gram poison in $10^9$ ml solution is 1...

t=int(input())
for i in range(t):
 n=int(input())
 N=list(map(int,input().split()))
 N.sort()

 k=n-1
 ave=N[k]
 for j in range(n-1):
  ave=(ave+N[k-1])/2
  k=k-1

 print(ave)


Solve in Python:
Tara was completing an Algorithms assignment and got stuck on a question. She thought of who can help her, and got reminded of Kabir who has good problem solving skills. The question is:
Given N$N$ the number of elements in the sequence A1$A_1$,A2$A_2$ … An$A_n$. Find out the prime factor which occurred maximum number of times among the largest prime factor corresponding to each element. if there are more than one such prime factors print the largest one.
You are friends with Kabir, help him to solve the problem for Tara.

-----Input:-----
- The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T test cases follows.
- First line of each test case contains N$N$, the number of elements in the sequence.
- Second line contains N space separated elements A1$A_1$,A2$A_2$ … An$A_n$.

-----Output:-----
- For each test case, print a single line, the number which occurs maximum number of times from the largest prime factor corresponding to each element.

-----Constraints-----
- 1≤T≤10$1 \leq T \leq 10$
- 1≤N≤105$1 \leq N \leq 10^5$
- 2≤A[i]≤105$2 \leq A[i] \leq 10^5$

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

3 2 15 6 8 5 10

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

-----EXPLANATION:-----
The largest prime factors of numbers are:
3 2  5  3  2  5  5 , of which 5 is most frequent.

def prime(num):
  if n>1:
   for i in range(2, int(num**0.5)+1):

       # If num is divisible by any number between
       # 2 and n / 2, it is not prime
       if (num % i) == 0:
           return False
           break
   else:
       return True

  else:
   return False
t=int(input())
for k in range(t):
    n=int(input())
    a=[0]*n
    l=list(map(int,input().split()))
    s=max(l)
    a1=[0]*(s+1)
    i=2
    while(i<=s):
        if (prime(i)):
         for j in range(i,s+1,i):
            a1[j]=i
        i+=1
    for j in range(n):
        a[j]=a1[l[j]]
    a.sort()
    ti=1
    ma=1
    nu=a[0]
    for j in range(1,n):
        if a[j]==a[j-1]:
            ti+=1
        else:
            if ti>=ma:
                ma=ti
                nu=a[j-1]

            ti=1
    if ti>=ma:
        ma=ti
        nu=a[n-1]

    print(nu)


Solve in Python:
Taru likes reading. Every month he gets a copy of the magazine "BIT". The magazine contains information about the latest advancements in technology.  Taru

reads the book at night and writes the page number to which he has read on a piece of paper so that he can continue from there the next day. But sometimes

the page number is not printed or is so dull that it is unreadable.  To make matters worse Taru's brother who is really naughty tears of some of the pages of

the Magazine and throws them in the dustbin. He remembers the number of leaves he had torn but he does not remember which page numbers got removed. When Taru

finds this out he is furious and wants to beat him up. His brother apologizes, and says he won't ever do this again. But Taru did not want to be easy on him

and he says "I will leave you only if you help me find the answer to this. I will tell you how many pages (Printed sides) were there in the Magazine plus the

pages on which the page numbers were not printed. You already know the number of leaves you tore (T). Can you tell me the expected sum of the page numbers

left in the Magazine?" Taru's brother replied "huh!! This is a coding problem". Please help Taru's brother.

Note: The magazine is like a standard book with all odd page numbers in front and the successive even page number on its back. If the book contains 6 pages,

Page number 1 and Page number 2 are front and back respectively. Tearing a leaf removes both the front and back page numbers.

-----Input-----
The first line contains the number of test cases t. 3t lines follow. The first line of each test case contains the number of pages (printed sides) in the

book. The second line's first integer is F, F integers follow which tell us the numbers of the page numbers not printed. The third line contains a single integer telling us the number of leaves Taru's brother tore.

-----Output-----
Output one real number correct up to 4 decimal digits which is equal to the expected sum of the page numbers left in the...

import sys

rl=sys.stdin.readline
T=int(rl())
for t in range(T):
 P=int(rl())
 T=(P+1)//2
 F=list(map(int,rl().split()))[1:]
 numtorn=int(rl())
 t=sum(range(1,P+1))-sum(F)
 K=T-numtorn
 print('%.4f' % (t*K/float(T)))


Solve in Python:
Task

Create a top-down movement system that would feel highly responsive to the player. In your Update method you have to check for the keys that are currently being pressed, the keys correspond to the enum Direction shown below, based on which key is pressed or released your method should behave this way:

1) When a key is first pressed, the player has to change his direction to that of the current key, without moving

2) If the key is still being pressed during the next Update, the player will move towards his current direction using these vectors: (Up = { 0, +1 } , Down = { 0, -1 }, Left = { -1, 0 }, Right = { +1, 0 })

3) If a new key is pressed, it will gain precedence over the previous key and the player will act as per 1)

4-A) If the current key (A) is released, then the precedence will go back to the previous key (B) (or the one before it, if (B) is not pressed anymore, and so on), then the player will behave as per 1).

4-B) If the current key is released, and no other keys are being pressed, the player will stand still

5) If all keys are released at once, the player will not move nor change direction

6) If multiple keys are pressed at once, the order of precedence will be the following { Up, Down, Left, Right }

Examples

    (n = pressed key, [n] = current key, p() = press, r() = release, (8,2,4,6 = up, down, left, right)):

    [] , p(8) -> [8] , p(4,6) -> 86[4] , r(6) -> 8[4] , r(4) -> [8] , r(8) -> []

    [] , p(2486) -> 642[8] , r(2,8) -> 6[4] , r(4,6) -> []

This is what you'll need to use in your code (NB: the tile coordinates cannot be changed, you'll need to assign a new Tile each time the player moves):

```python
class Tile:

    @property
    def x(self):
        return self._x

    @property
    def y(self):
        return self._y

    def __str__(self):
        return "({},{})".format(self._x, self._y)

class Input:

    @staticmethod
    def get_state(direction): # 2, 4, 6, 8
        return Input.STATES[direction] # pressed = true, released = false
```

from collections import Counter
class PlayerMovement:

    def __init__(self, x, y):
        self.position = Tile(x, y)
        self.direction = 8
        self.moves = {8:[0,1],2:[0,-1],4:[-1,0],6:[1,0]}
        self.keys = []
    def update(self):
        release = [i for i in [8,2,4,6] if not Input.get_state(i)]
        if any(i in self.keys for i in release):
            if len(self.keys)==1 : return self.keys.pop()
            for i in release:
                if i in self.keys : self.keys.pop(len(self.keys)-self.keys[::-1].index(i)-1)
            if not self.keys : return
            if self.direction == self.keys[-1]:
                  inc,dec = self.moves[self.direction]
                  self.position = Tile(self.position.x+inc,self.position.y+dec)
            self.direction = self.keys[-1]
        else:
            direction = [i for i in [8,2,4,6] if Input.get_state(i)]
            new, c = list((Counter(direction)-Counter(self.keys)).elements()), bool(self.keys)
            if not new and not self.keys : return
            self.keys.extend(sorted(new,key=[6,4,2,8].index))
            d = self.keys[-1]
            if not c or (d != self.direction): self.direction = d ; return
            inc,dec = self.moves[self.direction]
            self.position = Tile(self.position.x+inc,self.position.y+dec)


Solve in Python:
Task
======

Make a custom esolang interpreter for the language [InfiniTick](https://esolangs.org/wiki/InfiniTick). InfiniTick is a descendant of [Tick](https://esolangs.org/wiki/tick) but also very different. Unlike Tick, InfiniTick has 8 commands instead of 4. It also runs infinitely, stopping the program only when an error occurs. You may choose to do the [Tick](https://www.codewars.com/kata/esolang-tick) kata first.

Syntax/Info
======

InfiniTick runs in an infinite loop. This makes it both harder and easier to program in. It has an infinite memory of bytes and an infinite output amount. The program only stops when an error is reached. The program is also supposed to ignore non-commands.

Commands
======

`>`: Move data selector right.

`<`: Move data selector left.

`+`: Increment amount of memory cell. Truncate overflow: 255+1=0.

`-`: Decrement amount of memory cell. Truncate overflow: 0-1=255.

`*`: Add ascii value of memory cell to the output tape.

`&`: Raise an error, ie stop the program.

`/`: Skip next command if cell value is zero.

`\`: Skip next command if cell value is nonzero.

Examples
======

**Hello world!**

The following is a valid hello world program in...

def interpreter(tape):
    selector = 0
    output = ""
    array = [0]
    commandIndex = 0

    while(True):
      command = tape[commandIndex%len(tape)]

      if command == '>':
        selector+=1;
        if selector == len(array):
          array.append(0)

      if command == '<':
        if selector == 0:
          array = [0] + array
        else:
          selector-=1;

      if command == '+':
        array[selector]+=1;
        if array[selector] == 256:
          array[selector] = 0
      if command == '-':
        array[selector]-=1;
        if array[selector] == -1:
          array[selector] = 255
      if command == '/':
        if array[selector] == 0:
          commandIndex += 1
      if command == '\\':
        if array[selector] != 0:
          commandIndex += 1
      if command == '*':
        output = output + chr(array[selector])
      if command == '&':
        return output
      commandIndex+=1
    return output


def interpreter(tape):
    cells, cell, out = {}, 0, ''
    for c in tape:
        if c == '>': cell += 1
        if c == '<': cell -= 1
        if c == '+': cells[cell] = 1 if cell not in cells else 0 if cells[cell] == 255 else cells[cell] + 1
        if c == '*': out += chr(cells[cell])
    return out


Solve in Python:
Task:
Given an array arr of strings complete the function landPerimeter by calculating the total perimeter of all the islands. Each piece of land will be marked with 'X' while the water fields are represented as 'O'. Consider each tile being a perfect 1 x 1piece of land. Some examples for better visualization:

['XOOXO',
  'XOOXO',
  'OOOXO',
  'XXOXO',
  'OXOOO']

or

should return:
"Total land perimeter: 24",

while

['XOOO',
  'XOXO',
  'XOXO',
  'OOXX',
  'OOOO']

should return: "Total land perimeter: 18"
Good luck!

def land_perimeter(arr):

    I,J = len(arr),len(arr[0])

    P = 0
    for i in range(I):
        for j in range(J):
            if arr[i][j] == 'X':
                if i == 0   or arr[i-1][j] == 'O': P += 1
                if i == I-1 or arr[i+1][j] == 'O': P += 1
                if j == 0   or arr[i][j-1] == 'O': P += 1
                if j == J-1 or arr[i][j+1] == 'O': P += 1

    return 'Total land perimeter: ' + str(P)


Solve in Python:
Task:
Make a function that converts a word to pig latin. The rules of pig latin are:

```
If the word has more than 3 letters:
  1. Take the first letter of a word and move it to the end
  2. Add -ay to the word
Otherwise leave the word alone.
```

Example: `hello` = `ellohay`

pig_latin = lambda w: len(w) < 4 and w or "%s%say" % (w[1:], w[0])


Solve in Python:
Task:
This kata requires you to write an object that receives a file path
and does operations on it.
NOTE FOR PYTHON USERS: You cannot use modules os.path, glob, and re
The purpose of this kata is to use string parsing, so you're not supposed to import external libraries. I could only enforce this in python.
Testing:

Python:
```python
>>> master = FileMaster('/Users/person1/Pictures/house.png')
>>> master.extension()
'png'
>>> master.filename()
'house'
>>> master.dirpath()
'/Users/person1/Pictures/'
```

class FileMaster():
    def __init__(self, filepath):
        self.fp = filepath

    def extension(self):
        return self.fp.split('.')[-1]

    def filename(self):
        return self.fp.rsplit('/', 1)[-1].split('.')[0]

    def dirpath(self):
        return self.fp.rsplit('/', 1)[0] + '/'


Solve in Python:
Tavak and Seyyed are good friends. Seyyed is very funny and he told Tavak to solve the following problem instead of longest-path.

You are given l and r. For all integers from l to r, inclusive, we wrote down all of their integer divisors except 1. Find the integer that we wrote down the maximum number of times.

Solve the problem to show that it's not a NP problem.

-----Input-----

The first line contains two integers l and r (2 ≤ l ≤ r ≤ 10^9).

-----Output-----

Print single integer, the integer that appears maximum number of times in the divisors.

If there are multiple answers, print any of them.

-----Examples-----
Input
19 29

Output
2

Input
3 6

Output
3

-----Note-----

Definition of a divisor: https://www.mathsisfun.com/definitions/divisor-of-an-integer-.html

The first example: from 19 to 29 these numbers are divisible by 2: {20, 22, 24, 26, 28}.

The second example: from 3 to 6 these numbers are divisible by 3: {3, 6}.

L, R = [int(i) for i in input().split()]

if L == R:
    print(L)
else:
    print(2)


Solve in Python:
Taxis of Kharagpur are famous for making sharp turns. You are given the coordinates where a particular taxi was on a 2-D planes at N different moments: (x1, y1), (x2, y2), ..., (xN, yN). In between these coordinates, the taxi moves on a straight line. A turn at the i-th (2 ≤ i ≤ N-1) coordinate is said to be a sharp turn if the angle by which it turns at Point B = (xi, yi) when going from coordinates A = (xi-1, yi-1) to C = (xi+1, yi+1) via (xi, yi) is greater than 45 degrees. ie. suppose you extend the line segment AB further till a point D, then the angle DBC would be greater than 45 degrees.
You have to identify whether the taxi made a sharp turn somewhere or not (Please look at Output section for details). If it made a sharp turn, also identify whether it is possible to change the coordinates at one of the N moments to make sure that the taxi doesn't make any sharp turn. Note that all the N pairs of coordinates (including the new coordinates) should be integers and distinct and should have their x and y coordinates at least 0 and at most 50.

-----Input-----
- The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
- The first line of each test case contains a single integer N denoting the number of moments at which you are given the information of the taxi's coordinates.
- Each of the next N lines contains two space-separated integers xi and yi denoting the x and y coordinates of the taxi at i-th moment.

-----Output-----
- For each test case, print a single line containing two space-separated strings, either of which can be a "yes" or "no" (without quotes). If there was no sharp turn, the first string should be "yes", and if there was a sharp turn, the first string should be "no". For the second string, you should tell whether it is possible to modify at most one coordinate in such a way that taxi doesn't make a sharp turn. Note that if the first string is "yes", then the second string would always be...

import math
import copy
try:
 import psyco
 psyco.full()
except ImportError:
 pass

def isSharp(ang):
 return ang > math.pi/4 + 0.00001

def unitVector(p2, p1):
 d0 = p2[0] - p1[0]
 d1 = p2[1] - p1[1]
 d = math.sqrt(d0*d0 + d1*d1)
 if d != 0:
  return [d0/d, d1/d]
 return [0, 0]

def compVectors(P):
 V = []
 for i in range(1,len(P)):
  v = unitVector(P[i], P[i-1])
  if v[0] == 0 and v[1] == 0:
   return None
  V.append(v)
 return V

def angle(v2, v1):
 d = v2[0]*v1[0] + v2[1]*v1[1]
 if d > 1:
  d = 1
 if d < -1:
  d = -1
 return math.acos(d)

def compAngles(V):
 A = []
 for i in range(len(V)-1):
  A.append(angle(V[i+1], V[i]))
 return A

def updateAngles(i, P, V, A):
 if i-1 >= 0:
  V[i-1] = unitVector(P[i], P[i-1])
 if i+1 < len(P):
  V[i] = unitVector(P[i+1], P[i])
 if i-2 >= 0:
  A[i-2] = angle(V[i-1], V[i-2])
 if i-1 >= 0 and i+1 < len(P):
  A[i-1] = angle(V[i], V[i-1])
 if i+2 < len(P):
  A[i] = angle(V[i+1], V[i])

def checkMoves(check, P, V, A, filled):
 for i in check:
  if i < 0 or i >= len(P):
   break
  x, y = P[i]
  for j in range(51):
   for k in range(51):
    P[i][0] = j
    P[i][1] = k
    if str(P[i]) in filled:
     continue
    updateAngles(i, P, V, A)
    fixed = True
    if i-2 >= 0:
     if isSharp(A[i-2]):
      fixed = False
    if i-1 >= 0 and i-1 < len(A):
     if isSharp(A[i-1]):
      fixed = False
    if i < len(A):
     if isSharp(A[i]):
      fixed = False
    if fixed:
     return True
  P[i] = [x, y]
  updateAngles(i, P, V, A)
 return False

def canFix(first, last, P, V, A, filled):
 d = last - first
 if d > 2:
  return False
 if d == 2:
  check = [first+2]
 if d == 1:
  check = [first+1, first+2]
 if d == 0:
  check = [first, first+1, first+2]
 if checkMoves(check, P, V, A, filled):
  return True
 return False

T=int(input())
for i in range(T):
 N=int(input())
 P=[]
 V=[]
 filled={}
 for i in range(N):
  P.append(list(map(int,input().split())))
  filled[str(P[i])] = 1
 V = compVectors(P)
 A = compAngles(V)
 blunt = True
 first = -1
 last = -1
 for i in...


Solve in Python:
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.

```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.

class Dog ():
  def __init__(self, breed):
    self.breed = breed
  def bark(self):
    return "Woof"

snoopy = Dog("Beagle")

#snoopy.bark #= lambda: "Woof"

scoobydoo = Dog("Great Dane")


Solve in Python:
Teacher Sungjae wanted to hold a programming competition for his students where every participant need to be included into  team. The participants submitted their team names before the deadline. After the competition ran for half an hour, (It is assured that each registered team will submit absolutely once within half an hour) Sungjae mistakenly pressed a button that changed the order of the registered team names. Now in the submission list, order of the characters in the team's name doesn't matter. That means $abc$, $acb$, $bac$, $bca$, $cab$, $cba$ refers to the same team. The competition ran for two hours and then ended. Sungjae now counting each of the team's score and wants to print the registered team names and score. The scoreboard should be ordered based on scores in decreasing order and if two teams have same score, Sangjae would follow lexicographical order.
$N$.$B$. frequency of each character's in a registered team's name will not match with another team.
That means two teams named $xoxo$ and $oxox$ is not possible. Because both of them have the same frequency of each of the characters (two 'o' and two 'x'). Similarly $abb$ and $bab$ is not possible (because both of them have one 'a' and two 'b').
It is ensured that only possible test cases will be given.

-----Input:-----Input:
-
First line will contain $T$, number of testcases. Then the testcases follow.
-
The first line of each test case contains two integers , $N$ and $R$ - total number of submissions and the number of submissions within first half an hour.
-
Then $R$  lines follow: the i'th line contains a string $ti$, registered names of the teams and an integer $pi$, points they got on that submission.
-
Then $N-R$  lines follow: the i-th line contains a string $ti$- the i-th team's name (in any order) in lowercase letter only and $pi$ -points they got on that submission.

-----Output:-----Output:
For each testcase,print the scoreboard.
That means print the teams name and their point according to their score in decreasing order and...

for _ in range(int(input())):
    n,r=map(int,input().split())
    s=[]
    d=dict()
    for i in range(r):
        a,b=map(str,input().split())
        s.append([int(b),a])
        a=list(a)
        a.sort()
        d[''.join(a)]=i
    for i in range(n-r):
        a,b=map(str,input().split())
        a=list(a)
        a.sort()
        s[d[''.join(a)]][0]+=int(b)
    s.sort(key=lambda x:x[1], reverse=True)
    s.sort(key=lambda x:x[0])
    for i in range(-1,-r-1,-1):
        print(s[i][1],s[i][0])


Solve in Python:
Teacher brought a fruit basket for three students. The basket contains only Apples, Mangoes and Oranges. Student A knows a value $a$, the total number of Apples and Mangoes in the Basket, B knows a value $b$, the total number of Mangoes and Oranges in the basket and Student C knows a value $c$, the total number of Oranges and Apples in the Basket. Since the teacher brought it he knows a value $d$ , the total number of fruits in the basket. You have to determine the exact number of Apples , Mangoes and Oranges in the basket separately.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, four integers $a,b,c,d$.

-----Output:-----
For each testcase, output in a single line the number of Apples , Mangoes and Oranges in this order.

-----Constraints-----
- $1 \leq T \leq 100$
- $0 \leq a \leq 1000$
- $0 \leq b \leq 1000$
- $0 \leq c \leq 1000$
- $0 \leq d \leq 1000$
-The Solution always exisits

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

7 9 8 12

3 8 7 9

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

1 2 6

for _ in range(int(input())):
 a,b,c,d=map(int,input().split())
 print(c-d+a,b-d+a,d-a)


Solve in Python:
Ted$Ted$ loves prime numbers. One day he is playing a game called legendary$legendary$ with his girlfriend Robin$Robin$. Ted$Ted$ writes a number N$N$ on a table and the number is in the form of :
N = P1A1 *  P2A2 * ……….. * PnAn
Ted$Ted$ asks Robin$Robin$ to find the sum of all the numbers which are less than or equal to N$N$ and also contains all the primes whose minimum power in the number is given by an array B$B$.
As Robin$Robin$ is bad with maths she asks your help to answer this question.

-----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 a single integer n$n$, represents a number of distinct prime numbers.
- The second line of each test case contains n$n$ space separated distinct prime numbers which represents an array P$P$.
- The third line of each test case contains n$n$ space separated integers which represents an array A$A$.
- The fourth line of each test case contains n$n$ space separated integers which represents an array B$B$

-----Output:-----
For each test case, output the Answer Modulo 109 + 7 in a single line.

-----Constraints-----
- 1≤T≤3$1 \leq T \leq 3$
- 1≤n≤105$1 \leq n \leq 10^5$
- 2≤Pi≤106$2 \leq P_{i} \leq 10^6$
- 1≤Ai≤109$1 \leq A_{i} \leq 10^9$
- 0≤Bi≤Ai$0 \leq B_{i} \leq Ai$

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

-----Sample Output:-----
540

-----EXPLANATION:-----
22 * 31 * 52= 300 which is N over here.
The four numbers less than or equal to 300 are 30, 60, 150 and 300.

30 = 21 * 31 * 51 , 60 =  22 * 31 * 51, 150 =  21 * 31 * 52 and 300 =  22 * 31 * 52.
In the 4 numbers, the minimum powers for 2, 3 and 5 are 1, 1 and 1 or more than them in every case.

d = 10**9 + 7

t = int(input())
while t:
    t-=1
    n =int(input())
    p =list(map(int, input().strip().split()))
    a =list(map(int, input().strip().split()))
    b =list(map(int, input().strip().split()))
    ans = 1
    for i in range(n):
        c = a[i] - b[i] + 1
        tmp = (( pow(p[i],b[i],d) * ((pow(p[i],c,d) - 1 + d)%d) * pow(p[i]-1 , d-2, d)%d))
        ans *= tmp
        ans = ans%d

    print(ans)


Solve in Python:
Teddy and Tracy like to play a game based on strings. The game is as follows. Initially, Tracy writes a long random string on a whiteboard. Then, each player starting with Teddy makes turn alternately. Each turn, the player must erase a contiguous substring that exists in the dictionary. The dictionary consists of N words.
Of course, the player that can't erase any substring in his turn loses the game, and the other player is declared the winner.
Note that after a substring R is erased, the remaining substring becomes separated, i.e. they cannot erase a word that occurs partially to the left of R and partially to the right of R.

Determine the winner of the game, assuming that both players play optimally.

-----Input-----
The first line contains a single integer T, the number of test cases. T test cases follow. The first line of each testcase contains a string S, the string Tracy writes on the whiteboard. The next line contains a single integer N. N lines follow. The i-th line contains a single string wi, the i-th word in the dictionary.

-----Output-----
For each test case, output a single line containing the name of the winner of the game.

-----Example-----
Input:
3
codechef
2
code
chef
foo
1
bar
mississippi
4
ssissi
mippi
mi
ppi

Output:
Tracy
Tracy
Teddy

-----Constraints-----
- 1 <= T <= 5
- 1 <= N <= 30
- 1 <= |S| <= 30
- 1 <= |wi| <= 30
- S and wi contain only characters 'a'-'z'

D = {}

def g(s):
  if s in D: return D[s]

  vals = set()
  l = len(s)
  for i in range(l):
    for j in range(1, l+1 - i):
      sub = s[i : i+j]
      if sub in DIC:
        vals.add(g(s[:i]) ^ g(s[i+j:]))

  i = 0
  while 1:
    if not i in vals:
      break
    i += 1
  D[s] = i
  return D[s]

T = int(input(""))
for t in range(T):
  s = input("")
  d_len = int(input(""))
  DIC = set()
  for i in range(d_len):
    DIC.add(input(""))
  D = {}
  print("Teddy" if g(s) else "Tracy")


Solve in Python:
Tejas has invited the Clash Team for a Dinner Party. He places V empty plates (numbered from 1 to V inclusive) in a straight line on a table. He has prepared 2 kinds of Delicious Dishes named dish A and dish B.

He has exactly V servings of Dish A and W servings of dish B.

Now he wants to serve the dishes in such a way that if theith plate has serving of Dish A then (i-1)th plate should not have serving of Dish B. Assuming all the Dishes are identical find number of ways Tejas can serve the Clash Team.

-----Input-----
- The first line of the input contains an integer T denoting the number of test cases . The description of T testcases follow.

- The first line of each test case contains two space seperated integers V W .

-----Output-----
For each test case, output the number of ways Tejas can serve the Clash Team.

-----Constraints-----

- 1 ≤ T ≤ 100
- 1 ≤ V ≤ 1000
- 1 ≤ W ≤ 1000

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

1

3 3

Output:
4

-----Explanation-----

In the above example the 4 ways are:

AAA

AAB

ABB

BBB

for _ in range(int(input())):
  v,w=map(int,input().split())
  print(min(v,w)+1)


Solve in Python:
Tennis is a popular game. Consider a simplified view of a tennis game from directly above. The game will appear to be played on a 2 dimensional rectangle, where each player has his own court, a half of the rectangle. Consider the players and the ball to be points moving on this 2D plane. The ball can be assumed to always move with fixed velocity (speed and direction) when it is hit by a player. The ball changes its velocity when hit by the other player. And so on, the game continues.
Chef also enjoys playing tennis, but in n+1$n + 1$ dimensions instead of just 3. From the perspective of the previously discussed overhead view, Chef's court is an n$n$-dimensional hyperrectangle which is axis-aligned with one corner at (0,0,0,…,0)$(0, 0, 0, \dots, 0)$ and the opposite corner at (l1,l2,l3,…,ln$(l_1, l_2, l_3, \dots, l_n$). The court of his opponent is the reflection of Chef's court across the n−1$n - 1$ dimensional surface with equation x1=0$x_1 = 0$.
At time t=0$t=0$, Chef notices that the ball is at position (0,b2,…,bn)$(0, b_2, \dots, b_n)$ after being hit by his opponent. The velocity components of the ball in each of the n$n$ dimensions are also immediately known to Chef, the component in the ith$i^{th}$ dimension being vi$v_i$. The ball will continue to move with fixed velocity until it leaves Chef's court. The ball is said to leave Chef's court when it reaches a position strictly outside the bounds of Chef's court. Chef is currently at position (c1,c2,…,cn)$(c_1, c_2, \dots, c_n)$. To hit the ball back, Chef must intercept the ball before it leaves his court, which means at a certain time the ball's position and Chef's position must coincide.
To achieve this, Chef is free to change his speed and direction at any time starting from time t=0$t=0$. However, Chef is lazy so he does not want to put in more effort than necessary. Chef wants to minimize the maximum speed that he needs to acquire at any point in time until he hits the ball. Find this minimum value of speed smin$s_{min}$.
Note: If an object moves...

# cook your dish here
import math
for i in range(int(input())):
    n=int(input())
    bound=[int(i) for i in input().split()]
    ball=[int(i) for i in input().split()]
    speed=[int(i) for i in input().split()]
    chef=[int(i) for i in input().split()]
    cspeed=0
    time=float('inf')
    for i in range(n):
        if(speed[i]>0):
            a=(bound[i]-ball[i])/speed[i]
            time=min(a,time)
        elif(speed[i]<0):
            a=abs(ball[i]/speed[i])
            time=min(a,time)

    a=b=c=0
    for i in range(n):
        c+=speed[i]**2
        a+=(ball[i]-chef[i])**2
        b+=2*speed[i]*(ball[i]-chef[i])
    if(a==0):
        print(0)
    else:
        x=-b/(2*a)
        if(x>=1/time):
            cspeed=c - (b**2)/(4*a)
            print(math.sqrt(cspeed))
        else:
            cspeed=a/(time**2) + b/time + c
            print(math.sqrt(cspeed))


Solve in Python:
Thanks to the effects of El Nino this year my holiday snorkelling trip was akin to being in a washing machine... Not fun at all.

Given a string made up of '~' and '\_' representing waves and calm respectively, your job is to check whether a person would become seasick.

Remember, only the process of change from wave to calm (and vice versa) will add to the effect (really wave peak to trough but this will do). Find out how many changes in level the string has and if that figure is more than 20% of the string, return "Throw Up", if less, return "No Problem".

sea_sick=lambda s: ["No Problem","Throw Up"][(s.count("~_")+s.count("_~"))/float(len(s))>0.2]


Solve in Python:
The  Chef  has bought $N$ boxes of Tiles. The number of tiles present in  $i^{th}$ box is  $i$  ($i   $ varies from $1$ to $N$) . The Chef  has two houses  with  $N$  rooms  each, whose  floors  is a square with area $(i*i)$ ,i varies from $(1....N)$. He want to distribute equal number of tiles from $i^{th}$ box to any two rooms (each room must belong to one house ) such that all tiles  of $i^ { th}$  box is used and floor of  both rooms of different houses are tiled completely.
Since chef is busy doing some other works so he wants your help to count the total number of rooms of both houses that will be tiled completely.
Note $:$ size of  each tile present in boxes has length and breadth equal to $1$. It is not mandatory to use all the boxes.
A room should be tilled completely from a single box.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains one integer $N$.

-----Output:-----
For each testcase print  the total number of rooms of both houses that will be tiled completely.

-----Constraints-----
- $1 \leq T \leq 5000$
- $1 \leq N \leq 10^{12}$

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

-----Sample Output:-----
4

-----EXPLANATION:-----
The room $1$ and $2$ of both the houses are completely tiled.

from math import sqrt
t = int(input())
for _ in range(t):
  n = int(input())
  print(int(sqrt(n >> 1)) << 1)


Solve in Python:
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.

Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).

-----Input-----

The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages.

Then n lines follow — each employee's language list. At the beginning of the i-th line is integer k_{i} (0 ≤ k_{i} ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains k_{i} integers — a_{ij} (1 ≤ a_{ij} ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages.

The numbers in the lines are separated by single spaces.

-----Output-----

Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).

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

Output
0

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

Output
2

Input
2 2
1 2
0

Output
1

-----Note-----

In the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.

In the third sample employee 2 must learn language 2.

def main():
    n, m = list(map(int, input().split()))
    f = [1] * n
    lang = [set(map(int, input().split()[1:])) for _ in range(n)]
    for i, langi in enumerate(lang):
        for j, langj in enumerate(lang[:i]):
            if f[j] and langj.intersection(langi):
                f[j] = 0
                langi.update(langj)
    print(sum(f) - any(lang))

def __starting_point():
    main()

__starting_point()


Solve in Python:
The "Russian Peasant Method" is an old algorithm used by Russian peasants (and before them ancient Egyptians) to perform multiplication.  Consider that X and Y are two numbers.  X can be any number but Y must be a positive integer. To multiply X and Y:

1. Let the product = 0
2. If Y is odd, then the product = product + X
3. X = X + X
4. Y = integer part of Y / 2
5. if Y is nonzero, repeat from step 2; otherwise the algorithm terminates and returns the product.

For example:

Let X = 10

Let Y = 5

X: 10 20 40 80

Y: 5  2  1  0

product = 10 + 40 = 50

Note: usage of multiplication is of course forbidden...

def russian_peasant_multiplication(x,y):
    prod=0
    while y:
        if y%2:prod+=x
        x+=x
        y=y//2
    return prod


Solve in Python:
The $String$ Family gave birth to a new $Tripartite$ $trio$ $sisters$ and named them $Hema$, $Rekha$ and $Sushma$. Hema and Rekha are very fond of parties whereas Sushma hates them. One day Hema and Rekha asked their parents to buy them candies to distribute to people in their birthday party. (Remember Hema, Rekha and Sushma were born on the same day). But Sushma was uninterested in the party and only wanted candies for herself.
You will be given a list $P$ of possible number of candidates coming to the party. Were $P[i]$ denotes the count of people coming in the i th possibility. In each case every person should get maximum possible equal number of candies  such that after distributing the candies, there are always $R$ candies remaining for Sushma. You have to calculate the minimum number of candies required to buy so that, in any possible situation of the given array, each person coming to party gets equal number of candies (at least 1 and maximum possible out of total) and there are always $R$ candies remaining for Sushma.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- First line of each test case contain  $N$, number of possible count of people coming to party
- Next line contain $N$ spaced integers denoting the count of people
- Next line contain $R$ the number of candies always remaining after maximum equal distribution

-----Output:-----
For each testcase, output in a single line answer, the minimum number of candies required to buy.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq N \leq 10^4$
- $1 \leq P[i] \leq 41$
- $0 \leq R < min(P[i])$

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

-----Sample Output:-----
7

from math import gcd
def compute_lcm(x, y):
    lcm = (x*y)//gcd(x,y)
    return lcm

def LCMofArray(a):
    lcm = a[0]
    for i in range(1,len(a)):
        lcm = lcm*a[i]//gcd(lcm, a[i])
    return lcm

for _ in range(int(input())):
    lens = int(input())
    arrs = [int(x) for x in input().split()]
    rest = int(input())
    print(LCMofArray(arrs) + rest)


Solve in Python:
The 26 letters of the English alphabets are randomly divided into 5 groups of 5 letters with the remaining letter being ignored.  Each of the group is assigned a score of more than 0.  The ignored letter always has a score of 0.

With this kata, write a function ```nameScore(name)``` to work out the score of a name that is passed to the function.

The output should be returned as an object:

Only letters have a score. Spaces do not.

You can safely assume that ```name``` does not contain any punctuations or symbols.  There will also be no ```empty string``` or ```null``` value.

A static ```alpha``` object for testing has been preloaded  for your convenience in the following format:

Note that the ```alpha``` object will be randomly generated each time you run the test.

#Example

In accordance to the above ```alpha``` object, the name ```Mary Jane``` will have a name score of ```20``` => M=3 + a=1 + r=4 + y=5 + J=2 + a=1 + n=3 + e=1

def name_score(name):
    score = 0
    for c in name:
        for k, v in alpha.items():
            if c.upper() in k:
                score += v
                break
    return {name:score}


Solve in Python:
The AKS algorithm for testing whether a number is prime is a polynomial-time test based on the following theorem:

A number p is prime if and only if all the coefficients of the polynomial expansion of `(x − 1)^p − (x^p − 1)` are divisible by `p`.

For example, trying `p = 3`:

     (x − 1)^3 − (x^3 − 1) = (x^3 − 3x^2 + 3x − 1) − (x^3 − 1) = − 3x^2 + 3x

And all the coefficients are divisible by 3, so 3 is prime.

Your task is to code the test function, wich will be given an integer and should return true or false based on the above theorem. You should efficiently calculate every coefficient one by one and stop when a coefficient is not divisible by p to avoid pointless calculations. The easiest way to calculate coefficients is to take advantage of binomial coefficients: http://en.wikipedia.org/wiki/Binomial_coefficient and pascal triangle: http://en.wikipedia.org/wiki/Pascal%27s_triangle .

You should also take advantage of the symmetry of binomial coefficients. You can look at these kata: http://www.codewars.com/kata/pascals-triangle and http://www.codewars.com/kata/pascals-triangle-number-2

The kata here only use the simple theorem. The general AKS test is way more complex.  The simple approach is a good exercie but impractical. The general AKS test will be the subject of another kata as it is one of the best performing primality test algorithms.

The main problem of this algorithm is the big numbers emerging from binomial coefficients in the polynomial expansion. As usual Javascript reach its limit on big integer very fast. (This simple algorithm is far less performing than a trivial algorithm here). You can compare the results with those of this kata: http://www.codewars.com/kata/lucas-lehmer-test-for-mersenne-primes Here, javascript can barely treat numbers bigger than 50, python can treat M13 but not M17.

import math
def aks_test(p):
    center = (math.factorial(p//2)*math.factorial(p-p//2))
    if center%p==0:
        return False
    return True


Solve in Python:
The Ackermann function is a famous function that played a big role in computability theory as the first example of a total computable function that is not primitive recursive.

Since then the function has been a bit simplified but is still of good use. Due to its definition in terms of extremely deep recursion it can be used as a benchmark of a compiler's ability to optimize recursion.

The goal of this kata is to code a function which will be given two inputs, m and n, and will return the Ackermann number A(m,n) defined by:

```
A(m,n) = n+1                          if m=0
A(m,n) = A(m-1,1)                     if m>0 , n=0
A(m,n) = A(m-1,A(m,n-1))              if m,n > 0
```

m,n should be non-negative integers, the function should return null (Javascript), None (Python), or nil (Ruby) for other type, non-integer and negative numbers. In C, input is restricted to integer type.

def Ackermann(m,n):
    return n+1 if m == 0 else (Ackermann(m-1, 1) if n == 0 else Ackermann(m-1, Ackermann(m, n-1)))


Solve in Python:
The Binomial Form of a polynomial has many uses, just as the standard form does.  For comparison, if p(x) is in Binomial Form and q(x) is in standard form, we might write

p(x) := a0 \* xC0 + a1 \* xC1 + a2 \* xC2 + ... + aN \* xCN

q(x) := b0 + b1 \* x + b2 \* x^(2) + ... + bN \* x^(N)

Both forms have tricks for evaluating them, but tricks should not be necessary.  The most important thing to keep in mind is that aCb can be defined for non-integer values of a; in particular,

```
aCb := a * (a-1) * (a-2) * ... * (a-b+1) / b!   // for any value a and integer values b
    := a! / ((a-b)!b!)                          // for integer values a,b
```

The inputs to your function are an array which specifies a polynomial in Binomial Form, ordered by highest-degree-first, and also a number to evaluate the polynomial at.  An example call might be

```python
value_at([1, 2, 7], 3)
```

and the return value would be 16, since 3C2 + 2 * 3C1 + 7 = 16.  In more detail, this calculation looks like

```
1 * xC2 + 2 * xC1 + 7 * xC0 :: x = 3
3C2 + 2 * 3C1 + 7
3 * (3-1) / 2! + 2 * 3 / 1! + 7
3 + 6 + 7 = 16
```

More information can be found by reading about [Binomial Coefficients](https://en.wikipedia.org/wiki/Binomial_coefficient) or about [Finite Differences](https://en.wikipedia.org/wiki/Finite_difference).

Note that while a solution should be able to handle non-integer inputs and get a correct result, any solution should make use of rounding to two significant digits (as the official solution does) since high precision for non-integers is not the point here.

def binom(x, k):
    r = 1
    for i in range(1, k + 1):
        r *= (x - i + 1) / i
    return r

def value_at(poly_spec, x):
    r = 0
    for k, c in enumerate(poly_spec[::-1]):
        r += c * binom(x, k)
    return round(r, 2)


Solve in Python:
The Bubble Cup hypothesis stood unsolved for $130$ years. Who ever proves the hypothesis will be regarded as one of the greatest mathematicians of our time! A famous mathematician Jerry Mao managed to reduce the hypothesis to this problem:

Given a number $m$, how many polynomials $P$ with coefficients in set ${\{0,1,2,3,4,5,6,7\}}$ have: $P(2)=m$?

Help Jerry Mao solve the long standing problem!

-----Input-----

The first line contains a single integer $t$ $(1 \leq t \leq 5\cdot 10^5)$ - number of test cases.

On next line there are $t$ numbers, $m_i$ $(1 \leq m_i \leq 10^{18})$ - meaning that in case $i$ you should solve for number $m_i$.

-----Output-----

For each test case $i$, print the answer on separate lines: number of polynomials $P$ as described in statement such that $P(2)=m_i$, modulo $10^9 + 7$.

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

Output
2
4

-----Note-----

In first case, for $m=2$, polynomials that satisfy the constraint are $x$ and $2$.

In second case, for $m=4$, polynomials that satisfy the constraint are $x^2$, $x + 2$, $2x$ and $4$.

T = input()
mod = int(1e9 + 7)
a = list(map(int, input().split()))
c = []
for n in a:
    b = (n // 2 + 2)
    b = b * b
    b //= 4
    c.append(str(b % mod))
print(' '.join(c))


Solve in Python:
The Challenge
-------------
You'll need to implement a simple lexer type. It should take in an input string through the constructor (or the parameter, for Javascript), and break it up into typed-tokens (in python, C# and Java, you'll have to manage `null/None` input too, resulting in the same behavior than an empty string). You'll need to implement the necessary methods (aaccording to your language) to make the Simplexer object behave like an iterator, Meaning that it returns a token (assuming one is available) object each time it a `next` (`Current` field in C#) method would be called. If no tokens are available, an exception should be thrown (idealy: `StopIteration` in python, `InvalidOperationException` in C# and `NoSuchElementException` in Java).

Tokens are represented by Token objects, which define two properties as strings: `text`, and `type`. Constructor is `Token(text, type)`.

**C# Notes**:
`Iterator` is an extension of `IEnumerator` with default implementations for `Reset()`, `Dispose()` and `IEnumerator.Current` as these are not need to pass the challenge. You only need to override `MoveNext()` and `Current { get; }`.

Token Types
-----------
There are 7 tokens types that your lexer will need to produce: `identifier`, `string`, `integer`, `boolean`, `keyword`, `operator`, and `whitespace`. To create the token, you'd need to pass in the token value (the text) and the token type as strings, so for example, a simple integer token could be created with `new Token("1", "integer")` (Note: no default values or default constructor are provided, so use `new Token("","")` if you want a default Token object).

Token Grammar
--------------
Here's a table of the grammars for the various token types:
```
integer : Any sequence of one or more digits.

boolean : true or false.

string : Any sequence of characters surrounded by "double quotes".

operator : The characters +, -, *, /, %, (, ), and =.

keyword : The following are keywords: if, else, for, while, return, func, and break.

whitespace : Matches standard...

class Simplexer(object):
    def __init__(self, expression):
        self.tokens = []

        l = list(expression)[::-1]
        while l:
            t = l.pop()
            if t in '+-*/%()=': ttype = 'operator'
            elif t.isspace():
                ttype = 'whitespace'
                while l and l[-1].isspace(): t += l.pop()
            elif t.isdigit():
                ttype = 'integer'
                while l and l[-1].isdigit(): t += l.pop()
            elif t == '"':
                ttype = 'string'
                while l and l[-1] != '"': t += l.pop()
                t += l.pop()
            else:
                while l and not l[-1].isspace() and not l[-1] in '+-*/%()=': t += l.pop()

                ttype = 'boolean' if t in 'true false' else 'keyword' if t in 'if else for while return func and break'.split() else 'identifier'

            self.tokens.append(Token(t, ttype))
        self.tokens = self.tokens[::-1]

    def __iter__(self): return iter(self.tokens[::-1])

    def __next__(self):
        if self.tokens: return self.tokens.pop()
        raise StopIteration()


Solve in Python:
The Chef has a huge square napkin of size 2n X 2n. He folds the napkin n-3 times. Each time he folds its bottom side over its top side, and then its right side over its left side. After each fold, the side length of the napkin is reduced by half. The Chef continues folding until there remains a 8x8 sheet, lying flat on a table.
Oh, did I forget to mention that the Chef was cooking a new brown colored curry while folding the napkin. He drops some brown colored gravy onto some cells in the folded 8x8 napkin. When he drops the gravy, it soaks through all the cells below it.
Now the Chef unfolds the napkin to its original size. There are now many curry stained brown colored cells in the napkin. They form several separate regions, each of which is connected. Could you help the Chef count how many regions of brown cells are there in the napkin?
Note that two cells are adjacent if they share a common edge (they are not considered adjacent if they only share a corner). Two cells are connected if we can go from one cell to the other via adjacent cells. A region is a maximal set of cells such that every two of its cells are connected.
Please see the example test case for more details.

-----Input-----
The first line contains t, the number of test cases (about 50). Then t test cases follow. Each test case has the following form:
- The first line contains N (3 ≤ N ≤ 109)
- Then, 8 lines follow. Each line is a string of 8 characters, 0 or 1, where 1 denotes a stained brown cell in the folded napkin.

-----Output-----
For each test case, print a single number that is the number of disconnected brown regions in the unfolded napkin. Since the result may be a very large number, you only need to print its remainder when dividing by 21945.

-----Example-----
Input:
3
3
01000010
11000001
00000000
00011000
00011000
00010100
00001000
00000000
4
01000010
11000001
00000000
00011000
00011000
00010100
00001000
00000000
1000000000
11111111
11111111
11111111
11111111
11111111
11111111
11111111
11111111

Output:
6
22
1

-----Output...

import sys
t = int(sys.stdin.readline())

def identify(x, y):
    rows[x][y] = '2'

    r = 0
    if x == 0:
        r |= 1
    elif rows[x-1][y] == '1':
        r |= identify(x-1, y)
    if x == 7:
        r |= 4
    elif rows[x+1][y] == '1':
        r |= identify(x+1, y)
    if y == 0:
        r |= 2
    elif rows[x][y-1] == '1':
        r |= identify(x, y-1)
    if y == 7:
        r |= 8
    elif rows[x][y+1] == '1':
        r |= identify(x, y+1)
    return r

P = 21945

while t:
    t-=1
    n = int(sys.stdin.readline())-3

    rows = [list(sys.stdin.readline().strip()) for i in range(8)]
    total = 0
    for i in range(8):
        for j in range(8):
            if rows[i][j] == '1':
                r = identify(i,j)
                # print '\n'.join([''.join(ro) for ro in rows])
                # print r
                if n == 0:
                    total += 1
                    # print total
                    continue
                if r == 0:
                    total += pow(2, 2*n, P)
                elif r == 1 or r == 2 or r == 4 or r == 8:
                    total += pow(2, 2*n-1, P)
                    if r == 1 or r == 2:
                        total += pow(2, n, P)
                elif r == 5 or r == 10:
                    total += pow(2, n, P)
                elif r == 3 or r == 6 or r == 12 or r == 9:
                    total += pow(2, 2*n-2, P)
                    if r == 3:
                        total += 3 + 2*pow(2, n-1, P) - 2
                    elif r == 6 or r == 9:
                        total += pow(2, n-1, P)
                elif r == 15:
                    total += 1
                else:
                    total += pow(2, n-1, P)
                    if r == 11 or r == 7:
                        total += 1
                # print total
    print(total % P)


Solve in Python:
The Chef has been kidnapped by aliens ( they want to utilize his excellent cooking skills :P ) and has been transported to the alien planet "ZX532". Interestingly, "ZX532" uses a different time scale which has Y AlienHours on the face of a clock (instead of the 12 hours that we have).  They also have 'X*Y' AlienMinutes (instead of the 60 that we have).  X is defined as the number of minute divisions between each hour (the earth clock has X=5).
The Chef has been forced to cook a lot of dishes by the aliens. He is short of ingredients and hence needs to go out to the market to get them. However when he returns, he makes an interesting observation. The hands of AlienClock have exactly swapped position from the time he left (the big hand and the little hand have switched)!
Given the times between which The Chef might have left and the times between which The Chef may have returned, you are supposed to find out the actual time when he left.  If there is more than one possibility, print the one that maximizes the amount of time that The Chef is out.Details of the Clock
The AlienClock is circular and has exactly 2 hands : the hour hand and the minute hand. The whole circumference of the AlienClock is divided into Y divisions , each of which is further divided into X subdivisions [ X and Y are both positive integers ]. The clock is not discrete but continuous (the hands move continuously instead of moving at certain intervals such as every second, etc.... ).

-----Input-----
First line of input contains t (1≤ t ≤ 100) - the number of test cases. Each test case contains 2 lines each. The first line contains 2 space separated integers , X and Y (same as those specified in the problem statement; X ≤ 109 and Y ≤ 109 ).
The next line contains 8 space separated integers (a,b,c,d,e,f,g,h; 0 ≤ a ≤ c < Y; 0 ≤ e ≤ g < Y; a ≤ e; 0 ≤ b,d,f,h < X*Y ): specifying the times between which The Chef might have left (a:b => a hours and b minutes TO c:d => c hours and d minutes) and the times between which The Chef may have returned...

import decimal;
from decimal import *;

def solve(a, b, min1, min2, min3, min4, x, y):
	if a > b:
		return [];
	solMin1 = (a/y+b)/(y-1/y);
	solMin2 = (b/y+a)/(y-1/y);
	solMin1 *= (x*y);
	solMin2 *= (x*y);

	if solMin1 >= min1 and solMin1 <= min2 and solMin2 >= min3 and solMin2 <= min4:
		# Solution found
		return [a, solMin1, b, solMin2];
	return [];

def integerPart(x):
	return Decimal(str(x).split(".")[0]);

def fractionalPart(x):
	t = str(x).split(".");
	if len(t) > 0:
		return "." + t[1];
	return 0;

getcontext().prec = 30;
for i in range(eval(input())):
	(x,y) = input().split();
	(a,b,c,d,e,f,g,h) = input().split();
	x=Decimal(x);y=Decimal(y);a=Decimal(a);b=Decimal(b);c=Decimal(c);d=Decimal(d);e=Decimal(e);f=Decimal(f);g=Decimal(g);h=Decimal(h);

	if a > g or (a == g and b > h):
		print("-1");
		continue;

	solutionh = Decimal("-1");
	solutionm = Decimal("-1");
	diff = Decimal("-10000000000000000");

	solution1 = [];solution2=[];solution3=[];solution4=[];solution5=[];solution6=[];solution7=[];solution8=[];solution9=[];
	solution10 = [];solution11=[];solution12=[];solution13=[];solution14=[];
	l1 = 0;
	if g == e:
		l1 = f;
	solution1 = solve(a+0,g+0,b,x*y,l1,h,x,y);
	if a < y - 1 and len(solution1) == 0:
		solution2 = solve(a+1,g+0,0,x*y,l1,h,x,y);
	if g >= 1 and len(solution1) == 0 and len(solution2) == 0:
		solution4 = solve(a+0,g-1,b,x*y,0,x*y,x,y);
	if g-e >= 2 and c-a>=2 :
		solution5 = solve(a+1,g-1,0,x*y,0,x*y,x,y);

	if len(solution1) == 0 and len(solution2) == 0 and len(solution4) == 0:
		solution10 = solve(a, e, 0, x*y, 0, x*y, x, y);
		solution11 = solve(c, e, 0, x*y, 0, x*y, x, y);
		solution12 = solve(c, g, 0, x*y, 0, x*y, x, y);
	if a < y - 1 and len(solution1) == 0 and len(solution2) == 0 and len(solution4) == 0 and c - a >= 2:
		solution13 = solve(a + 1, e, 0, x*y, 0, x*y, x, y);
	if g >= 1 and len(solution1) == 0 and len(solution2) == 0 and len(solution4) == 0 and g - e >= 2:
		solution14 = solve(c, g - 1, 0, x*y, 0, x*y, x, y);

	if len(solution1) > 0:
		if solution1[0] < c or...


Solve in Python:
The Chef has one long loaf of bread of length 1. He wants to cut it into as many little loaves as he can. But he wants to adhere to the following rule: At any moment, the length of the longest loaf which he possesses may not be larger than the length of shortest one, times some constant factor. Every time, he is only allowed to cut exactly one loaf into two shorter ones.

-----Input-----
One floating-point number, 1 ≤ k ≤ 1.999, meaning the stated constant factor. The number will have at most 3 digits after the decimal point.

-----Output-----

First, you should output one number n, the maximal achievable number of loaves for the given value of the constant factor. Then, you should output any proof that this number of loaves is in fact achievable: n-1 descriptions of cutting, using the following notation. At each step, you print two numbers: first, the index of the loaf that you want to cut into two parts; second, the length of the newly created loaf (cut off from the original one). It is assumed that the starting loaf has index 0. Each newly created loaf will be given the lowest possible free integer index (so, at the ith step this will be i). Each time, the size of size of the original loaf will be decreased by the size of the newly created loaf.

-----Example-----
Input:
1.5
Output:
4
0 0.4
0 0.3
1 0.2

import sys
from math import log

k = float(sys.stdin.readline())
answer = int(log(2.0, 2.0/k))
print(2*answer)

m = 2 ** (1.0/answer)
# m = 2.0/k
thesum = 0
for i in range(answer):
 thesum += m**i
# print [m**i/thesum for i in xrange(answer)]
loaves = [1]

def maxIndex(list):
 max = -1
 mi = -1
 for i, x in enumerate(list):
  if x > max:
   max = x
   mi = i
 return mi

desired = [m**i/thesum for i in range(answer)]
desired.reverse()
# print desired
cuts = []
while len(desired) > 1:
 cuts.append(desired[-1])
 lastsum = desired[-1] + desired[-2]
 del desired[-2:]
 desired[0:0] = [lastsum]

# print cuts

while cuts:
 length = cuts.pop()
 i = maxIndex(loaves)
 print(i, length)
 loaves[i] -= length
 loaves.append(length)
 # print loaves

# print loaves
for i in range(answer):
 i = maxIndex(loaves[:answer])
 x = loaves[i]/2.0
 print(i, x)
 loaves.append(x)
 loaves[i] -= x
# print loaves


Solve in Python:
The Chef has prepared the appetizers in the shapes of letters to spell a special message for the guests. There are n appetizers numbered from 0 to n-1 such that if the appetizers are arrayed in this order, they will display the message. The Chef plans to display them in this order on a table that can be viewed by all guests as they enter. The appetizers will only be served once all guests are seated.

The appetizers are not necessarily finished in the same order as they are numbered. So, when an appetizer is finished the Chef will write the number on a piece of paper and place it beside the appetizer on a counter between the kitchen and the restaurant. A server will retrieve this appetizer and place it in the proper location according to the number written beside it.

The Chef has a penchant for binary numbers. The number of appetizers created is a power of 2, say n = 2k. Furthermore, he has written the number of the appetizer in binary with exactly k bits. That is, binary numbers with fewer than k bits are padded on the left with zeros so they are written with exactly k bits.

Unfortunately, this has unforseen complications. A binary number still "looks" binary when it is written upside down. For example, the binary number "0101" looks like "1010" when read upside down and the binary number "110" looks like "011" (the Chef uses simple vertical lines to denote a 1 bit). The Chef didn't realize that the servers would read the numbers upside down so he doesn't rotate the paper when he places it on the counter. Thus, when the server picks up an appetizer they place it the location indexed by the binary number when it is read upside down.

You are given the message the chef intended to display and you are to display the message that will be displayed after the servers move all appetizers to their locations based on the binary numbers they read.

-----Input-----

The first line consists of a single integer T ≤ 25 indicating the number of test cases to follow. Each test case consists of a single line beginning with...

t=int(input())
def reversebinary(bits,n):
    bStr=''
    for i in range(bits):
        if n>0:
            bStr=bStr+str(n%2)
        else:
            bStr=bStr+'0'
        n=n>>1
    return int(bStr,2)

for i in range(t):
    k,msg=input().split()
    k=int(k)
    newmsg=[]
    for j in msg:
        newmsg.append(j)
    for j in range(len(msg)):
        newmsg[reversebinary(k,j)]=msg[j]
    print(''.join(newmsg))


Solve in Python:
The Chef is given an array of numbers and asked to find the first balance point of an array. A balance point is an index in the array N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no such balance point, print -1

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N denoting the number of weights on the array. The second line contains N space-separated integers A1, A2, ..., AN denoting the weights

-----Output-----
For each test case, output a single line containing the index of the first balance point. If no such index exists, output -1

-----Constraints-----
For Subtask 1:
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 10
- -1000 ≤ A1, A2, ..., AN ≤ 1000
For Subtask 1:
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 1000
- -10000 ≤ A1, A2, ..., AN ≤ 10000

-----Example-----
Input:
2
7
7 8 9 1 9 8 7
6
1 100 50 -51 1 1

Output:
3
1

-----Explanation-----
Example case 1. In the first case, at the midpoint of the array 1, the sum of the left side {7,8,9} is equal to the sum of the right side {9,8,7}
Example case 1. In the second case, at index 1, the sum of left side =1 is equal to the sum of the right side {50,-51,1,1}

t=eval(input())
for i in range(t):
 n=eval(input())
 a=list(map(int,input().split()))
 f=0
 for i in range(1,n-1):
  c=0
  for j in range(0,i):
   c=c+a[j]
  if c+c==sum(a)-a[i]:
   f=i
   break
 if sum(a[1:])==0:
  print(0)
 elif sum(a[0:n-1])==0:
  print(n-1)
 elif f==0:
  print(-1)
 else:
  print(f)


Solve in Python:
The Chef once decided to prepare some nice dishes on his birthday. There are N items kept on his shelf linearly from position 1 to N. Taste of the i-th item is denoted by a integer Ai.

He wants to make Q dishes. A dish will be made using some ingredients in the continuous range AL, AL + 1, , , AR (1-base indexing). Quality of the dish will be determined by the ingredient with minimum taste.

Chef wants help of his assistant Rupsa to find out sum and product of qualities of the dishes. As product of the qualities of the dishes could be very large, print it modulo 109 + 7. Also, you are given an integer K and you are assured that for each dish, the size of continuous range of the ingredients (i.e. R - L + 1) will always lie between K and 2 * K, both inclusive.

Method of generation of Array A

You are given non-negative integer parameters a, b, c, d, e, f, r, s, t, m, A[1]

for x = 2 to N:
	if(t^x mod s  <= r)        // Here t^x signifies "t to the power of x"
		A[x] = (a*A[x-1]^2 + b*A[x-1] + c) mod m
	else
		A[x] = (d*A[x-1]^2 + e*A[x-1] + f) mod m

Method of generation of range of ingredients for Q dishes

You are given non-negative integer parameters L1, La, Lc, Lm, D1, Da, Dc, Dm

for i = 1 to Q:
	L1 = (La * L1 + Lc) mod Lm;
	D1 = (Da * D1 + Dc) mod Dm;
	L = L1 + 1;
	R = min(L + K - 1 + D1, N);

-----Input-----
- The first line contains three integers N, K and Q.
- The second line contains the integers a, b, c, d, e, f, r, s, t, m, and A[1].
- Then third line contains the integers L1, La, Lc, Lm, D1, Da, Dc, and Dm

-----Output-----
Output two space separated integers:

- The sum of qualities of the dishes.
- The product of qualities of the dishes modulo 109+7.

-----Constraints-----
- 1 ≤ N, Q ≤ 107
- 1 ≤ K ≤ N
- 0 ≤ a, b, c, d, e, f, r, s, t, m, A[1] ≤ 109+7
- 1 ≤ Lm ≤ N - K + 1
- 1 ≤ Dm ≤ K + 1
- 1 ≤ La, Lc ≤ Lm
- 1 ≤ Da, Dc ≤ Dm
- 1 ≤ L1 ≤ N
- 1 ≤ D1 ≤ K

-----Sub tasks-----
- Subtask #1: 1 ≤ N, Q ≤ 1000 (10 points)
- Subtask #2: 1 ≤ Q ≤ 104 (20 points)
- Subtask #3: original constraints (70...

mod=10**9+7
N,K,Q=list(map(int,input().split()))

A=[0,0]
#min_t=[-1]*((N*N-1)/2)
#print min_t
a,b,c,d,e,f,r,s,t,m,A[1]=list(map(int,input().split()))

L1,La,Lc,Lm,D1,Da,Dc,Dm=list(map(int,input().split()))

tmpt=t
min_arr=[0]
for x in range(2,N+1):
 tmpt=(tmpt*t)%s
 if tmpt <= r:
  A.append(( A[x-1]*(a*A[x-1] + b) + c) % m)
 else:
  A.append(( A[x-1]*(d*A[x-1] + e) + f) % m)
for x in range(1,N-K+2):
 min_arr.append(min(A[x:x+K]))

res_sum=0
res_pro=1
for x in range(1,Q+1):
 L1 = (La * L1 + Lc) % Lm
 D1 = (Da * D1 + Dc) % Dm
 L = L1 + 1
 R = min(L + K - 1 + D1, N)
 R=R-K+1
 #print min_arr,L,R,min_arr[L:R+1]
 if L==R:
  tmp=min_arr[L]
 else:
  tmp=min(min_arr[L:R+1])
 res_sum+=tmp
 res_pro=(res_pro*tmp)% mod
print(res_sum,res_pro)


Solve in Python:
The Collatz Conjecture states that for any natural number n, if n is even, divide it by 2. If n is odd, multiply it by 3 and add 1. If you repeat the process continuously for n, n will eventually reach 1.

For example, if n = 20, the resulting sequence will be:

[20, 10, 5, 16, 8, 4, 2, 1]

Write a program that will output the length of the Collatz Conjecture for any given n. In the example above, the output would be 8.

For more reading see: http://en.wikipedia.org/wiki/Collatz_conjecture

def collatz(n):
  step = 1
  while n!= 1:
    n = [n//2, (n*3)+1][n%2]
    step += 1
  return step


Solve in Python:
The Collatz conjecture (also known as 3n+1 conjecture) is a conjecture that applying the following algorithm to any number we will always eventually reach one:

```
[This is writen in pseudocode]
if(number is even) number = number / 2
if(number is odd) number = 3*number + 1
```

#Task

Your task is to make a function ```hotpo``` that takes a positive ```n``` as input and returns the number of times you need to perform this algorithm to get ```n = 1```.

#Examples

```
hotpo(1) returns 0
(1 is already 1)

hotpo(5) returns 5
5 -> 16 -> 8 -> 4 -> 2 -> 1

hotpo(6) returns 8
6 -> 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1

hotpo(23) returns 15
23 -> 70 -> 35 -> 106 -> 53 -> 160 -> 80 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
```

#References
- Collatz conjecture wikipedia page: https://en.wikipedia.org/wiki/Collatz_conjecture

def hotpo(n):
    if n == 1 : return 0
    count = 0

    while n != 1 :
        if n % 2 == 0:
            n = n / 2
        else :
            n = 3 * n + 1
        count += 1
        #print (remainder, count)
    return (count)


Solve in Python:
The Collatz conjecture is one of the most famous one. Take any positive integer n, if it is even divide it by 2, if it is odd multiply it by 3 and add 1 and continue indefinitely.The conjecture is that whatever is n the sequence will reach 1. There is many ways to approach this problem, each one of them had given beautifull graphs and impressive display of calculation power. The simplest approach can be found in this kata: http://www.codewars.com/kata/5286b2e162056fd0cb000c20
You look at the Collatz sequence of a number and see when it reaches 1.

In this kata we will take a look at the length of collatz sequences. And how they evolve. Write a function that take a positive integer n and return the number between 1 and n that has the maximum Collatz sequence length and the maximum length. The output has to take the form of an array [number, maxLength] For exemple the Collatz sequence of 4 is [4,2,1], 3 is [3,10,5,16,8,4,2,1], 2 is [2,1], 1 is [1], so `MaxCollatzLength(4)` should return `[3,8]`. If n is not a positive integer, the function have to return [].

* As you can see, numbers in Collatz sequences may exceed n.

The last tests use random big numbers so you may consider some optimisation in your code:

* You may get very unlucky and get only hard numbers: try submitting 2-3 times if it times out; if it still does, probably you need to optimize your code more;

* Optimisation 1: when calculating the length of a sequence, if n is odd, what 3n+1 will be ?

* Optimisation 2: when looping through 1 to n, take i such that i<n/2, what will be the lenght of the sequence for 2i ?

c = {1:1}
def F(n):
    if n in c : return c[n]
    c[n] = 1 + F(n*3+1 if n&1 else n//2)
    return c[n]
max_collatz_length=lambda n:[] if type(n)!=int or n<=0 else max([[i,F(i)] for i in range(1,n+1)], key=lambda x:x[1])


Solve in Python:
The Dynamic Connectivity Problem

Given a set of of N objects, is there a path connecting the two objects?

Implement an class that implements the following API:

  *  Takes n as input, initializing a data-structure with N objects (0...N-1)
  *  Implements a Union command that adds a connection between point p and point q
  *  Implements a Connected command that returns a boolean and asks is there a connection between point p and point q

As a simple example:
Imagine you initialize an data structure filled with integers from 0 to 9 (N = 10)
```python
  results1 = DynamicConnectivity(10)
```
You will receive a series of union commands linking various points
```python
  results1.union(4,3)
  results1.union(3,8)
  results1.union(6,5)
  results1.union(9,4)
  results1.union(2,1)
```
This should result in 5 groups of connections:

  * 3,4,8,9
  * 5,6
  * 2,1
  * 0
  * 7

All members of a groups (set) are conected to every other member
If you asked is 0 connected to 7, it should return False
If you asked is 8 connected to 9 you should return True even if 8,9 wern't directly joined.
(8 is connected to 3 which is connected to 4 which is connected to 9)
```python
  results1.connected(0,7) == False
  results1.connected(8,9) == True
```

For the purposes of this problem, you do not have to mainatin the order of the connections, you just have to know that the connection is there.

Hint:
  There is a naive implenetation that takes time proportional to O(n^2) (Quadratic Funtion)
  **This will time out the problem**
  (Because every time you double the input like from 50 nodes to 100 nodes, the function takes **4** times as long)
  Test will check that you are able to outrun this naive implementation. If you can't that means that your code is too slow

  There is a solution that takes linearitmic time or faster O(n * lg n)

Hint Two: (Take it or leave it)
  If you find yourself nesting a loop inside a loop, you are creating a quadratic function

Implementation must be able to handle initializing 1 million nodes, and...

class DynamicConnectivity(object):
    def __init__(self, n):
        self.__map = list(range(0, n))

    def __root(self, p):
        while p != self.__map[p]:
            self.__map[p] = self.__map[self.__map[p]]
            p = self.__map[p]
        return p

    def union(self, p, q):
        self.__map[self.__root(p)] = self.__root(q)

    def connected(self, p, q):
        return self.__root(p) == self.__root(q)


Solve in Python:
The EEE classes are so boring that the students play games rather than paying attention during the lectures. Harsha and Dubey are playing one such game.

The game involves counting the number of anagramic pairs of a given string (you can read about anagrams from here). Right now Harsha is winning. Write a program to help Dubey count this number quickly and win the game!

-----Input-----
The first line has an integer T which is the number of strings. Next T lines each contain a strings. Each string consists of lowercase english alphabets only.

-----Output-----
For each string, print the answer in a newline.

-----Constraints-----
- 1 ≤ T ≤ 1000
- 1 ≤ length of each string ≤ 100

-----Example-----
Input:
3
rama
abba
abcd
Output:
2
4
0

-----Explanation-----
rama has the following substrings:

- r
- ra
- ram
- rama
- a
- am
- ama
- m
- ma
- a
Out of these, {5,10} and {6,9} are anagramic pairs.

Hence the answer is 2.

Similarly for other strings as well.

def sort_str(s):
    o = []
    for c in s:
        o.append(c)
    o.sort()
    return "".join(o)
def find_ana(s):
    if len(s) <= 1:
        return 0
    h = {}
    c = 0
    for i in range(len(s)):
       for j in range(i+1, len(s)+1):
          t = sort_str(s[i:j])
          if t in h:
            c += h[t]
            h[t] += 1
          else:
            h[t] = 1
    return c
t = int(input())
for _ in range(t):
    print(find_ana(input()))


Solve in Python:
The Earth has been invaded by aliens. They demand our beer and threaten to destroy the Earth if we do not supply the exact number of beers demanded.

Unfortunately, the aliens only speak Morse code. Write a program to convert morse code into numbers using the following convention:

1 .----
2 ..---
3 ...--
4 ....-
5 .....
6 -....
7 --...
8 ---..
9 ----.
0 -----

morse_converter=lambda s:int(''.join(str(9-'----.....-----'.rindex(s[i:i+5]))for i in range(0,len(s),5)))


Solve in Python:
The Fair Nut is going to travel to the Tree Country, in which there are $n$ cities. Most of the land of this country is covered by forest. Furthermore, the local road system forms a tree (connected graph without cycles). Nut wants to rent a car in the city $u$ and go by a simple path to city $v$. He hasn't determined the path, so it's time to do it. Note that chosen path can consist of only one vertex.

A filling station is located in every city. Because of strange law, Nut can buy only $w_i$ liters of gasoline in the $i$-th city. We can assume, that he has infinite money. Each road has a length, and as soon as Nut drives through this road, the amount of gasoline decreases by length. Of course, Nut can't choose a path, which consists of roads, where he runs out of gasoline. He can buy gasoline in every visited city, even in the first and the last.

He also wants to find the maximum amount of gasoline that he can have at the end of the path. Help him: count it.

-----Input-----

The first line contains a single integer $n$ ($1 \leq n \leq 3 \cdot 10^5$) — the number of cities.

The second line contains $n$ integers $w_1, w_2, \ldots, w_n$ ($0 \leq w_{i} \leq 10^9$) — the maximum amounts of liters of gasoline that Nut can buy in cities.

Each of the next $n - 1$ lines describes road and contains three integers $u$, $v$, $c$ ($1 \leq u, v \leq n$, $1 \leq c \leq 10^9$, $u \ne v$), where $u$ and $v$ — cities that are connected by this road and $c$ — its length.

It is guaranteed that graph of road connectivity is a tree.

-----Output-----

Print one number — the maximum amount of gasoline that he can have at the end of the path.

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

Output
3

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

Output
7

-----Note-----

The optimal way in the first example is $2 \to 1 \to 3$.  [Image]

The optimal way in the second example is $2 \to 4$.  [Image]

from sys import stdin, setrecursionlimit
import threading
n = int(stdin.readline())
w = [int(x) for x in stdin.readline().split()]
graph = [{} for x in range(n)]
for road in range(n-1):
    u,v,c = [int(x) for x in stdin.readline().split()]
    u -= 1
    v -= 1

    if v in graph[u]:
        graph[u][v] = min(graph[u][v], c)
    else:
        graph[u][v] = c

    if u in graph[v]:
        graph[v][u] = min(graph[v][u], c)
    else:
        graph[v][u] = c

gas = [{} for x in range(n)]
highs = [[0,0] for x in range(n)]

path = [(0,0)]

ind = 0

while ind < len(path):
    cur, par = path[ind]
    edges = graph[cur]
    for x in edges:
        if x != par:
            path.append((x,cur))
    ind += 1

def mostGas(node,parent):
    edges = graph[node]
    high = w[node]
    high2 = w[node]

    for x in edges:
        if x != parent:
            gas[node][x] = highs[x][0] + w[node] - edges[x]
            if gas[node][x] > high:
                high,high2 = gas[node][x], high
            elif gas[node][x] > high2:
                high2 = gas[node][x]
    highs[node] = [high,high2]
    return high

'''def fillIn(node,parent):
    edges = graph[node]
    high,high2 = highs[node]
    for x in edges:
        if x != parent:
            if gas[node][x] == high:
                gas[x][node] = high2 - edges[x]
            else:
                gas[x][node] = high - edges[x]
            if gas[x][node] > highs[x][0]:
                highs[x] = [gas[x][node], highs[x][0]]
            elif gas[x][node] > highs[x][1]:
                highs[x][1] = gas[x][node]
            fillIn(x,node)'''

for x,y in path[::-1]:
    mostGas(x,y)
#fillIn(0,0)

high = 0

for x in range(n):
    high = max(high, highs[x][0]+highs[x][1]-w[x])
print(high)