Solve in Python:
Did you know that there are over 40,000 varieties of Rice in the world ? There are so many dishes that can be prepared with Rice too. A famous chef from Mumbai, Tid Gusto prepared a new dish and named it 'Tid Rice'. He posted the recipe in his newly designed blog for community voting, where a user can plus (+) or minus (-) the recipe. The final score is just the sum of all votes, where (+) and (-) are treated as +1 and -1 respectively. But, being just a chef ( and not a codechef ) he forgot to take care of multiple votes by the same user.

A user might have voted multiple times and Tid is worried that the final score shown is not the correct one. Luckily, he found the user logs, which had all the N votes in the order they arrived.  Remember that, if a user votes more than once, the user's previous vote is first nullified before the latest vote is counted ( see explanation for more clarity ). Given these records in order ( and being a codechef yourself :) ), calculate the correct final score.

-----Input-----
First line contains T ( number of testcases, around 20 ). T cases follow. Each test case starts with N ( total number of votes, 1 <= N <= 100 ). Each of the next N lines is of the form "userid vote" ( quotes for clarity only ), where userid is a non-empty string of lower-case alphabets ( 'a' - 'z' ) not more than 20 in length and vote is either a + or - . See the sample cases below, for more clarity.

-----Output-----
For each test case, output the correct final score in a new line

-----Example-----
Input:
3
4
tilak +
tilak +
tilak -
tilak +
3
ratna +
shashi -
ratna -
3
bhavani -
bhavani +
bhavani -

Output:
1
-2
-1

Explanation

Case 1 : Initially score = 0. Updation of scores in the order of user tilak's votes is as follows,

( + ): +1 is added to the final score. This is the 1st vote by this user, so no previous vote to nullify. score = 1
( + ):  0 should be added ( -1 to nullify previous (+) vote, +1 to count the current (+) vote ). score = 1
( - ) : -2 should be added ( -1 to nullify previous (+)...

t = int(input())
for i in range(t):
 n = int(input())
 scores = {}
 for j in range(n):
  line = input()
  (key, value) = line.split(' ')
  if value == '+':
   scores[key] = 1
  else:
   scores[key] = -1
 sum = 0
 for k in scores:
  sum += scores[k]
 print(sum)


Solve in Python:
Digory Kirke and Polly Plummer are two kids living next door to each other. The attics of the two houses are connected to each other through a passage. Digory's Uncle Andrew has been secretly doing strange things in the attic of his house, and he always ensures that the room is locked. Being curious, Digory suspects that there is another route into the attic through Polly's house, and being curious as kids always are, they wish to find out what it is that Uncle Andrew is secretly up to.

So they start from Polly's house, and walk along the passageway to Digory's. Unfortunately, along the way, they suddenly find that some of the floorboards are missing, and that taking a step forward would have them plummet to their deaths below.

Dejected, but determined, they return to Polly's house, and decide to practice long-jumping in the yard before they re-attempt the crossing of the passage. It takes them exactly one day to master long-jumping a certain length. Also, once they have mastered jumping a particular length L, they are able to jump any amount less than equal to L as well.

The next day they return to their mission, but somehow find that there is another place further up the passage, that requires them to jump even more than they had practiced for. So they go back and repeat the process.

Note the following:

-  At each point, they are able to sense only how much they need to jump at that point, and have no idea of the further reaches of the passage till they reach there. That is, they are able to only see how far ahead is the next floorboard.
-  The amount they choose to practice for their jump is exactly the amount they need to get across that particular part of the passage. That is, if they can currently jump upto a length L0, and they require to jump a length L1(> L0) at that point, they will practice jumping length L1 that day.
-  They start by being able to "jump" a length of 1.

Find how many days it will take them to cross the passageway. In the input, the passageway is described as a string P of...

t=int(input())
for _ in range(t):
 s=input()
 l,d,m=0,0,0
 for i in range(len(s)):
  if s[i]=='.':
   l+=1
  if s[i]=='#' :
   if l>m:
    d+=1
    m=l
   l=0
 print(d)


Solve in Python:
Dima is a beginner programmer. During his working process, he regularly has to repeat the following operation again and again: to remove every second element from the array. One day he has been bored with easy solutions of this problem, and he has come up with the following extravagant algorithm.

Let's consider that initially array contains n numbers from 1 to n and the number i is located in the cell with the index 2i - 1 (Indices are numbered starting from one) and other cells of the array are empty. Each step Dima selects a non-empty array cell with the maximum index and moves the number written in it to the nearest empty cell to the left of the selected one. The process continues until all n numbers will appear in the first n cells of the array. For example if n = 4, the array is changing as follows: [Image]

You have to write a program that allows you to determine what number will be in the cell with index x (1 ≤ x ≤ n) after Dima's algorithm finishes.

-----Input-----

The first line contains two integers n and q (1 ≤ n ≤ 10^18, 1 ≤ q ≤ 200 000), the number of elements in the array and the number of queries for which it is needed to find the answer.

Next q lines contain integers x_{i} (1 ≤ x_{i} ≤ n), the indices of cells for which it is necessary to output their content after Dima's algorithm finishes.

-----Output-----

For each of q queries output one integer number, the value that will appear in the corresponding array cell after Dima's algorithm finishes.

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

Output
3
2
4

Input
13 4
10
5
4
8

Output
13
3
8
9

-----Note-----

The first example is shown in the picture.

In the second example the final array is [1, 12, 2, 8, 3, 11, 4, 9, 5, 13, 6, 10, 7].

from sys import*
input=stdin.readline
n,q=map(int,input().split())
for _ in range(q):
    i=int(input())
    while i%2==0:i+=n-i//2
    print((i+1)//2)


Solve in Python:
Dinesh is very fond of sweets recently his aunt Riya gifted him an array $a$ of sweets of size $N$. The ith sweet is of the type $a[i]$. His mother told him that he can choose one type of sweet in a day and eat at most 2 sweets of that type. Since he has to eat all the sweets as quickly as possible because his cousins are arriving. Find out the minimum number of days in which he can eat all the sweets gifted by his aunt Riya.

-----Input:-----
- First-line will contain $N$, the number of sweets.
- The next line will contain $N$ space integers denoting the type of sweets.

-----Output:-----
Output the minimum number of days in which he can eat all the sweets.

-----Constraints-----
- $1 \leq N \leq 10000$
- $1 \leq a[i] \leq 10^3$

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

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

# cook your dish here
n = int(input())
a = list(map(int,input().split()))
v = dict()
count = 0
for i in range(n):
 k = a[i]
 if k in v:
  v[k] += 1
 else:
  v[k] = 1
for x in v:
 if v[x] >= 2 :
  if v[x] % 2 == 0:
   count += v[x] // 2
  else:
   count += v[x] // 2
   count += 1
 else:
  if v[x] == 1:
   count += 1

print(count)


Solve in Python:
Dio Brando has set  a goal for himself of becoming the richest and the most powerful being on earth.To achieve his goals he will do anything using either manipulation,seduction or plain violence.
Only one guy stands between his goal of conquering earth ,named Jotaro Kujo aka JoJo .Now Dio has a stand (visual manifestation of life energy  i.e, special power )  “Za Warudo” ,which can stop time itself but needs to chant few words to activate the time stopping ability of the stand.There is a code hidden inside the words and if you can decipher the code then Dio loses his power.
In order to stop Dio ,Jotaro asks your help to decipher the code since he can’t do so while fighting Dio at the same time.
You will be given a string as input and you have to find the shortest substring which contains all the characters of itself and then make a number based on the alphabetical ordering of the characters.
For example : “bbbacdaddb”
shortest substring will be “bacd” and based on the alphabetical ordering
the answer is 2134

-----NOTE:-----
A substring is a contiguous subsegment of a string. For example, "acab" is a substring of "abacaba" (it starts in position 3 and ends in position 6), but "aa" or "d" aren't substrings of this string. So the substring of the string s from position l to position r is

S[l;r]=SlSl+1…Sr.

-----Input :-----
The first line contains $T$,number of test cases.
The second line contains a string $S$.

-----Output:-----
For each test cases ,output the number you can get from the shortest string

-----Constraints:-----
$1 \leq t \leq 100$
$1 \leq |S| \leq 10^6$

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

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

abcdfgh

urdrdrav

jojojojoj

bbbbaaa

cddfsccs

tttttttttttt

-----Sample Output:-----
1234678

2118418418122

1015

21

46193

20

-----Explanation:-----
Test case 1: abcdfgh is the shortest substring containing all char of itself and the number is 1234678

# cook your dish here
import sys
import math
from collections import Counter
from collections import OrderedDict
def inputt():
    return sys.stdin.readline().strip()
def printt(n):
    sys.stdout.write(str(n)+'\n')
def listt():
    return [int(i) for i in inputt().split()]
def gcd(a,b):
   return math.gcd(a,b)

def lcm(a,b):
    return (a*b) / gcd(a,b)
from collections import defaultdict

def find_sub_string(str):
    str_len = len(str)

    # Count all distinct characters.
    dist_count_char = len(set([x for x in str]))

    ctr, start_pos, start_pos_index, min_len = 0, 0, -1, 9999999999
    curr_count = defaultdict(lambda: 0)
    for i in range(str_len):
        curr_count[str[i]] += 1

        if curr_count[str[i]] == 1:
            ctr += 1

        if ctr == dist_count_char:
            while curr_count[str[start_pos]] > 1:
                if curr_count[str[start_pos]] > 1:
                    curr_count[str[start_pos]] -= 1
                start_pos += 1

            len_window = i - start_pos + 1
            if min_len > len_window:
                min_len = len_window
                start_pos_index = start_pos
    return str[start_pos_index: start_pos_index + min_len]
t= int(inputt())
for _ in range(t):
    j=[]
    str1 =inputt()
    s=find_sub_string(str1)
    for i in s:
        j.append(abs(97-ord(i))+1)
    st = [str(i) for i in j]
    print(''.join(st))


Solve in Python:
Divisors of 42 are : 1, 2, 3, 6, 7, 14, 21, 42.
These divisors squared are: 1, 4, 9, 36, 49, 196, 441, 1764.
The sum of the squared divisors is 2500 which is 50 * 50, a square!

Given two integers m, n (1 <= m <= n) we want to find all integers
between m and n whose sum of squared divisors is itself a square.
42 is such a number.

The result will be an array of arrays or of tuples (in C an array of Pair) or a string, each subarray having two elements,
first the number whose squared divisors is a square and then the sum
of the squared divisors.

#Examples:
```
list_squared(1, 250) --> [[1, 1], [42, 2500], [246, 84100]]
list_squared(42, 250) --> [[42, 2500], [246, 84100]]
```

The form of the examples may change according to the language, see `Example Tests:` for more details.

**Note**

In Fortran - as in any other language - the returned string is not permitted to contain any redundant trailing whitespace: you can use dynamically allocated character strings.

import math

def store_diviors_squared_sum(func):
    store = {}
    def helper(integer):
        if integer not in store:
            store[integer] = func(integer)
        return store[integer]
    return helper

@store_diviors_squared_sum
def divisors_squared_sum(integer):
    squared_divisors_sum = 1
    for number in range(2, integer+1):
        if integer % number == 0: squared_divisors_sum += number**2
    return squared_divisors_sum

def list_squared(m, n):
    return_array = []
    for integer in range(m, n+1):
        squared_divisors_sum = divisors_squared_sum(integer)
        if math.sqrt(squared_divisors_sum) % 1 == 0:
            return_array.append([integer, squared_divisors_sum])
    return return_array


Solve in Python:
Divya's watch of worth Rs10 cr is abducted by N thieves(1,2....i...N). The fight over the watch leads to a final decision that it should belong to the thief who wins a simple game. The rules of the game state that every thief  registers a time in the format HH:MM:SS . Accordingly the average A of three clockwise angles  between the hours , minutes and seconds hands is calculated . Thus the ith thief  with the maximum A wins the game and gets to keep the watch.

The thieves are poor in mathematics and will need your help . Given the number of thieves and their registered time resolves the conflict and help them in choosing the winner

-----Input-----
First line of input contains T which denotes the number of test cases.

The first line of each test case consists of an integer which denotes the number of thieves thereby N line follow which give the time choosen by each thieve in the format HH:MM:SS.

-----Output:-----
Output single integer i which denotes the ith thief.

-----Constraints:-----

1<=T<=100

1<=N<=50

01<=HH<=12

00<=MM<=60

00<=SS<=60

-----Example:-----
Input:
2
3
12:28:26
07:26:04
11:23:17
2
07:43:25
06:23:34

Output:
3
1

# your code goes here
from sys import stdin, stdout
t = int(stdin.readline())
while t:
 t -= 1
 n = int(stdin.readline())
 maxi = -1
 index = 0
 for i in range(n):
  hh,mm,ss = list(map(int, stdin.readline().strip().split(':')))
  ssa = ss * 360.0 / 60.0
  mma = (mm + (ss / 60.0)) * 360.0 / 60.0
  hha = (hh + (mm + (ss / 60.0)) / 60.0) * 360.0 / 12.0
  avg = (abs(ssa-hha) + abs(mma-ssa) + abs(mma-hha)) / 3
  # print hha, mma, ssa
  if avg > maxi:
   maxi = avg
   index = i
 stdout.write(str(index+1)+'\n')


Solve in Python:
Do you have in mind the good old TicTacToe?

Assuming that you get all the data in one array, you put a space around each value, `|` as a columns separator and multiple `-` as rows separator, with something like `["O", "X", " ", " ", "X", " ", "X", "O", " "]` you should be returning this structure (inclusive of new lines):

```
 O | X |
-----------
   | X |
-----------
 X | O |
```

Now, to spice up things a bit, we are going to expand our board well beyond a trivial `3` x `3` square and we will accept rectangles of big sizes, still all as a long linear array.

For example, for `"O", "X", " ", " ", "X", " ", "X", "O", " ", "O"]` (same as above, just one extra `"O"`) and knowing that the length of each row is `5`, you will be returning

```
 O | X |   |   | X
-------------------
   | X | O |   | O
```

And worry not about missing elements, as the array/list/vector length is always going to be a multiple of the width.

def display_board(board, width):
    board = [c.center(3) for c in board]
    rows = ["|".join(board[n:n+width]) for n in range(0, len(board), width)]
    return ("\n" + "-"*(4*width - 1) + "\n").join(rows)


Solve in Python:
Do you know Professor Saeed? He is the algorithms professor at Damascus University. Yesterday, he gave his students hard homework (he is known for being so evil) - for a given binary string $S$, they should compute the sum of $F(S, L, R)$ over all pairs of integers $(L, R)$ ($1 \le L \le R \le |S|$), where the function $F(S, L, R)$ is defined as follows:
- Create a string $U$: first, set $U = S$, and for each $i$ ($L \le i \le R$), flip the $i$-th character of $U$ (change '1' to '0' or '0' to '1').
- Then, $F(S, L, R)$ is the number of valid pairs $(i, i + 1)$ such that $U_i = U_{i+1}$.
As usual, Professor Saeed will give more points to efficient solutions. Please help the students solve this homework.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains a single string $S$.

-----Output-----
For each test case, print a single line containing one integer $\sum_{1 \le L \le R \le |S|} F(S, L, R)$.

-----Constraints-----
- $1 \le T \le 100$
- $1 \le |S| \le 3 \cdot 10^6$
- the sum of $|S|$ over all test cases does not exceed $6 \cdot 10^6$

-----Subtasks-----
Subtask #1 (50 points):
- $1 \le |S| \le 300$
- the sum of $|S|$ over all test cases does not exceed $600$
Subtask #2 (50 points): original constraints

-----Example Input-----
1
001

-----Example Output-----
6

-----Explanation-----
Example case 1:
- $L = 1, R = 1$: $U$ is "101", $F = 0$
- $L = 2, R = 2$: $U$ is "011", $F = 1$
- $L = 3, R = 3$: $U$ is "000", $F = 2$
- $L = 1, R = 2$: $U$ is "111", $F = 2$
- $L = 2, R = 3$: $U$ is "010", $F = 0$
- $L = 1, R = 3$: $U$ is "110", $F = 1$

a=int(input())
answer=[]
for i in range(a):
 s=input()
 l=len(s)
 ans=0
 for i in range(l-1):
  if s[i]==s[i+1]:
   ans=ans+((l-1)*l)/2
  elif s[i]!=s[i+1]:
   ans=ans+l
 answer.append(ans)
for i in range(a):
 print(int(answer[i]))


Solve in Python:
Do you know that The Chef has a special interest in palindromes? Yes he does! Almost all of the dishes in his restaurant is named by a palindrome strings. The problem is that a name of a dish should not be too long, so The Chef has only limited choices when naming a new dish.

For the given positive integer N, your task is to calculate the number of palindrome strings of length not exceeding N, that contain only lowercase letters of English alphabet (letters from 'a' to 'z', inclusive). Recall that a palindrome is a string that reads the same left to right as right to left (as in "radar").

For example:

- For N = 1, we have 26 different palindromes of length not exceeding N:
"a", "b", ..., "z".
- For N = 2 we have 52 different palindromes of length not exceeding N:
"a", "b", ..., "z",
"aa", "bb", ..., "zz".
- For N = 3 we have 728 different palindromes of length not exceeding N:
"a", "b", ..., "z",
"aa", "bb", ..., "zz",
"aaa", "aba", ..., "aza",
"bab", "bbb", ..., "bzb",
...,
"zaz", "zbz", ..., "zzz".

Since the answer can be quite large you should output it modulo 1000000007 (109 + 7). Yes, we know, most of you already hate this modulo, but there is nothing we can do with it :)

-----Input-----

The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The only line of each test case contains a single integer N.

-----Output-----

For each test case, output a single line containing the answer for the corresponding test case.

-----Constrains-----

- 1 ≤ T ≤ 1000
- 1 ≤ N ≤ 109

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

Output:
26
52
728
1404
508533804

-----Explanation-----

The first three examples are explained in the problem statement above.

def permutation(n,p):
    r = 26
    if n == 1:
        return 26
    elif n == 2:
        return 52
    elif n == 3:
        return 728
    else:
        if n%2 == 0:
            return ((2*(bin_expo(r,((n//2)+1),p)-r)*bin_expo(25,1000000005,p)))%p
        else:
            n = n+1
            return ((2*((bin_expo(r,(n//2+1),p)-r)*bin_expo(r-1,1000000005,p)))- bin_expo(26,n//2,p))%p
def bin_expo(x,n,p):
    if n == 0:
        return 1
    elif n == 1:
        return x%p
    else:
        temp = bin_expo(x,n//2,p)
        temp = (temp*temp)%p
        if n%2 ==0:
            return temp
        else:
            return ((x%p)*temp)%p
for _ in range(int(input())):
    n = int(input())
    p = 1000000007
    print(int(permutation(n,p)))


Solve in Python:
Doctor Kunj installed new software on cyborg Shresth.
This software introduced Shresth to range minimum queries.
Cyborg Shresth thought of T$T$ different problems in each of which you will be given
an array A$A$ of length N$N$ and an array B$B$ of length M$M$. In each of these problems, you have to calculate:
∑mi=1∑mj=irangeMin(B[i],B[j])$\sum_{i=1}^m \sum_{j=i}^m rangeMin(B[i],B[j])$
Where rangeMin(i,j)$rangeMin(i,j)$ returns the minimum element in the range of indices i$i$ to j$j$ (both included) in array A$A$.
It is given that array B$B$ consists of pairwise distinct elements and is in ascending order.

-----Input Format:-----
- First line will contain T$T$, the number of different problems Cyborg Shresth thought of.
- Each problem's input data will be given in three different lines.
- The first line will contain N$N$ and M$M$, the length of array A$A$ and B$B$ respectively.
- The second line will contain N$N$ space separated positive integers, which form the array A$A$. -
- The third line will contain M$M$ space separated positive integers, which form the array B$B$.

-----Output Format:-----
- For each different problem, print on a new line the answer to the problem, i.e. the value of ∑mi=1∑mj=irangeMin(B[i],B[j])$\sum_{i=1}^m \sum_{j=i}^m rangeMin(B[i],B[j])$ .

-----Constraints:-----
- 1≤T≤105$1 \leq T \leq {10}^5$
- 1≤N≤105$1 \leq N \leq {10}^5$
- 1≤M≤105$1 \leq M \leq {10}^5$
- 1≤A[i]≤109$1 \leq A[i] \leq 10^9$
- 1≤B[i]≤N$1 \leq B[i] \leq N$
It is guaranteed that the sum of N$N$ over all test cases does not exceed 106${10}^6$ .

-----Sample Input:-----
1
7 3
10 3 7 9 1 19 2
1 4 6

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

-----Explanation:-----
For the given array A$A$, we have to calculate rangeMin(1,1)+rangeMin(1,4)+rangeMin(1,6)+rangeMin(4,4)+rangeMin(4,6)+rangeMin(6,6)$rangeMin(1,1) + rangeMin(1,4) + rangeMin(1,6) + rangeMin(4,4) + rangeMin(4,6) + rangeMin(6,6) $.
This is equal to 10+3+1+9+1+19=43$10 + 3 + 1 + 9 + 1 +19 = 43$.

def f(a,n):
    l,r,s1,s2 = [0]*n, [0]*n, [], []

    for i in range(n):
     count = 1
     while(len(s1)>0 and a[i]<s1[-1][0]):
      count += s1[-1][1]
      s1.pop()
     s1.append((a[i],count))
     l[i] = count

    for i in range(n-1,-1,-1):
     count = 1
     while(len(s2)>0 and a[i]<=s2[-1][0]):
      count += s2[-1][1]
      s2.pop()
     s2.append((a[i],count))
     r[i] = count

    count = 0
    for i in range(n):
     count += a[i]*l[i]*r[i]

    return count

t = int(input())


Solve in Python:
Don Drumphet lives in a nice neighborhood, but one of his neighbors has started to let his house go.  Don Drumphet wants to build a wall between his house and his neighbor’s, and is trying to get the neighborhood association to pay for it.  He begins to solicit his neighbors to petition to get the association to build the wall.  Unfortunately for Don Drumphet, he cannot read very well, has a very limited attention span, and can only remember two letters from each of his neighbors’ names.  As he collects signatures, he insists that his neighbors keep truncating their names until two letters remain, and he can finally read them.

Your code will show Full name of the neighbor and the truncated version of the name as an array. If the number of the characters in name is less than or equal to two, it will return an array containing only the name as is"

def who_is_paying(name):
    if len(name) == 1:
        return [name]
    elif name == '':
        return ['']
    elif name == name[0:2]:
        return [name]
    else:
        return [name,name[0:2]]


Solve in Python:
Don't Drink the Water

Given a two-dimensional array representation of a glass of mixed liquids, sort the array such that the liquids appear in the glass based on their density. (Lower density floats to the top) The width of the glass will not change from top to bottom.

```
======================
|   Density Chart    |
======================
| Honey   | H | 1.36 |
| Water   | W | 1.00 |
| Alcohol | A | 0.87 |
| Oil     | O | 0.80 |
----------------------

[                            [
 ['H', 'H', 'W', 'O'],        ['O','O','O','O']
 ['W', 'W', 'O', 'W'],  =>    ['W','W','W','W']
 ['H', 'H', 'O', 'O']         ['H','H','H','H']
 ]                           ]

 ```

 The glass representation may be larger or smaller. If a liquid doesn't fill a row, it floats to the top and to the left.

def separate_liquids(glass):
    liquids = [];
    comparing = { 'H' : 1.36, 'W' : 1.00, 'A' : 0.87, 'O' : 0.80 }
    for row in glass:
        liquids.extend(row)

    liquids.sort(key=lambda k: comparing[k], reverse=True)

    for i in range(len(glass)):
        for j in range(len(glass[0])):
            glass[i][j] = liquids.pop()

    return glass


Solve in Python:
Doubleville, a small town in Texas, was attacked by the aliens. They have abducted some of the residents and taken them to the a spaceship orbiting around earth. After some (quite unpleasant) human experiments, the aliens cloned the victims, and released multiple copies of them back in Doubleville. So now it might happen that there are 6 identical person named Hugh F. Bumblebee: the original person and its 5 copies. The Federal Bureau of Unauthorized Cloning (FBUC) charged you with the task of determining how many copies were made from each person. To help you in your task, FBUC have collected a DNA sample from each person. All copies of the same person have the same DNA sequence, and different people have different sequences (we know that there are no identical twins in the town, this is not an issue).

-----Input-----

The input contains several blocks of test cases. Each case begins with a line containing two integers: the number 1 <= n <= 20000 people, and the length 1 <= m <= 20 of the DNA sequences. The next n lines contain the DNA sequences: each line contains a sequence of m characters, where each character is either 'A', 'C', 'G' or 'T'.

The input is terminated by a block with n = m = 0 .

-----Output-----
For each test case, you have to output n lines, each line containing a single integer. The first line contains the number of different people that were not copied. The second line contains the number of people that were copied only once (i.e., there are two identical copies for each such person.) The third line contains the number of people that are present in three identical copies, and so on: the i -th line contains the number of persons that are present in i identical copies. For example, if there are 11 samples, one of them is from John Smith, and all the others are from copies of Joe Foobar, then you have to print '1' in the first and the tenth lines, and '0' in all the other lines.

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

9 6
AAAAAA
ACACAC
GTTTTG
ACACAC
GTTTTG
ACACAC
ACACAC
TCCCCC
TCCCCC
0...

def main():
        while True:
                [n, m] = [int(i) for i in input().split()]
                if n == m and n == 0:
                        break
                cache = {}
                for i in range(n):
                        dna = input().rstrip('\n')
                        if dna in cache:
                                cache[dna] = 1 + cache[dna]
                        else:
                                cache[dna] = 1
                c = [0 for i in range(n + 1)]
                for dna in cache:
                        c[cache[dna]] = 1 + c[cache[dna]]
                for i in range(1, n + 1):
                        print(c[i])

def __starting_point():
        main()
__starting_point()


Solve in Python:
Doubly linked list is one of the fundamental data structures. A doubly linked list is a sequence of elements, each containing information about the previous and the next elements of the list. In this problem all lists have linear structure. I.e. each element except the first has exactly one previous element, each element except the last has exactly one next element. The list is not closed in a cycle.

In this problem you are given n memory cells forming one or more doubly linked lists. Each cell contains information about element from some list. Memory cells are numbered from 1 to n.

For each cell i you are given two values:   l_{i} — cell containing previous element for the element in the cell i;  r_{i} — cell containing next element for the element in the cell i.

If cell i contains information about the element which has no previous element then l_{i} = 0. Similarly, if cell i contains information about the element which has no next element then r_{i} = 0. [Image] Three lists are shown on the picture.

For example, for the picture above the values of l and r are the following: l_1 = 4, r_1 = 7; l_2 = 5, r_2 = 0; l_3 = 0, r_3 = 0; l_4 = 6, r_4 = 1; l_5 = 0, r_5 = 2; l_6 = 0, r_6 = 4; l_7 = 1, r_7 = 0.

Your task is to unite all given lists in a single list, joining them to each other in any order. In particular, if the input data already contains a single list, then there is no need to perform any actions. Print the resulting list in the form of values l_{i}, r_{i}.

Any other action, other than joining the beginning of one list to the end of another, can not be performed.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of memory cells where the doubly linked lists are located.

Each of the following n lines contains two integers l_{i}, r_{i} (0 ≤ l_{i}, r_{i} ≤ n) — the cells of the previous and the next element of list for cell i. Value l_{i} = 0 if element in cell i has no previous element in its list. Value r_{i} = 0 if element in cell i has no next element in...

k, n = 0, int(input())
t = [list(map(int, input().split())) for j in range(n)]
for m, (l, r) in enumerate(t, 1):
    if not l:
        if k: t[k - 1][1], t[m - 1][0] = m, k
        k = m
        while r: k, r = r, t[r - 1][1]
for l, r in t: print(l, r)


Solve in Python:
Dr. S. De teaches computer architecture in NIT Patna. Whenever he comes across any good question(with complexity $k$), he gives that question to students within roll number range $i$ and $j$
At the start of semester he assigns score of $10$ to every student in his class if a student submits a question of complexity $k$, his score gets multiplied by $k$
This month he gave $M$ questions and he is wondering what will be mean of maximum scores of all the student. He is busy in improving his finger print attendance module, can you help him?
Input file may be large so try to use fast input output

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a First line of input, two integers $N, M$ i.e. Number of students in the class and number of questions given in this month.
- Next $M$ lines contains 3 integers -$i, j, k$ i.e. starting roll number, end roll number and complexity of the question

-----Output:-----
For each testcase, output in a single line answer - $floor$ value of Mean of maximum possible score for all students.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq N, M \leq 10^5$
- $1 \leq i \leq j \leq N$
- $1 \leq k \leq 100$

-----Subtasks-----
Subtask1
-
$1 \leq T \leq 10$
-
$1 \leq N, M \leq 10^4$
Subtask2
-
Original Constraints

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

-----Sample Output:-----
202

-----EXPLANATION:-----
Initial score of students will be : $[10, 10, 10, 10, 10]$
after solving question 1 scores will be: $[50, 50, 50, 10, 10]$
after solving question 2 scores will be: $[50, 100, 100, 20, 20]$
after solving question 1 scores will be: $[50, 100, 700, 140, 20]$
Hence after all questions mean of maximum scores will $(50+100+700+140+20)/5 = 202$

try:
 t=int(input())
 for a in range(t):
  l=input().split()
  n=int(l[0])
  m=int(l[1])
  d={}
  s=0
  for b in range(m):
   l1=input().split()
   i=int(l1[0])
   j=int(l1[1])
   k=int(l1[2])
   for c in range(i,j+1):
    if c not in d:
     d[c]=10
   for c in range(i,j+1):
    d[c]=d[c]*k
  for i in d:
   s=s+d[i]
  print(s//n)
except:
 pass


Solve in Python:
Dreamoon likes coloring cells very much.

There is a row of $n$ cells. Initially, all cells are empty (don't contain any color). Cells are numbered from $1$ to $n$.

You are given an integer $m$ and $m$ integers $l_1, l_2, \ldots, l_m$ ($1 \le l_i \le n$)

Dreamoon will perform $m$ operations.

In $i$-th operation, Dreamoon will choose a number $p_i$ from range $[1, n-l_i+1]$ (inclusive) and will paint all cells from $p_i$ to $p_i+l_i-1$ (inclusive) in $i$-th color. Note that cells may be colored more one than once, in this case, cell will have the color from the latest operation.

Dreamoon hopes that after these $m$ operations, all colors will appear at least once and all cells will be colored. Please help Dreamoon to choose $p_i$ in each operation to satisfy all constraints.

-----Input-----

The first line contains two integers $n,m$ ($1 \leq m \leq n \leq 100\,000$).

The second line contains $m$ integers $l_1, l_2, \ldots, l_m$ ($1 \leq l_i \leq n$).

-----Output-----

If it's impossible to perform $m$ operations to satisfy all constraints, print "'-1" (without quotes).

Otherwise, print $m$ integers $p_1, p_2, \ldots, p_m$ ($1 \leq p_i \leq n - l_i + 1$), after these $m$ operations, all colors should appear at least once and all cells should be colored.

If there are several possible solutions, you can print any.

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

Output
2 4 1

Input
10 1
1

Output
-1

def main():
    import sys
    input = sys.stdin.readline

    N, M = list(map(int, input().split()))
    L = list(map(int, input().split()))

    if sum(L) < N:
        print(-1)
        return

    ans = [0] * M
    left = N
    for i in range(M-1, -1, -1):
        if left - L[i] >= i:
            ans[i] = left - L[i] + 1
            left -= L[i]
        else:
            if i+L[i]-1 >= N:
                print(-1)
                return
            ans[i] = i+1
            left = i
    print(*ans)

def __starting_point():
    main()

__starting_point()


Solve in Python:
Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS:

You are given two integers $d, m$, find the number of arrays $a$, satisfying the following constraints:  The length of $a$ is $n$, $n \ge 1$  $1 \le a_1 < a_2 < \dots < a_n \le d$  Define an array $b$ of length $n$ as follows: $b_1 = a_1$, $\forall i > 1, b_i = b_{i - 1} \oplus a_i$, where $\oplus$ is the bitwise exclusive-or (xor). After constructing an array $b$, the constraint $b_1 < b_2 < \dots < b_{n - 1} < b_n$ should hold.

Since the number of possible arrays may be too large, you need to find the answer modulo $m$.

-----Input-----

The first line contains an integer $t$ ($1 \leq t \leq 100$) denoting the number of test cases in the input.

Each of the next $t$ lines contains two integers $d, m$ ($1 \leq d, m \leq 10^9$).

Note that $m$ is not necessary the prime!

-----Output-----

For each test case, print the number of arrays $a$, satisfying all given constrains, modulo $m$.

-----Example-----
Input
10
1 1000000000
2 999999999
3 99999998
4 9999997
5 999996
6 99995
7 9994
8 993
9 92
10 1

Output
1
3
5
11
17
23
29
59
89
0

aas = []
for _ in range(int(input())):
    d, m = map(int, input().split())
    A = []
    s = 1
    sus = 0
    while sus + s <= d:
        A.append(s)
        sus += s
        s *= 2
    A.append(d - sum(A))
    ans = 1
    for x in A:
        ans *= (x+1)
        ans %= m
    ans -= 1
    ans %= m
    aas.append(str(ans))
print('\n'.join(aas))


Solve in Python:
Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if $\operatorname{mod}(x, b) \neq 0$ and $\frac{\operatorname{div}(x, b)}{\operatorname{mod}(x, b)} = k$, where k is some integer number in range [1, a].

By $\operatorname{div}(x, y)$ we denote the quotient of integer division of x and y. By $\operatorname{mod}(x, y)$ we denote the remainder of integer division of x and y. You can read more about these operations here: http://goo.gl/AcsXhT.

The answer may be large, so please print its remainder modulo 1 000 000 007 (10^9 + 7). Can you compute it faster than Dreamoon?

-----Input-----

The single line of the input contains two integers a, b (1 ≤ a, b ≤ 10^7).

-----Output-----

Print a single integer representing the answer modulo 1 000 000 007 (10^9 + 7).

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

Output
0

Input
2 2

Output
8

-----Note-----

For the first sample, there are no nice integers because $\operatorname{mod}(x, 1)$ is always zero.

For the second sample, the set of nice integers is {3, 5}.


Solve in Python:
DropCaps means that the first letter of the starting word of the paragraph should be in caps and the remaining lowercase, just like you see in the newspaper.

But for a change, let's do that for each and every word of the given String. Your task is to capitalize every word that has length greater than 2, leaving smaller words as they are.

*should work also on Leading and Trailing Spaces and caps.

```python
drop_cap('apple') => "Apple"
drop_cap('apple of banana'); => "Apple of Banana"
drop_cap('one   space'); => "One   Space"
drop_cap('   space WALK   '); => "   Space Walk   "
```

**Note:** you will be provided atleast one word and should take string as input and return string as output.

def drop_cap(str_):
    return ' '.join( w.capitalize() if len(w) > 2 else w for w in str_.split(' ') )


Solve in Python:
Due to COVID19 all employees of chemical factory are quarantined in home. So, company is organized by automated robots. There are $N$ Containers in company, which are labelled with $1$ to $N$ numbers. There are Total $N$ robots in Company, which are labelled $1$ to $N$.
Each Robot adds $1$ litter Chemical in containers whose labels are multiple of robots’ label. (E.g. robot labelled 2 will add Chemical in containers labelled 2, 4, 6, ….).
Robots follow few rules mentioned below:
- Chemical with $pH<7$ is acidic.
- Chemical with $pH=7$ is neutral.
- Chemical with $pH>7$ is basic.
- Mixture of $1$ litter acid and $1$ litter base makes neutral solution.
- If Container is empty or pH of Chemical in container is equal to
- $7$ then robot adds $1$ litter acidic Chemical.
- If pH of Chemical in container is less than $7$ then robots adds $1$ litter basic Chemical.
Now Chemical is packed in $4$ ways:
- Containers with exactly $2$ litter acid and $1$ litter base are packed at $P1$ cost.
- Containers with acidic Chemical are packed at $P2$ cost. (Here Don’t consider containers with exactly $2$ litter acid and $1$ litter base as we counted them in above rule)
- Containers with $pH=7$ Chemical is packed at $P3$ cost.
- Containers with Basic Chemical are packed at $P4$ cost.
Now $1$ employee given task to find packing cost of containers with labels in range $[ k1, k2]$ (Inclusive). Help him out. As Cost can be large find cost in modulo of $100000007$

-----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 $3$ space separated Integers $N$, $K1$ and $K2$.
- The second and last line contains $4$ space separated Integers $P1$, $P2$, $P3$ and $P4$

-----Output:-----
For each test case, print total cost of packing of containers modulo 100000007.

-----Constraints-----
- $1 \leq T \leq 50000$
- $1 \leq P1, P2, P3, P4 \leq 2*10^7$
- $2 \leq N \leq 2*10^7$
- $1 \leq K1, K2 \leq...

primes={}
def SieveOfEratosthenes(n):

    prime = [True for i in range(n+1)]
    p = 2
    while (p * p <= n):

        if (prime[p] == True):

            # Update all multiples of p
            for i in range(p * p, n+1, p):
                prime[i] = False
        p += 1

    # Print all prime numbers
    for p in range(2, n+1):
        if prime[p]:
            primes[p]=1

t=int(input())

SieveOfEratosthenes(10000)
factors={1:2,2:3}

for i in range(3,5000):
    if i in primes:
        factors[i*i]=1
    else:
        factors[i*i]=2

for case in range(t):
    n,k1,k2=list([int(x) for x in input().split()])
    p1,p2,p3,p4=list([int(x) for x in input().split()])
    costs=[0,p1%100000007,p2%100000007,p3%100000007,p4%100000007]
    cost=0
    numbers_to_remove=0
    for number in factors:
        if number >=k1 and number <=k2:
            cost=cost+costs[factors[number]]
            numbers_to_remove+=1
    cost=(cost%100000007+(k2-k1+1-numbers_to_remove)*costs[3]%100000007)%100000007

    print(cost%100000007)


Solve in Python:
Due to another of his misbehaved,
the primary school's teacher of the young Gauß,  Herr J.G. Büttner, to keep the bored and unruly young schoolboy Karl Friedrich Gauss busy for a good long time, while he teaching arithmetic to his mates,
assigned him the problem of adding up all the whole numbers from 1 through a given number `n`.

Your task is to help the young Carl Friedrich to solve this problem as quickly as you can; so, he can astonish his teacher and rescue his recreation interval.

Here's, an example:

```
f(n=100) // returns 5050
```

It's your duty to verify that n is a valid positive integer number. If not, please, return false (None for Python, null for C#).

> **Note:** the goal of this kata is to invite you to think about some 'basic' mathematic formula and how you can do performance optimization on your code.

> Advanced - experienced users should try to solve it in one line, without loops, or optimizing the code as much as they can.

-----

**Credits:** this kata was inspired by the farzher's kata 'Sum of large ints' . In fact, it can be seen as a sort of prep kata for that one.

def f(n):

    return sum(range(1,n+1,1)) if str(n).isdigit() and int(n) > 0 else None


Solve in Python:
Due to the COVID pandemic, maintaining social distancing is of utmost importance. In this problem, you'd calculate how many days would it take to reach an apocalypse from an initial case if nobody maintains social distancing.
The Earth is flat (for this question) and it's dimensions are $R$ x $C$
The whole Earth is already divided into blocks and the virus can spread in all directions except diagonally. The virus from each newly infected person will spread in all directions in the next day, thus growing exponentially.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Next line contains $R$ and $C$ respectively separated by a space.
- Next line contains $x$ and $y$ respectively separated by a space, denoting the indices of the initial case in the world.

-----Output:-----
For each testcase, output in a single line an integer denoting the number of days after which everyone will be infected.

-----Constraints-----
- $1 \leq T \leq 10^4$
- $2 \leq R,C \leq 10^7$
- $0 \leq x,y \leq 10^7$

-----Subtasks-----
- 10 points : $1 \leq T \leq 5$ and $2 \leq R,C \leq 10$
- 20 points : $2 \leq R,C \leq 10^5$
- 70 points : Original constraints

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

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

-----EXPLANATION:-----
2nd test case:
Assuming, it's a small world of $3$ x $4$
0 is not infected. 1 is infected.
World indexing is like a 2D array:
(0,0) (0,1) (0,2) (0,3)
(1,0) (1,1) (1,2) (1,3)
(2,0) (2,1) (2,2) (2,3)
If this is the case on Day 0:
0 0 0 0
0 1 0 0
0 0 0 0
This will be the case on Day 1:
0 1 0 0
1 1 1 0
0 1 0 0
This will be the case on Day 2:
1 1 1 0
1 1 1 1
1 1 1 0
The End on Day 3:
1 1 1 1
1 1 1 1
1 1 1 1
Thus, answer will be 3

#AUTHOR:: AMAN VERMA
try:
 for _ in range(int(input())):
  row,column=list(map(int,input().split(" ")))
  x_x,y_y=list(map(int,input().split(" ")))
  ab=max((x_x-0),(row-x_x-1))
  ba=max((y_y-0),(column-y_y-1))
  print(ab+ba)
except:
 pass


Solve in Python:
Due to the COVID pandemic, people have been advised to stay at least $6$ feet away from any other person. Now, people are lining up in a queue at the local shop and it is your duty to check whether they are all following this advice.
There are a total of $N$ spots (numbered $1$ through $N$) where people can stand in front of the local shop. The distance between each pair of adjacent spots is $1$ foot. Each spot may be either empty or occupied; you are given a sequence $A_1, A_2, \ldots, A_N$, where for each valid $i$, $A_i = 0$ means that the $i$-th spot is empty, while $A_i = 1$ means that there is a person standing at this spot. It is guaranteed that the queue is not completely empty.
For example, if $N = 11$ and the sequence $A$ is $(0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1)$, then this is a queue in which people are not following the advice because there are two people at a distance of just $3$ feet from each other.
You need to determine whether the people outside the local shop are following the social distancing advice or not. As long as some two people are standing at a distance smaller than 6 feet from each other, it is bad and you should report it, since social distancing is not being followed.

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

-----Output-----
For each test case, print a single line containing the string "YES" if social distancing is being followed or "NO" otherwise (without quotes).

-----Constraints-----
- $1 \le T \le 100$
- $1 \le N \le 100$
- $0 \le A_i \le 1$ for each valid $i$
- at least one spot is occupied

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

-----Example Input-----
3
3
1 0 1
7
1 0 0 0 0 0 1
11
0 1 0 0 0 0 0 1 0 0 1

-----Example Output-----
NO
YES
NO

-----Explanation-----
Example case 1: The first and...

for test_ in range(int(input())):
    n = int(input())
    a = list(map(int,input().strip().split()))
    temp = []
    for i in range(n):
        if a[i] == 1:
            temp.append(i)
    if len(temp) == 1:
        print("YES")
    else:
        dist = []
        for i in range(1,len(temp)):
            dist.append(temp[i]-temp[i-1])
        print("YES" if min(dist)>=6 else "NO")


Solve in Python:
Due to the COVID pandemic, there has been an increase in the number of cases if a hospital. The management has decided to clear a large square area for the patients and arrange for beds. But the beds can't be too near to each other.
The area is of dimension $N$ x $N$
The whole area is already divided into blocks. $1$ means there's a bed in the block, $0$ denotes there isn't. Note, beds placed on consecutive diagonal blocks are safe.
This is a SAFE example:
1 0
0 1
This is an UNSAFE example:
0 1 1
0 0 0
1 0 0
To avoid spreading the virus even further, you have to make sure no two adjacent blocks have beds in them. This is done to maintain distance between beds.
Return an output of "SAFE" if you find the workers have arranged the beds with due consideration to the distance needed. Return "UNSAFE" otherwise.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Next line contains $N$.
- Next $N$ lines will contain $N$ number of space-separated integers $Ai$ which make denote the beds in the area.

-----Output:-----
For each test case, output in a single line whether the total arrangement is "SAFE" or "UNSAFE". Even if there's a single unsafe bed in the whole area, report the whole area as "UNSAFE".

-----Constraints-----
- $1 \leq T \leq 100$
- $0 \leq Ai \leq 1$
- $2 \leq N \leq 100$

-----Subtasks-----
- 30 points : $1 \leq N \leq 7$
- 70 points : Original constraints

-----Sample Input:-----
2
4
1 0 1 0
0 0 0 1
0 1 0 0
1 0 0 1
4
1 0 1 0
0 0 0 0
1 0 1 1
0 1 0 0

-----Sample Output:-----
SAFE
UNSAFE

-----EXPLANATION:-----
Beds placed on blocks diagonally are not a problem.

T = int(input())

for t in range(T):

 N = int(input())

 l = []

 for i in range(N):
  l.append(list(map(int,input().split())))

 flg = True

 for i in range(N):
  for j in range(1,N):
   if l[i][j] == l[i][j-1] and l[i][j] == 1:
    flg = False
    break
  if flg == False:
   break

 if flg == False:
  print('UNSAFE')
 else:
  for i in range(1,N):
   for j in range(N):
    if l[i][j] == l[i-1][j] and l[i][j] == 1:
     flg = False
     break
   if flg == False:
    break
  if flg == False:
   print('UNSAFE')
  else:
   print('SAFE')


Solve in Python:
During Quarantine Time Chef is at home and he was quite confused about what to cook so, he went to his son and asked about what would he prefer to have? He replied, cakes.
Now, chef cook $N$ number of cake and number of layers for every cake is different. After cakes are baked, Chef arranged them in a particular order and then generates a number by putting number of layers of cakes as digit in sequence (e.g., if chef arranges cakes with layers in sequence $2$, $3$ and $5$ then generated number is $235$).
Chef has to make his son powerful in mathematics, so he called his son and ask him to arrange the cakes in all the possible ways and every time when different sequence is generated he has to note down the number. At the end he has to find sum of all the generated numbers. So, help him to complete this task.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- The first line of each test case contains a single integer $N$ denoting number of cakes.
- The second line contains $N$ space-separated integers $L1$ $L2$ … $LN$ layers of the cake.

-----Output:-----
For each test case, print a single line containing sum of all the possible numbers which is generated by arranging cake in different sequence.

-----Constraints :-----
- $1 \leq T  \leq 2*10^5$
- $1 \leq N, L1, L2, L3,…, LN \leq 9$

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

-----Sample Output:-----
2220

-----Explanation:-----
Sum of all possibilities :
$235 + 532 + 253 + 352 + 523 + 325 = 2220 $

# cook your dish here
def fact(nnn):
    f=1
    for i in range(1,nnn+1):
        f=f*i
    # print(f)
    return f
t=int(input())
for i in range(0,t):
    n=int(input())
    lis=list(map(int,input().strip().split()))[:n]
    s=sum(lis)
    st="1"*n
    last=int(st)
    # fac=
    # print(fact(n-1))
    ans=fact(n-1)*s*last
    print(ans)


Solve in Python:
During quarantine chef’s friend invented a game. In this game there are two players, player 1 and Player 2. In center of garden there is one finish circle and both players are at different distances respectively $X$ and $Y$ from finish circle.
Between finish circle and Player 1 there are $X$ number of circles and between finish circle and Player 2 there are $Y$ number of circles. Both player wants to reach finish circle with minimum number of jumps. Player can jump one circle to another circle.
Both players can skip $2^0-1$ or $2^1- 1$ or …. or $2^N-1$ circles per jump. A player cannot skip same number of circles in a match more than once. If both players uses optimal way to reach finish circle what will be the difference of minimum jumps needed to reach finish circle by both players.
If both players reach finish circle with same number of jumps answer will be $0$ $0$.

-----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 2 space separated integers $X$ and $Y$.

-----Output:-----
For each test case, print a single line containing 2 space-separated integers which player win and what is the difference between number of minimum jump required by both players to reach finish circle.

-----Constraints-----
- $1 \leq T \leq 10^5$
- $1 \leq X,Y \leq 2*10^7$

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

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

-----Explanation:-----
Test Case 1:

Test Case 2:

#=============templates==============#
takeArr = lambda: list(map(int,input().split()))
takeList = lambda: list(map(int,input().split()))
import sys
sys.setrecursionlimit(10**6)
# import itertools
# import collections
#==================MAIN==================#
from math import floor,ceil,log2
def powOfPositive(n) :
 pos = floor(log2(n));
 return 2**pos;
def powOfNegative(n) :
 pos = ceil(log2(n));
 return (-1 * pow(2, pos));
def highestPowerOf2(n) :
 if (n > 0) :
  return powOfPositive(n);
 else :
  n = -n;
  return powOfNegative(n);
def main(t):
 x,y = takeArr()
 a,b = x+1,y+1
 sa = sb = 0
 while a:
  a -= highestPowerOf2(a)
  sa += 1
 while b:
  b -= highestPowerOf2(b)
  sb += 1

 winner = 2 if sa>sb else 1 if sb>sa else 0
 score = abs(sa-sb) if winner else 0
 print(winner,score)
 if t>1:
  main(t-1)
main(int(input()))

#==================END==================#


Solve in Python:
During the archaeological research in the Middle East you found the traces of three ancient religions: First religion, Second religion and Third religion. You compiled the information on the evolution of each of these beliefs, and you now wonder if the followers of each religion could coexist in peace.

The Word of Universe is a long word containing the lowercase English characters only. At each moment of time, each of the religion beliefs could be described by a word consisting of lowercase English characters.

The three religions can coexist in peace if their descriptions form disjoint subsequences of the Word of Universe. More formally, one can paint some of the characters of the Word of Universe in three colors: $1$, $2$, $3$, so that each character is painted in at most one color, and the description of the $i$-th religion can be constructed from the Word of Universe by removing all characters that aren't painted in color $i$.

The religions however evolve. In the beginning, each religion description is empty. Every once in a while, either a character is appended to the end of the description of a single religion, or the last character is dropped from the description. After each change, determine if the religions could coexist in peace.

-----Input-----

The first line of the input contains two integers $n, q$ ($1 \leq n \leq 100\,000$, $1 \leq q \leq 1000$) — the length of the Word of Universe and the number of religion evolutions, respectively. The following line contains the Word of Universe — a string of length $n$ consisting of lowercase English characters.

Each of the following line describes a single evolution and is in one of the following formats:   + $i$ $c$ ($i \in \{1, 2, 3\}$, $c \in \{\mathtt{a}, \mathtt{b}, \dots, \mathtt{z}\}$: append the character $c$ to the end of $i$-th religion description.  - $i$ ($i \in \{1, 2, 3\}$) – remove the last character from the $i$-th religion description. You can assume that the pattern is non-empty.

You can assume that no religion will have...

n, q = map(int, input().split())
s = '!' + input()

nxt = [[n + 1] * (n + 2) for _ in range(26)]
for i in range(n - 1, -1, -1):
    c = ord(s[i + 1]) - 97
    for j in range(26):
        nxt[j][i] = nxt[j][i + 1]
    nxt[c][i] = i + 1

w = [[-1], [-1], [-1]]
idx = lambda i, j, k: i * 65536 + j * 256 + k
dp = [0] * (256 * 256 * 256)
def calc(fix=None):
    r = list(map(range, (len(w[0]), len(w[1]), len(w[2]))))
    if fix is not None: r[fix] = range(len(w[fix]) - 1, len(w[fix]))
    for i in r[0]:
        for j in r[1]:
            for k in r[2]:
                dp[idx(i, j, k)] = min(nxt[w[0][i]][dp[idx(i - 1, j, k)]] if i else n + 1,
                                       nxt[w[1][j]][dp[idx(i, j - 1, k)]] if j else n + 1,
                                       nxt[w[2][k]][dp[idx(i, j, k - 1)]] if k else n + 1)
                if i == j == k == 0: dp[idx(i, j, k)] = 0

out = []
for _ in range(q):
    t, *r = input().split()
    if t == '+':
        i, c = int(r[0]) - 1, ord(r[1]) - 97
        w[i].append(c)
        calc(i)
    else:
        i = int(r[0]) - 1
        w[i].pop()
    req = dp[idx(len(w[0]) - 1, len(w[1]) - 1, len(w[2]) - 1)]
    out.append('YES' if req <= n else 'NO')

print(*out, sep='\n')


Solve in Python:
During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants.

Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a_1, the second place participant has rating a_2, ..., the n-th place participant has rating a_{n}. Then changing the rating on the Codesecrof site is calculated by the formula $d_{i} = \sum_{j = 1}^{i - 1}(a_{j} \cdot(j - 1) -(n - i) \cdot a_{i})$.

After the round was over, the Codesecrof management published the participants' results table. They decided that if for a participant d_{i} < k, then the round can be considered unrated for him. But imagine the management's surprise when they found out that the participants' rating table is dynamic. In other words, when some participant is removed from the rating, he is removed from the results' table and the rating is recalculated according to the new table. And of course, all applications for exclusion from the rating are considered in view of the current table.

We know that among all the applications for exclusion from the rating the first application to consider is from the participant with the best rank (the rank with the minimum number), for who d_{i} < k. We also know that the applications for exclusion from rating were submitted by all participants.

Now Sereja wonders, what is the number of participants to be excluded from the contest rating, and the numbers of the participants in the original table in the order of their exclusion from the rating. Pay attention to the analysis of the first test case for a better understanding of the statement.

-----Input-----

The first line contains two integers n, k (1 ≤ n ≤ 2·10^5,  - 10^9 ≤ k ≤ 0). The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — ratings of the participants in the initial table.

-----Output-----

Print the numbers of participants in the order in which they were removed from the table. Print...

n, k = map(int, input().split())
c, v = 0, []
for i, a in enumerate(map(int, input().split())):
    j = i + 1 - len(v)
    d = c - (j - 1) * (n - j) * a
    if d < k:
        v.append(i + 1)
        n -= 1
    else:
        c += a * (j - 1)
print('\n'.join(map(str, v)))


Solve in Python:
Dustin, is the head of an Intelligence agency. He wants to send a secret message S$S$ to his colleague.The message is a single word consisting of only lowercase english letters but he decides to encrypt the message for security reasons. He makes a string M$M$ of length N$N$, such that after deleting a substring of non-zero length from M$M$, the remaining string is S$S$.
Calculate the number of all such possible strings he can form.

-----Input:-----
- First line will contain T$T$, number of testcases. Then the testcases follow.
- For each testcase the there is a single line which contains an integer, N$N$ and then a string S$S$.

-----Output:-----
For each testcase, output the number of possible strings modulo 109+7$10^9+7$.

-----Constraints-----
- 1≤T≤50$1 \leq T \leq 50$
- 1≤N≤1018$1 \leq N \leq 10^{18}$
- 1≤|S|≤105$1 \leq |S| \leq 10^5$
- S$S$ can contain only lowercase English letters.

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

3 a

3 ab

-----Sample Output:-----
1326

76

# cook your dish here
t = int(input())

for _ in range(t):

    n,s = input().split()

    N = int(n)
    r = N - len(s)

    count = 0

    if N>len(s):

     count = pow(26, r-1,(10**9+7))
     count*= (26+25*len(s))

     count = count%(10**9 + 7)
    print(count)


Solve in Python:
Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color c_{i}.

Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.

Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.

A subtree of some vertex is a subgraph containing that vertex and all its descendants.

Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.

-----Input-----

The first line contains single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.

Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree.

The next line contains n integers c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ 10^5), denoting the colors of the vertices.

-----Output-----

Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him.

Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.

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

Output
YES
2
Input
3
1 2
2 3
1 2 3

Output
YES
2
Input
4
1 2
2 3
3 4
1 2 1 2

Output
NO

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

colors = list(map(int, input().split()))

lehet = []
for i in range(n-1):
	if colors[a[i]-1] != colors[b[i]-1]:
		if len(lehet) == 0:
			lehet += [a[i], b[i]]
		else:
			if a[i] in lehet and b[i] in lehet:
				print("NO")
				return
			elif a[i] in lehet:
				lehet = [a[i]]
			elif b[i] in lehet:
				lehet = [b[i]]
			else:
				print("NO")
				return
print("YES")
if len(lehet) == 0:
	lehet = [1]
print(lehet[0])


Solve in Python:
Each floating-point number should be formatted that only the first two decimal places are returned. You don't need to check whether the input is a valid number because only valid numbers are used in the tests.

Don't round the numbers! Just cut them after two decimal places!
```
Right examples:
32.8493 is 32.84
14.3286 is 14.32

Incorrect examples (e.g. if you round the numbers):
32.8493 is 32.85
14.3286 is 14.33
```

def two_decimal_places(number):
    string = str(number)
    n = string.find('.')
    return float(string[0:n+3])


Solve in Python:
Each number should be formatted that it is rounded to two decimal places. You don't need to check whether the input is a valid number because only valid numbers are used in the tests.
```
Example:
5.5589 is rounded 5.56
3.3424 is rounded 3.34
```

def two_decimal_places(n):
    s=("{:.2f}".format(n))
    return float(s)


Solve in Python:
Each test case will generate a variable whose value is 777. Find the name of the variable.

def find_variable():
    for k, v in globals().items():
        if v == 777:
            return k


Solve in Python:
Edo has got a collection of n refrigerator magnets!

He decided to buy a refrigerator and hang the magnets on the door. The shop can make the refrigerator with any size of the door that meets the following restrictions: the refrigerator door must be rectangle, and both the length and the width of the door must be positive integers.

Edo figured out how he wants to place the magnets on the refrigerator. He introduced a system of coordinates on the plane, where each magnet is represented as a rectangle with sides parallel to the coordinate axes.

Now he wants to remove no more than k magnets (he may choose to keep all of them) and attach all remaining magnets to the refrigerator door, and the area of the door should be as small as possible. A magnet is considered to be attached to the refrigerator door if its center lies on the door or on its boundary. The relative positions of all the remaining magnets must correspond to the plan.

Let us explain the last two sentences. Let's suppose we want to hang two magnets on the refrigerator. If the magnet in the plan has coordinates of the lower left corner (x_1, y_1) and the upper right corner (x_2, y_2), then its center is located at ($\frac{x_{1} + x_{2}}{2}$, $\frac{y_{1} + y_{2}}{2}$) (may not be integers). By saying the relative position should correspond to the plan we mean that the only available operation is translation, i.e. the vector connecting the centers of two magnets in the original plan, must be equal to the vector connecting the centers of these two magnets on the refrigerator.

The sides of the refrigerator door must also be parallel to coordinate axes.

-----Input-----

The first line contains two integers n and k (1 ≤ n ≤ 100 000, 0 ≤ k ≤ min(10, n - 1)) — the number of magnets that Edo has and the maximum number of magnets Edo may not place on the refrigerator.

Next n lines describe the initial plan of placing magnets. Each line contains four integers x_1, y_1, x_2, y_2 (1 ≤ x_1 < x_2 ≤ 10^9, 1 ≤ y_1 < y_2 ≤ 10^9) — the coordinates of the lower...

from sys import*
#
def check(u, d, l, r):
    used = [pointsx[i][1] for i in range(l)]
    used += [pointsx[-1 - i][1] for i in range(r)]
    used += [pointsy[i][1] for i in range(u)]
    used += [pointsy[-1 - i][1] for i in range(d)]
    if len(set(used)) > k:
        return DOHERA
    dx = pointsx[-1 - r][0] - pointsx[l][0]
    dy = pointsy[-1 - d][0] - pointsy[u][0]
    dx += dx & 1
    dy += dy & 1
    dx = max(2, dx)
    dy = max(2, dy)
    return dx * dy
#
(n, k) = list(map(int, input().split()))
pointsx = []
pointsy = []
DOHERA = 10 ** 228
for i in range(n):
    a = list(map(int, input().split()))
    pointsx += [(a[0] + a[2], i)]
    pointsy += [(a[1] + a[3], i)]
(pointsx, pointsy) = (sorted(pointsx), sorted(pointsy))
ans = DOHERA
for u in range(0, k + 1):
    for d in range(0, k + 1):
        for l in range(0, k + 1):
            for r in range(0, k + 1):
                if l + r  <= k and u + d <= k:
                    ans = min(ans, check(u, d, l, r))
print(ans // 4)

# Made By Mostafa_Khaled


Solve in Python:
Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number n. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that n is the answer to the arithmetic task for first-graders. In the textbook, a certain positive integer x was given. The task was to add x to the sum of the digits of the number x written in decimal numeral system.

Since the number n on the board was small, Vova quickly guessed which x could be in the textbook. Now he wants to get a program which will search for arbitrary values of the number n for all suitable values of x or determine that such x does not exist. Write such a program for Vova.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^9).

-----Output-----

In the first line print one integer k — number of different values of x satisfying the condition.

In next k lines print these values in ascending order.

-----Examples-----
Input
21

Output
1
15

Input
20

Output
0

-----Note-----

In the first test case x = 15 there is only one variant: 15 + 1 + 5 = 21.

In the second test case there are no such x.

#!/usr/bin/env python3
n = int(input())

ans = []
for i in range(0, 90):
    x = n - i
    if x <= 0: continue

    ds = 0
    s = str(x)
    for c in s:
        ds += ord(c) - ord('0')
    if ds == i:
        ans.append(x)
ans = sorted(ans)

print(len(ans))
print(' '.join(map(str, ans)))


Solve in Python:
Emily and Mia are friends. Emily got Mia’s essay paper, but since she is a prankster, she decided to meddle with the words present in the paper. She changes all the words in the paper into palindromes. To do this, she follows two rules:
- In one operation she can only reduce the value of an alphabet by 1, i.e.  she can change ‘d’ to ‘c’, but she cannot change ‘c’ to ‘d’ or ‘d’ to ‘b’.
- The alphabet ‘a’ will not be reduced any further.
Each reduction in the value of any alphabet is counted as a single operation. Find the minimum number of operations required to convert a given string into a palindrome.

-----Input:-----
- The first line contains an integer $T$, denoting the number of test cases.
- Each test case consists of a string $S$ containing only lowercase characters with no spaces.

-----Output:-----
For each test case on a new line, print the minimum number of operations for the corresponding test case.

-----Constraints-----
- $1<=T<=10$
- $1<=|S|<=10^7$, where $|S|$ denotes length of string S.

-----Sample Input:-----
4
abc
abcba
abcd
cba

-----Sample Output:-----
2
0
4
2

-----EXPLANATION:-----
For the first test case string = “abc”
c->b->a so the string become “aba” which is a palindrome. For this we perform 2 operations

n=int(input())
for i in range(n):
   s=input().strip()
   c=0
   I=0
   J=len(s)-1
   while I<J:
       c+=abs(ord(s[I])-ord(s[J]))
       I+=1
       J-=1
   print(c)


Solve in Python:
Error Handling is very important in coding and seems to be overlooked or not implemented properly.

#Task

Your task is to implement a function which takes a string as input and return an object containing the properties
vowels and consonants. The vowels property must contain the total count of vowels {a,e,i,o,u}, and the total count of consonants {a,..,z} - {a,e,i,o,u}. Handle invalid input and don't forget to return valid ones.

#Input

The input is any random string. You must then discern what are vowels and what are consonants and sum for each category their total occurrences in an object. However you could also receive inputs that are not strings. If this happens then you must return an object with a vowels and consonants total of 0 because the input was NOT a string. Refer to the Example section for a more visual representation of which inputs you could receive and the outputs expected. :)

Example:

```python
Input: get_count('test')
Output: {vowels:1,consonants:3}

Input: get_count('tEst')
Output: {vowels:1,consonants:3}

Input get_count('    ')
Output: {vowels:0,consonants:0}

Input get_count()
Output: {vowels:0,consonants:0}
```

C#

A Counter class has been put in the preloaded section taking two parameters Vowels and Consonants this must be the Object you return!

def get_count(words=None):
    result = {'vowels':0, 'consonants':0}
    vowels, consonants = 'aeiou', 'bcdfghjklmnpqrstvwxyz'

    if type(words) == str:
        result['vowels'] = len([v for v in words.lower() if v in vowels])
        result['consonants'] = len([c for c in words.lower() if c in consonants])

    return result


Solve in Python:
Esoteric languages are pretty hard to program, but it's fairly interesting to write interpreters for them!

Your task is to write a method which will interpret Befunge-93 code! Befunge-93 is a language in which the code is presented not as a series of instructions, but as instructions scattered on a 2D plane; your pointer **starts at the top-left corner** and defaults to **moving right** through the code. Note that the instruction pointer **wraps** around the screen! There is a singular stack which we will assume is unbounded and only contain integers. While Befunge-93 code is supposed to be restricted to 80x25, you need not be concerned with code size. Befunge-93 supports the following instructions (from [Wikipedia](https://en.wikipedia.org/wiki/Befunge)):

- `0-9` Push this number onto the stack.
- `+` Addition: Pop `a` and `b`, then push `a+b`.
- `-` Subtraction: Pop `a` and `b`, then push `b-a`.
- `*` Multiplication: Pop `a` and `b`, then push `a*b`.
- `/` Integer division: Pop `a` and `b`, then push `b/a`, rounded down. If `a` is zero, push zero.
- `%` Modulo: Pop `a` and `b`, then push the `b%a`. If `a` is zero, push zero.
- `!`   Logical NOT: Pop a value. If the value is zero, push `1`; otherwise, push zero.
- ``` ` ``` (backtick) Greater than: Pop `a` and `b`, then push `1` if `b>a`, otherwise push zero.
- `>` Start moving right.
- `<` Start moving left.
- `^` Start moving up.
- `v` Start moving down.
- `?` Start moving in a random cardinal direction.
- `_` Pop a value; move right if `value = 0`, left otherwise.
- `|` Pop a value; move down if `value = 0`, up otherwise.
- `"` Start string mode: push each character's ASCII value all the way up to the next `"`.
- `:` Duplicate value on top of the stack. If there is nothing on top of the stack, push a `0`.
- `\` Swap two values on top of the stack. If there is only one value, pretend there is an extra `0` on bottom of the stack.
- `$` Pop value from the stack and discard it.
- `.` Pop value and output as an integer.
- `,` Pop value and output the ASCII...

import random

def interpret(code):
    output = ""
    coordinates = code.split("\n")
    coordinate = [list(row) for row in coordinates]
    stack = []
    x = 0
    y = 0
    dx = 1
    dy = 0
    a = ""
    temp=1
    ascii_code = 0
    opened = False
    skip_next = False

    while True:
        command = coordinate[y][x]
        if skip_next:
            skip_next = False
            x += dx
            y += dy
            continue
        elif command.isnumeric():
            stack.append(int(command))
        elif command == '>':
            dx = 1
            dy = 0
        elif command == '<':
            dx = -1
            dy = 0
        elif command == '^':
            dx = 0
            dy = -1
        elif command == 'v':
            dx = 0
            dy = 1
        elif command == '?':
            dx = random.randint(-1,1)
            if dx != 0:
                dy = 0
            else:
                dy = random.choice([-1, 1])
        elif command == '"':
            opened = not opened
        elif opened:
            stack.append(ord(command))
        elif command == "+":
            a, b = stack.pop(), stack.pop()
            stack.append(a + b)
        elif command == "-":
            a, b = stack.pop(), stack.pop()
            stack.append(b - a)
        elif command == "*":
            a, b = stack.pop(), stack.pop()
            stack.append(a * b)
        elif command == "/":
            a, b = stack.pop(), stack.pop()
            stack.append(int(b / a) if a != 0 else 0)
        elif command == "%":
            a, b = stack.pop(), stack.pop()
            stack.append(b % a if a != 0 else 0)
        elif command == "!":
            if int(stack[-1]) == 0:
                stack[-1] = 1
            else:
                stack[-1] = 0
        elif command == "`":
            a, b = stack.pop(), stack.pop()
            if b > a:
                stack.append(1)
            else:
                stack.append(0)
        elif command == "_":
            if stack.pop() == 0:
          ...


Solve in Python:
Eugene has to do his homework. But today, he is feeling very lazy and wants to you do his homework. His homework has the following given maths problem.
You are given three integers: A, N, M. You write the number A appended to itself N times in a row. Let's call the resulting big number X. For example, if A = 120, N = 3, then X will be 120120120. Find out the value of X modulo M.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follow.
Each test case is described in one line containing three integers: A, N and M as described in the problem statement.

-----Output-----
For each test case, output a single line containing an integer denoting the value of X modulo M.

-----Constraints-----
- 1 ≤ T ≤ 105
- 0 ≤ A ≤ 109
- 1 ≤ N ≤ 1012
- 2 ≤ M ≤ 109

-----Subtasks-----
Subtask #1 (15 points):
- 0 ≤ A ≤ 100
- 1 ≤ N ≤ 105

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

Subtask #3 (60 points):
- Original constraints

-----Example-----
Input:
2
12 2 17
523 3 11

Output:
5
6

-----Explanation-----
Example 1: As A = 12, N = 2, X = 1212, 1212 modulo 17 = 5
Example 2. As A = 523, N = 3, X = 523523523, 523523523 modulo 11 = 6


Solve in Python:
Eugene loves sequences, especially arithmetic progressions. One day he was asked to solve a difficult problem.

If a sequence of numbers A1, A2, ... , AN form an arithmetic progression A, he was asked to calculate sum of F(Ai), for L ≤ i ≤ R.
F(X) is defined as:

If X < 10 then F(X) = X.

Else F(X) = F(sum_of_digits(X)).

Example:
F(1378) =
F(1+3+7+8) =
F(19) =
F(1 + 9) =
F(10) =
F(1+0) =
F(1) = 1

-----Input-----
- The first line of the input contains an integer T denoting the number of test cases.
- Each test case is described in one line containing four integers: A1 denoting the first element of the arithmetic progression A, D denoting the common difference between successive members of A, and L and R as described in the problem statement.

-----Output-----
- For each test case, output a single line containing one integer denoting sum of F(Ai).

-----Constraints-----
- 1 ≤ T ≤ 105
- 1 ≤ A1 ≤ 109
- 0 ≤ D ≤ 109
- 1 ≤ R ≤ 1018
- 1 ≤ L ≤ R

-----Subtasks-----
- Subtask 1:  0 ≤ D ≤ 100, 1 ≤ A1 ≤ 109, 1 ≤ R ≤ 100  - 15 points
- Subtask 2:  0 ≤ D ≤ 109, 1 ≤ A1 ≤ 109, 1 ≤ R ≤ 106  - 25 points
- Subtask 3: Original constraints - 60 points

-----Example-----
Input:
2
1 1 1 3
14 7 2 4

Output:
6
12

-----Explanation-----
Example case 1.
A = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...}
A1 = 1
A2 = 2
A3 = 3
F(A1) = 1
F(A2) = 2
F(A3) = 3
1+2+3=6
Example case 2.
A = {14, 21, 28, 35, 42, 49, 56, 63, 70, 77,  ...}
A2 = 21
A3 = 28
A4 = 35
F(A2) = 3
F(A3) = 1
F(A4) = 8
3+1+8=12

import math

def f(x):
    if x<10:
        return x
    n = 0
    while x>0:
        n+=x%10
        x/=10
    return f(n)

def ans(a,d,n):
    s = 0
    if d==0:
        print(a*n)
    elif d==1 or d==2 or d==4 or d==5 or d==7 or d==8:
        if n<9:
            while n>0:
                s = s+a
                a = f(a+d)
                n = n-1
            print(s)
        else:
            x = 9
            while x>0:
                s = s+a
                a = f(a+d)
                x = x-1
            s = s*int(n/9)
            n = n%9
            while n>0:
                s = s+a
                a = f(a+d)
                n = n-1
            print(s)
    elif d==3 or d==6:
        if n<3:
            while n>0:
                s = s+a
                a = f(a+d)
                n = n-1
            print(s)
        else:
            x = 3
            while x>0:
                s = s+a
                a = f(a+d)
                x = x-1
            s = s*int(n/3)
            n = n%3
            while n>0:
                s = s+a
                a = f(a+d)
                n = n-1
            print(s)
    else:
        if a==0:
            print(9*(n-1))
        else:
            print(a*n)

t = int(input())
while t>0:
    a,d,l,r = list(map(int,input().split(' ')))
    n = r-l+1
    a = a+(l-1)*d
    a = f(a)
    d = f(d)
    ans(a,d,n)
    t-=1


Solve in Python:
Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, /. Each operand may be an integer or another expression.

Note:

       Division between two integers should truncate toward zero.
       The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.

Example 1:

Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9

Example 2:

Input: ["4", "13", "5", "/", "+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6

Example 3:

Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
Output: 22
Explanation:
  ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22

class Solution:
   def evalRPN(self, tokens):
     """
     :type tokens: List[str]
     :rtype: int
     """
     s = []
     for token in tokens:
       if token == "+":
         a = int(s.pop())
         b = int(s.pop())
         s.append(a+b)
       elif token == "/":
         a = int(s.pop())
         b = int(s.pop())
         s.append(b/a)
       elif token == "*":
         a = int(s.pop())
         b = int(s.pop())
         s.append(a*b)
       elif token == "-":
         a = int(s.pop())
         b = int(s.pop())
         s.append(b-a)
       else:
         s.append(token)
     if len(s) is not 1:
       return False
     else:
       return int(s.pop())


Solve in Python:
Ever heard about Dijkstra's shallowest path algorithm? Me neither. But I can imagine what it would be.

You're hiking in the wilderness of Northern Canada and you must cross a large river. You have a map of one of the safer places to cross the river showing the depths of the water on a rectangular grid. When crossing the river you can only move from a cell to one of the (up to 8) neighboring cells. You can start anywhere along the left river bank, but you have to stay on the map.

An example of the depths provided on the map is

```
[[2, 3, 2],
 [1, 1, 4],
 [9, 5, 2],
 [1, 4, 4],
 [1, 5, 4],
 [2, 1, 4],
 [5, 1, 2],
 [5, 5, 5],
 [8, 1, 9]]
```
If you study these numbers, you'll see that there is a path accross the river (from left to right) where the depth never exceeds 2. This path can be described by the list of pairs `[(1, 0), (1, 1), (2, 2)]`. There are also other paths of equal maximum depth, e.g., `[(1, 0), (1, 1), (0, 2)]`. The pairs denote the cells on the path where the first element in each pair is the row and the second element is the column of a cell on the path.

Your job is to write a function `shallowest_path(river)` that takes a list of lists of positive ints (or array of arrays, depending on language) showing the depths of the river as shown in the example above and returns a shallowest path (i.e., the maximum depth is minimal) as a list of coordinate pairs (represented as tuples, Pairs, or arrays, depending on language) as described above. If there are several paths that are equally shallow, the function shall return a shortest such path. All depths are given as positive integers.

import math
def shallowest_path(river):
    maxsize = 999999999
    steps = [
        (-1,-1),(-1, 0),(-1, 1),
        ( 0,-1),        ( 0, 1),
        ( 1,-1),( 1, 0),( 1, 1)
    ]
    h, w = len(river), len(river[0])
    res = [[]] * h
    for r in range(h):
        res[r] = [(maxsize, [(r,0)])] * w

    points = []
    for r in range(h):
        res[r][0] = (river[r][0], [(r,0)])
        points.append((r, 0))

    while len(points) > 0:
        p = points.pop(0)
        r, c = p[0], p[1]
        deep = res[r][c][0]
        path = res[r][c][1]
        length = len(path)
        if c < w - 1:
            for s in steps:
                nr = r + s[0]
                nc = c + s[1]
                if nr >= 0 and nr < h and nc >= 0 and nc < w and (nr,nc) not in path:
                    tdeep = res[nr][nc][0]
                    tpath = res[nr][nc][1]
                    tlength = len(tpath)
                    ndeep = max(deep, river[nr][nc])
                    if tdeep > ndeep or (tdeep == ndeep and tlength > length + 1):
                        npath = path.copy()
                        npath.append((nr, nc))
                        res[nr][nc] = (ndeep, npath)
                        if (nr, nc) not in points:
                            points.append((nr, nc))

    min_deep, min_path = maxsize, []
    for r in range(h):
        p = res[r][-1]
        if p[0] < min_deep:
            min_deep,  min_path = p[0], p[1]
        elif p[0] == min_deep and len(p[1]) < len(min_path):
            min_deep, min_path = p[0], p[1]
    return min_path


Solve in Python:
Ever since you started work at the grocer, you have been faithfully logging down each item and its category that passes through. One day, your boss walks in and asks, "Why are we just randomly placing the items everywhere? It's too difficult to find anything in this place!" Now's your chance to improve the system, impress your boss, and get that raise!

The input is a comma-separated list with category as the prefix in the form `"fruit_banana"`. Your task is to group each item into the 4 categories `Fruit, Meat, Other, Vegetable` and output a string with a category on each line followed by a sorted comma-separated list of items.

For example, given:

```
"fruit_banana,vegetable_carrot,fruit_apple,canned_sardines,drink_juice,fruit_orange"
```

output:

```
"fruit:apple,banana,orange\nmeat:\nother:juice,sardines\nvegetable:carrot"
```

Assume that:
1. Only strings of the format `category_item` will be passed in
2. Strings will always be in lower case
3. Input will not be empty
4. Category and/or item will not be empty
5. There will be no duplicate items
6. All categories may not have items

def group_groceries(s):
    d = {x: [] for x in "fruit meat other vegetable".split()}
    for x in s.split(","):
        a, b = x.split("_")
        d[a if a in d else "other"].append(b)
    return "\n".join(f"{x}:{','.join(sorted(y))}" for x, y in d.items())


Solve in Python:
Ever the learned traveller, Alan Partridge has pretty strong views on London:

```
"Go to London. I guarantee you'll either be mugged or not appreciated.
Catch the train to London, stopping at Rejection, Disappointment, Backstabbing Central and Shattered Dreams Parkway."
```
Your job is to check that the provided list of stations contains all of the stops Alan mentions. There will be other stations in the array.  Example:

```
['Rejection', 'Disappointment', 'Backstabbing Central', 'Shattered Dreams Parkway']
```

If the stations all appear, return 'Smell my cheese you mother!', if not,  return 'No, seriously, run. You will miss it.'.

Other katas in this series:
Alan Partridge I - Partridge Watch
Alan Partridge II - Apple Turnover

def alan(arr):
    stops = ['Rejection', 'Disappointment', 'Backstabbing Central', 'Shattered Dreams Parkway']
    counter = 0

    for i in stops:
        if i in arr:
            counter += 1

    if counter == len(stops):
        return "Smell my cheese you mother!"
    return "No, seriously, run. You will miss it."


Solve in Python:
Every  positive integer number, that is not prime, may be decomposed in prime factors. For example the prime factors of 20, are:
```
2, 2, and 5, because: 20 = 2 . 2 . 5
```
The first prime factor (the smallest one) of ```20``` is ```2``` and the last one (the largest one) is ```5```. The sum of the first and the last prime factors, ```sflpf``` of 20 is: ```sflpf = 2 + 5 = 7```

The number ```998 ```is the only integer in the range ```[4, 1000]``` that has a value of ```501``` , so its ```sflpf``` equals to 501, but in the range ```[4, 5000]``` we will have more integers with ```sflpf = 501``` and are: ```998, 1996, 2994, 3992, 4990```.

We need a function ```sflpf_data()``` (javascript: ```sflpfData()```that receives two arguments, ```val``` as the value of sflpf and ```nMax``` as a limit, and the function will output a sorted list of the numbers between ```4``` to ```nMax```(included) that have the same value of sflpf equals to ```val```.

Let's see some cases:
```python
sflpf_data(10, 100) == [21, 25, 63]
/// the prime factorization of these numbers are:
Number  Prime Factorization     Sum First and Last Prime Factor
21       = 3 . 7      ---->                 3 + 7 = 10
25       = 5 . 5      ---->                 5 + 5 = 10
63       = 3 . 3 . 7  ---->                 3 + 7 = 10
```
```python
sflpf_data(10, 200) == [21, 25, 63, 105, 125, 147, 189]
sflpf_data(15, 150) == [26, 52, 78, 104, 130]
```
(Advice:Try to discard primes in a fast way to have a more agile code)

Enjoy it!

def sflpf(n):
    i = 2
    first = True
    small = 0
    large = 0
    while i*i <= n:
        while n % i == 0:
            large = i
            if first:
                small = i
                first = False
            n /= i
        i += 1
    if small:
        return small + max(large, n)
    else:
        return 0

sflpf_of = [sflpf(i) for i in range(1, 2*10**4)]

def sflpf_data(val, n):
    return [x for x in range(1, n+1) if sflpf_of[x-1] == val]


Solve in Python:
Every Friday Chef and his N - 1 friends go for a party. At these parties, they play board games. This Friday, they are playing a game named "Boats! Boats! Boats!". In this game players have to transport cookies between Venice and Constantinople. Each player has a personal storage. The players are numbered from 1 to N, Chef is numbered 1. Rules for determining a winner are very difficult, therefore Chef asks you to write a program, which will determine who is a winner.

There are 6 types of cookies. For each cookie in the storage player gets 1 point. Also player gets additional points if he packs his cookies in some boxes as follows:

- A box containing 4 different types of cookies fetches 1 additional point.
- A box containing 5 different types of cookies fetches 2 additional points.
- A box containing 6 different types of cookies fetches 4 additional points.

Obviously a cookie can be put into a single box.

For each player, you know the number of cookies in his storage (denoted by c[i]), also the types of cookies in the storage given denoted by type[i][j].

Your task is to determine the winner of this game. Output "tie" if there are two or more players with same maximum score, "chef" if only Chef has a maximum score, winner's index in all other cases.

-----Input-----

The first line of input contains a single integer T denoting the number of test cases. This will be followed by T test cases.
The first line of each test case contains an integer N denoting the number of players.
The second line of each test case contains an integer c[i] denoting the number of cookies in the i-th storage, followed by c[i] space-separated integers type[i][j] which denote the type if j-th cookie in the storage i-th.

-----Output-----
For each test case, output a single line containing the answer as specified in the statement.

-----Constraints and Subtasks-----Subtask #1 : (20 points)

- 1 ≤ T ≤ 10
- 1 ≤  N  ≤ 100
- 1 ≤  c[i]  ≤  100
- 1 ≤  type[i][j]  ≤  3
Subtask #2 : (80 points)

- 1 ≤ T ≤ 10
- 1 ≤  N  ≤ 100 ...

for _ in range(int(input())):
 n = int(input())
 a = [list(map(int,input().split())) for _ in range(n)]
 p = list()
 for b in a:
  ans = 0
  d = [0]*6
  for i in b[1:]:
   d[i-1]+=1
  d = sorted(d)
  ans+=d[0]*4
  ans+=(d[1]-d[0])*2
  ans+=(d[2]-d[1])
  ans+=b[0]
  p.append(ans)
 if n==1: print("chef")
 else:
  s = sorted(p)
  if s[n-1]==s[n-2]: print("tie")
  elif p[0]==max(p): print("chef")
  else: print(p.index(max(p))+1)


Solve in Python:
Every Friday and Saturday night, farmer counts amount of sheep returned back to his farm (sheep returned on Friday stay and don't leave for a weekend).

Sheep return in groups each of the days -> you will be given two arrays with these numbers (one for Friday and one for Saturday night). Entries are always positive ints, higher than zero.

Farmer knows the total amount of sheep, this is a third parameter. You need to return the amount of sheep lost (not returned to the farm) after final sheep counting on Saturday.

Example 1: Input: {1, 2}, {3, 4}, 15 --> Output: 5

Example 2: Input: {3, 1, 2}, {4, 5}, 21 --> Output: 6

Good luck! :-)

def lostSheep(friday, saturday, total):
    return total - sum(saturday) - sum(friday)


Solve in Python:
Every Turkish citizen has an identity number whose validity can be checked by these set of rules:

- It is an 11 digit number
- First digit can't be zero
- Take the sum of 1st, 3rd, 5th, 7th and 9th digit and multiply it by 7.
Then subtract the sum of 2nd, 4th, 6th and 8th digits from this value.
Modulus 10 of the result should be equal to 10th digit.
- Sum of first ten digits' modulus 10 should be equal to eleventh digit.

Example:

    10167994524
    //  1+1+7+9+5= 23   // "Take the sum of 1st, 3rd, 5th, 7th and 9th digit..."
    //    23 * 7= 161   //  "...and multiply it by 7"
    //   0+6+9+4 = 19   // "Take the sum of 2nd, 4th, 6th and 8th digits..."
    // 161 - 19 = 142   // "...and subtract from first value"
    // "Modulus 10 of the result should be equal to 10th digit"
    10167994524
             ^ = 2 = 142 % 10
    // 1+0+1+6+7+9+9+4+5+2 = 44
    // "Sum of first ten digits' modulus 10 should be equal to eleventh digit"
    10167994524
              ^ = 4 = 44 % 10

Your task is to write a function to check the validity of a given number.
Return `true` or `false` accordingly.

Note: The input can be a string in some cases.

import re

def check_valid_tr_number(n):
    lst = list(map(int,str(n) if isinstance(n,int) else '0'))
    return (isinstance(n,int)
            and len(lst)==11
            and sum(lst[:10]) % 10 == lst[-1]
            and (sum(lst[0:9:2])*7 - sum(lst[1:8:2])) % 10 == lst[-2])


Solve in Python:
Every character in the string “IITMANDI” is given a certain number of points. You are given a scrabble board with only one row. The input contains the positions of score modifiers such as: Double Letter, Triple Letter, Double Word and Triple Word. You need to find the best position to place the string “IITMANDI” such that your score is maximized.
Double Letter - Doubles the number of points you get for the letter placed on the double letter.
Triple Letter - Triples the number of points you get for the letter placed on the triple letter.
Double Word - Doubles the number of points you get for the word. Applied after applying above modifiers.
Triple Word - Triples the number of points you get for the word. Applied after applying the above modifiers.
The word has to be read from left to right. You can’t place it in the reverse direction.

The letters have to be placed continuously on the board.

If there is no modifier or a double word or triple word modifier before a tile, it's score is added to the total score. The double word and triple modifiers are applied at the end.

-----Input Format-----
- First line containes a single integer $T$ - the number of test cases.
- First line of each test case contains a single integer $N$ - the size of the board.
- Second line of each test case contains a string of size $N$ representing the board according to the following convention:

'.' - No modifier

'd' - Double letter

't' - Triple letter

'D' - Double word

'T' - Triple word
- Third line of each test case contains 8 integers corresponding to the points associated with each letter of the string "IITMANDI". Note that the 3 'I's in IITMANDI cannot be interchanged freely. The score of the first 'I' will be equal to the first integer, score of the second 'I' will be equal to the second integer and the score of the last 'I' will be equal to the last integer.

-----Output Format-----
For each test case, output a single integer in a new line, the maximum possible score.

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

# cook your dish here
maxpoints=[]
def maxvaluez(num,arr,sc):

 i=0
 points=0
 mult=1
 while i<8:
  if arr[i]==".":
   points+=sc[i]
   i+=1

  elif arr[i]=="d":
   points+=2*sc[i]
   i+=1

  elif arr[i]=="t":
   points+=3*sc[i]

   i+=1

  elif arr[i]=="D":
   mult=mult*2
   points+=sc[i]
   i+=1

  elif arr[i]=="T":
   mult=mult*3
   points+=sc[i]
   i+=1

  else:
   i+=1

 points=points*mult
 maxpoints.append(points)
 return points

def maxpicker(num,arr,sc):
 for i in range(num-7):
  maxvaluez(num,arr[i:],sc)

 return max(maxpoints)

try:
 t=int(input())
 for i in range(t):
  num = int(input())
  arr = input()
  sc = list(map(int, input().split()))
  print(maxpicker(num,arr,sc))
  maxpoints=[]
except:
 pass


Solve in Python:
Every college has a stud−max$stud-max$ buoy. JGEC$JGEC$ has its own Atul$Atul$ who loves to impress everyone with his smile. A presentation is going on at the auditorium where there are N$N$ rows of M$M$ chairs with people sitting on it. Everyone votes for Atul's presentation skills, but Atul is interested in knowing the maximum$maximum$ amount of vote that he receives either taking K$K$ people vertically$vertically$ or horizontally$horizontally$. Atul$Atul$, however, wants to finish up the presentation party soon, hence asks for your help so that he can wrap up things faster.

-----Input:-----
- First line will contain T$T$, number of test cases. Then the test cases follow.
- Each testcase contains of a single line of input, three integers N$N$, M$M$ and K$K$.
- N lines follow, where every line contains M numbers$numbers$ denoting the size of the sugar cube

-----Output:-----
For each test case, output in a single line the maximum votes Atul can get.

-----Constraints-----
- 1≤T≤$1 \leq T \leq $5
- 1≤N,M≤500$1 \leq N,M \leq 500$
- K≤min(N,M)$K \leq min(N,M)$
- 1≤numbers≤109$1 \leq numbers \leq 10^9$

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

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

-----EXPLANATION:-----
If Atul starts counting votes from (1,4), then he can take the 3 consecutive elements vertically downwards and those are 7,6 and 9 which is the maximum sum possible.

t = int(input())
for i in range(t):
    q = input().split()
    n = int(q[0])
    m = int(q[1])
    k = int(q[2])
    sumax = 0
    b = []
    for j in range(n):
        a = [int(k) for k in input().split()]
        b = b + [a]
    for j in range(n):
        su = 0
        for x in range(k):
            su = su +b[j][x]
            if su > sumax:
                sumax = su
        for a in range(1, m-k+1):
            su = su - b[j][a-1] +b[j][k+a-1]
            if su > sumax:
                sumax = su
    for j in range(m):
        su = 0
        for x in range(k):
            su = su + b[x][j]
            if su > sumax:
                sumax = su
        for a in range(1, n-k+1):
            su = su - b[a-1][j] + b[a+k-1][j]
            if su > sumax:
                sumax = su
    print(sumax)


Solve in Python:
Every day we can send from the server a certain limit of e-mails.

Task:
Write a function that will return the integer number of e-mails sent in the percentage of the limit.

Example:
```
limit       - 1000;
emails sent - 101;
return      - 10%; // becouse integer from 10,1 = 10
```

Arguments:

Integer, limit;
Integer, number of e-mails sent today;

When:

the argument ```$sent = 0```, then return the message: "No e-mails sent";
the argument ```$sent >= $limit```, then return the message: "Daily limit is reached";
the argument ```$limit is empty```, then default ```$limit = 1000``` emails;

Good luck!

def get_percentage(sent, limit=1000):
    return "No e-mails sent" if not sent \
        else "%d%%" % (100*sent//limit) if sent < limit \
            else "Daily limit is reached"