Solve in Python:
The annual snake festival is upon us, and all the snakes of the kingdom have gathered to participate in the procession. Chef has been tasked with reporting on the procession, and for this he decides to first keep track of all the snakes. When he sees a snake first, it'll be its Head, and hence he will mark a 'H'. The snakes are long, and when he sees the snake finally slither away, he'll mark a 'T' to denote its tail. In the time in between, when the snake is moving past him, or the time between one snake and the next snake, he marks with '.'s.
Because the snakes come in a procession, and one by one, a valid report would be something like "..H..T...HTH....T.", or "...", or "HT", whereas "T...H..H.T", "H..T..H", "H..H..T..T" would be invalid reports (See explanations at the bottom).
Formally, a snake is represented by a 'H' followed by some (possibly zero) '.'s, and then a 'T'. A valid report is one such that it begins with a (possibly zero length) string of '.'s, and then some (possibly zero) snakes between which there can be some '.'s, and then finally ends with some (possibly zero) '.'s.

Chef had binged on the festival food and had been very drowsy. So his report might be invalid. You need to help him find out if his report is valid or not.

-----Input-----
- The first line contains a single integer, R, which denotes the number of reports to be checked. The description of each report follows after this.
- The first line of each report contains a single integer, L, the length of that report.
- The second line of each report contains a string of length L. The string contains only the characters '.', 'H', and 'T'.

-----Output-----
- For each report, output the string "Valid" or "Invalid" in a new line, depending on whether it was a valid report or not.

-----Constraints-----
- 1 ≤ R ≤ 500
- 1 ≤ length of each report ≤ 500

-----Example-----
Input:
6
18
..H..T...HTH....T.
3
...
10
H..H..T..T
2
HT
11
.T...H..H.T
7
H..T..H

Output:
Valid
Valid
Invalid
Valid
Invalid
Invalid

-----Explanation-----
"H..H..T..T" is...

t = int(input())
for i in range(t):
 n = int(input())
 a = input()
 valid = True
 count = 0
 for j in a:
  if j == 'H':
   count+=1
   if count>1:
    valid= False
  if j == 'T':
   count-=1
   if count<0:
    valid= False
 if valid and count==0:
  print('Valid')
 else:
  print('Invalid')


Solve in Python:
The auditorium of Stanford University is made up of L*R matrix (assume each coordinate has a chair). On the occasion of an event Chef was called as a chief guest. The auditorium was filled with males (M) and females (F), occupying one chair each. Our Chef is very curious guy, so he asks the gatekeeper some queries. The queries were as follows: Is there any K*K sub-matrix in the auditorium which contains all Males or Females.

-----Input-----
- The first line contains three space-separated integers L, R  and Q describing the dimension of the auditorium and the number of questions Chef will ask.
- Each of next L lines contains R characters (M or F).
- Next Q lines contains K and a character (M or F).

-----Output-----
- For each query output "yes" (without quotes) if there exist any K*K sub-matrix in the auditorium which contains all Males (if he asks about Male) or Females (if he asks about Female), otherwise output "no" (without quotes).

-----Constraints and Subtasks-----
- 1 <= L, R, K <= 1000
- 1 <= Q <= 1e6
Subtask 1: 30 points
- 1 <= L, R, Q <= 200
Subtask 2: 70 points
- Original Contraints

-----Example-----
Input:
4 3 3
MMF
MMM
FFM
FFM
2 F
3 M
1 M

Output:
yes
no
yes

def chk():
 for r in range(i+1, i+k):
  if m[r][ix:ix+k] != ss:
   return False
 return True
l, r, q = list(map(int, input().split()))
m = [input().replace(" ", "") for _ in range(l)]
for _ in range(q):
 k, s = input().split()
 k = int(k)
 ss = k * s
 ans = "no"
 for i in range(l-k+1):
  st = 0
  while ss in m[i][st:]:
   ix = m[i].index(ss, st)
   if chk():
    ans = "yes"
    break
   st = ix + 1
  if ans == "yes":break
 print(ans)


Solve in Python:
The biggest event of the year – Cota 2 world championship "The Innernational" is right around the corner. $2^n$ teams will compete in a double-elimination format (please, carefully read problem statement even if you know what is it) to identify the champion.

Teams are numbered from $1$ to $2^n$ and will play games one-on-one. All teams start in the upper bracket.

All upper bracket matches will be held played between teams that haven't lost any games yet. Teams are split into games by team numbers. Game winner advances in the next round of upper bracket, losers drop into the lower bracket.

Lower bracket starts with $2^{n-1}$ teams that lost the first upper bracket game. Each lower bracket round consists of two games. In the first game of a round $2^k$ teams play a game with each other (teams are split into games by team numbers). $2^{k-1}$ loosing teams are eliminated from the championship, $2^{k-1}$ winning teams are playing $2^{k-1}$ teams that got eliminated in this round of upper bracket (again, teams are split into games by team numbers). As a result of each round both upper and lower bracket have $2^{k-1}$ teams remaining. See example notes for better understanding.

Single remaining team of upper bracket plays with single remaining team of lower bracket in grand-finals to identify championship winner.

You are a fan of teams with numbers $a_1, a_2, ..., a_k$. You want the championship to have as many games with your favourite teams as possible. Luckily, you can affect results of every championship game the way you want. What's maximal possible number of championship games that include teams you're fan of?

-----Input-----

First input line has two integers $n, k$ — $2^n$ teams are competing in the championship. You are a fan of $k$ teams ($2 \le n \le 17; 0 \le k \le 2^n$).

Second input line has $k$ distinct integers $a_1, \ldots, a_k$ — numbers of teams you're a fan of ($1 \le a_i \le 2^n$).

-----Output-----

Output single integer — maximal possible number of championship games that include...


Solve in Python:
The built-in print function for Python class instances is not very entertaining.

In this Kata, we will implement a function ```show_me(instname)``` that takes an instance name as parameter and returns the string "Hi, I'm one of those (classname)s! Have a look at my (attrs).", where (classname) is the class name and (attrs) are the class's attributes. If (attrs) contains only one element, just write it. For more than one element (e.g. a, b, c), it should list all elements sorted by name in ascending order (e.g. "...look at my a, b and c").

Example:
For an instance ```porsche = Vehicle(2, 4, 'gas')``` of the class
```
class Vehicle:
  def __init__(self, seats, wheels, engine):
    self.seats = seats
    self.wheels = wheels
    self.engine = engine
```
the function call ```show_me(porsche)``` should return the string 'Hi, I'm one of those Vehicles! Have a look at my engine, seats and wheels.'

Hints:
For simplicity we assume that the parameter "instname" is always a class instance.

def show_me(instname):
    return "Hi, I'm one of those {}s! Have a look at my {}.".format(instname.__class__.__name__, ', '.join(list(instname.__dict__.keys())) if len(list(instname.__dict__.keys())) == 1 else ', '.join(sorted(list(instname.__dict__.keys()))).rpartition(', ')[0] + ' and ' + ', '.join(sorted(list(instname.__dict__.keys()))).rpartition(', ')[2])


Solve in Python:
The business has been suffering for years under the watch of Homie the Clown. Every time there is a push to production it requires 500 hands-on deck, a massive manual process, and the fire department is on stand-by along with Fire Marshall Bill the king of manual configuration management. He is called a Fire Marshall because production pushes often burst into flames and rollbacks are a hazard.

The business demands change and as such has hired a new leader who wants to convert it all to DevOps…..there is a new Sheriff in town.

The Sheriff's first order of business is to build a DevOps team. He likes Microservices, Cloud, Open-Source, and wants to push to production 9500 times per day without even pressing a button, beautiful seamless immutable infrastructure properly baked in the Continuous Delivery oven is the goal.

The only problem is Homie the Clown along with Legacy Pete are grandfathered in and union, they started out in the era of green screens and punch cards and are set in their ways. They are not paid by an outcome but instead are measured by the amount of infrastructure under management and total staff headcount.

The Sheriff has hired a new team of DevOps Engineers. They advocate Open Source, Cloud, and never doing a manual task more than one time. They believe Operations to be a first class citizen with Development and are preparing to shake things up within the company.

Since Legacy is not going away, yet, the Sheriff's job is to get everyone to cooperate so DevOps and the Cloud will be standard. The New Kids on the Block have just started work and are looking to build common services with Legacy Pete and Homie the Clown.
```
Every Time the NKOTB propose a DevOps pattern……

Homie stands up and says "Homie don't Play that!"

IE:

NKOTB Say -> "We need Cloud now!"

Homie Say -> "Cloud! Homie dont play that!"

NKOTB Say -> "We need Automation now!"

Homie Say -> "Automation! Homie dont play that!"

NKOTB Say -> "We need Microservices now!"

Homie Say -> "Microservices! Homie dont play...

res1 = "{}! Homie dont play that!".format
res2 = "{} monitoring objections, {} automation, {} deployment pipeline, {} cloud, and {} microservices.".format
get = __import__("re").compile("We need (\w+) now!").search

def nkotb_vs_homie(requirements):
    return [res1(get(req).group(1).capitalize()) for reqs in requirements for req in reqs] + [res2(*map(len, requirements))]


Solve in Python:
The bustling town of Siruseri has just one sports stadium. There are a number of schools, colleges, sports associations, etc. that use this stadium as the venue for their sports events.
Anyone interested in using the stadium has to apply to the Manager of the stadium indicating both the starting date (a positive integer $S$) and the length of the sporting event in days (a positive integer $D$) they plan to organise. Since these requests could overlap it may not be possible to satisfy everyone. Also, there should be at least one gap day between any two approved events, so that the stadium can be cleaned.
It is the job of the Manager to decide who gets to use the stadium and who does not. The Manager, being a genial man, would like to keep as many organisations happy as possible and hence would like to allocate the stadium so that maximum number of events are held.
Suppose, for example, the Manager receives the following 4 requests:
$ $
Event No.   Starting Date        Length

1                   2                    5
2                   9                    7
3                  15                    6
4                   9                    3

$ $
He would allot the stadium to events $1$, $4$ and $3$. Event $1$ begins on day $2$ and ends on day $6$, event $4$ begins on day $9$ and ends on day $11$ and event $3$ begins on day $15$ and ends on day $20$. You can verify that it is not possible to schedule all the $4$ events (since events $2$ and $3$ overlap and only one of them can get to use the stadium).
Your task is to help the manager find the best possible allotment (i.e., the maximum number of events that can use the stadium).

-----Input:-----
The first line of the input will contain a single integer $N$ indicating the number of events for which the Manager has received a request. Lines $2,3,...,N+1$ describe the requirements of the $N$ events. Line $i+1$ contains two integer $S_i$ and $D_i$ indicating the starting date and the duration of event $i$.

-----Output:-----
Your output must consist of a...

arr=[]
for _ in range(int(input())) :
    start,end=[int(x) for x in input().split()]
    arr.append((start,start+end))
arr.sort()
ans=1
check=arr[0][1]
for i in range(1,len(arr)) :
    if arr[i][0] > check :
        ans+=1
        check = arr[i][1]
print(ans)


Solve in Python:
The cat wants to lay down on the table, but the problem is that we don't know where it is in the room!

You'll get in input:
 - the cat coordinates as a list of length 2, with the row on the map and the column on the map.
 - the map of the room as a list of lists where every element can be 0 if empty or 1 if is the table (there can be only one 1 in the room / lists will never be empty).

# Task:

You'll need to return the route to the table, beginning from the cat's starting coordinates, as a String. The route must be a sequence of letters U, D, R, L that means Up, Down, Right, Left. The order of the letters in the output isn't important.

# Outputs:

* The route for the cat to reach the table, as a string
* If there isn't a table in the room you must return "NoTable"
* if the cat is outside of the room you must return "NoCat" (this output has the precedence on the above one).
* If the cat is alredy on the table, you can return an empty String.

# Example:

```
cat = [0,1]
room =[[0,0,0], [0,0,0], [0,0,1]]

The route will be "RDD", or "DRD" or "DDR"
```

def put_the_cat_on_the_table(cat, room):
    ty,tx = next(((i,j) for i,row in enumerate(room) for j,v in enumerate(row) if v==1),('No','Table'))
    cy,cx = cat
    if cy<0 or cx<0 or cy+1>len(room) or cx+1>len(room[0]): return 'NoCat'
    if ty+tx == 'NoTable': return ty+tx
    return ('U' if (ty-cy)<0 else 'D')*(abs(ty-cy)) + ('L' if (tx-cx)<0 else 'R')*(abs(tx-cx))


Solve in Python:
The central dogma of molecular biology is that DNA is transcribed into RNA, which is then tranlsated into protein. RNA, like DNA, is a long strand of nucleic acids held together by a sugar backbone (ribose in this case). Each segment of three bases is called a codon. Molecular machines called ribosomes translate the RNA codons into amino acid chains, called polypeptides which are then folded into a protein.

Protein sequences are easily visualized in much the same way that DNA and RNA are, as large strings of letters. An important thing to note is that the 'Stop' codons do not encode for a specific amino acid. Their only function is to stop translation of the protein, as such they are not incorporated into the polypeptide chain. 'Stop' codons should not be in the final protein sequence. To save a you a lot of unnecessary (and boring) typing the keys and values for your amino acid dictionary are provided.

Given a string of RNA, create a funciton which translates the RNA into its protein sequence. Note: the test cases will always produce a valid string.

```python
protein('UGCGAUGAAUGGGCUCGCUCC') returns 'CDEWARS'
```

Included as test cases is a real world example! The last example test case encodes for a protein called green fluorescent protein; once spliced into the genome of another organism, proteins like GFP allow biologists to visualize cellular processes!

Amino Acid Dictionary
----------------------

```python
    # Phenylalanine
    'UUC':'F', 'UUU':'F',
    # Leucine
    'UUA':'L', 'UUG':'L', 'CUU':'L', 'CUC':'L','CUA':'L','CUG':'L',
    # Isoleucine
    'AUU':'I', 'AUC':'I', 'AUA':'I',
    # Methionine
    'AUG':'M',
    # Valine
    'GUU':'V', 'GUC':'V', 'GUA':'V', 'GUG':'V',
    # Serine
    'UCU':'S', 'UCC':'S', 'UCA':'S', 'UCG':'S', 'AGU':'S', 'AGC':'S',
    # Proline
    'CCU':'P', 'CCC':'P', 'CCA':'P', 'CCG':'P',
    # Threonine
    'ACU':'T', 'ACC':'T', 'ACA':'T', 'ACG':'T',
    # Alanine
    'GCU':'A', 'GCC':'A', 'GCA':'A', 'GCG':'A',
    # Tyrosine
   ...


Solve in Python:
The characters of Chima need your help. Their weapons got mixed up! They need you to write a program that accepts the name of a character in Chima then tells which weapon he/she owns.

For example: for the character `"Laval"` your program should return the solution `"Laval-Shado Valious"`

You must complete the following character-weapon pairs:

* Laval-Shado Valious,
* Cragger-Vengdualize,
* Lagravis-Blazeprowlor,
* Crominus-Grandorius,
* Tormak-Tygafyre,
* LiElla-Roarburn.

Return `"Not a character"` for invalid inputs.

weapon_map = {
'Laval':'Laval-Shado Valious',
'Cragger': 'Cragger-Vengdualize',
'Lagravis':'Lagravis-Blazeprowlor',
'Crominus': 'Crominus-Grandorius',
'Tormak': 'Tormak-Tygafyre',
'LiElla': 'LiElla-Roarburn',
}

def identify_weapon(character):
    return weapon_map.get(character, 'Not a character')


Solve in Python:
The chef has a number N, Cheffina challenges chef to form the largest number X from the digits of N.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, $N$.

-----Output:-----
For each test case, output in a single line answer.

-----Constraints-----
- $1 \leq T \leq 10^5$
- $1 \leq N \leq 10^6$

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

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

# cook your dish here
n=int(input())
l=[]
for i in range(n):
    a=int(input())
    l.append(a)
for i in l:
    b = list(map(int, str(i)))
    b.sort(reverse=True)
    s = [str(i) for i in b]
    r = int("".join(s))
    print(r)


Solve in Python:
The chef has a recipe he wishes to use for his guests,
but the recipe will make far more food than he can serve to the guests.
The chef therefore would like to make a reduced version of the recipe which has the same ratios of ingredients, but makes less food.
The chef, however, does not like fractions.
The original recipe contains only whole numbers of ingredients,
and the chef wants the reduced recipe to only contain whole numbers of ingredients as well.
Help the chef determine how much of each ingredient to use in order to make as little food as possible.

-----Input-----
Input will begin with an integer T, the number of test cases.
Each test case consists of a single line.
The line begins with a positive integer N, the number of ingredients.
N integers follow, each indicating the quantity of a particular ingredient that is used.

-----Output-----
For each test case, output exactly N space-separated integers on a line,
giving the quantity of each ingredient that the chef should use in order to make as little food as possible.

-----Sample Input-----
3
2 4 4
3 2 3 4
4 3 15 9 6

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

-----Constraints-----
T≤100

2≤N≤50

All ingredient quantities are between 1 and 1000, inclusive.

#! /usr/bin/env python

from sys import stdin
from functools import reduce

def gcd(a,b):
	while b!=0:
		a,b=b,a%b
	return a

def gcdl(l):
	return reduce(gcd, l[1:],l[0])

def __starting_point():
	T=int(stdin.readline())
	for case in range(T):
		numbers=list(map(int, stdin.readline().split()[1:]))
		g=gcdl(numbers)

		numbers=[n/g for n in numbers]
		print(" ".join([str(x) for x in numbers]))

__starting_point()


Solve in Python:
The chef has one array of N natural numbers (might be in sorted order). Cheffina challenges chef to find the total number of inversions in the array.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains two lines of input, $N$.
- N space-separated natural numbers.

-----Output:-----
For each test case, output in a single line answer as the total number of inversions.

-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq N \leq 10^5$
- $1 \leq arr[i] \leq 10^5$

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

-----Sample Output:-----
8

def merge(A, aux, low, mid, high):

    k = i = low
    j = mid + 1
    inversionCount = 0

    # While there are elements in the left and right runs
    while i <= mid and j <= high:
        if A[i] <= A[j]:
            aux[k] = A[i]
            i = i + 1
        else:
            aux[k] = A[j]
            j = j + 1
            inversionCount += (mid - i + 1)  # NOTE

        k = k + 1

    # Copy remaining elements
    while i <= mid:
        aux[k] = A[i]
        k = k + 1
        i = i + 1

    # Don't need to copy second half

    # copy back to the original list to reflect sorted order
    for i in range(low, high + 1):
        A[i] = aux[i]

    return inversionCount

# Sort list [low..high] using auxiliary space aux
def mergeSort(A, aux, low, high):

    # Base case
    if high == low:  # if run size == 1
        return 0

    # find mid point
    mid = low + ((high - low) >> 1)
    inversionCount = 0

    # recursively split runs into two halves until run size == 1,
    # then merge them and return back up the call chain

    inversionCount += mergeSort(A, aux, low, mid)        # split / merge left half
    inversionCount += mergeSort(A, aux, mid + 1, high)   # split / merge right half
    inversionCount += merge(A, aux, low, mid, high)      # merge the two half runs

    return inversionCount

for _ in range(int(input())):
    n=int(input())
    l=list(map(int,input().split()))
    aux=l.copy()
    print(mergeSort(l,aux,0,len(l)-1))


Solve in Python:
The chef is having one array of N natural numbers(numbers may be repeated). i.e. All natural numbers must be less than N. Chef wants to rearrange the array and try to place a natural number on its index of the array, i.e array[i]=i. If multiple natural numbers are found for given index place one natural number to its index and ignore others.i.e. arr[i]=i and multiple i found in array ignore all remaining i's If any index in the array is empty place 0 at that place. i.e. if for arr[i], i is not present do arr[i]=0.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains two lines of input.
- First-line has $N$ denoting the size of an array.
- Second-line has $N$ space-separated natural numbers.

-----Output:-----
For each test case, output in a single line with the new rearranged array.

-----Constraints-----
- $1 \leq T \leq 10^3$
- $2 \leq N \leq 10^3$
- $arr[i] \leq N-1$

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

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

-----EXPLANATION:-----
For 1) $1$ occurs twice in the array hence print 0 at 0th index and 1 at 1st index
For 2) $1$ occurs thrice and 2 once in the array hence print 0 at 0th index and 1 at 1st index, 2 at 2nd index and 0 at 3rd index.

from collections import Counter
try:
    for _ in range(int(input())):
        n=int(input())
        a=list(map(int,input().split()))
        d=dict(Counter(a))
        new=[]
        for i in range(0,n):
            if i in d:
                new.append(i)
            else:
                new.append(0)

        print(*new)
except:
    pass


Solve in Python:
The chef is having one array of natural numbers. Cheffina challenges chef that find the sum of weights all the natural numbers present in the array, but the main problem is that all numbers have not original weights. After every 6 natural numbers weight is set to 1 as weight increases by 1 after that. (i.e. weight of 1 is 1, weight of 2 is 2 but the weight of 7 is 1 and weight of 8 is 2 and so on…). Help the chef to find the sum.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains two lines of input, one integer $N$.
- Next line has N space separate natural numbers.

-----Output:-----
For each testcase, output in a single line answer.

-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq N \leq 10^5$
- $1 \leq arr[i] \leq 10^6$

-----Sample Input:-----
1
6
6 7 9 11 4 16

-----Sample Output:-----
23

-----EXPLANATION:-----
Array after conversion = [6, 1, 3, 5, 4, 4]

for _ in range(int(input())):
    n=int(input())
    arr1=list(set(map(int,input().split())))
    sum=0
    for i in arr1:
        if i%6==0:
            sum+=6
        else:
            sum+=(i%6)
    print(sum)


Solve in Python:
The chef is having one string of English lower case alphabets only. The chef wants to remove all "abc" special pairs where a,b,c are occurring consecutively. After removing the pair, create a new string and again remove "abc" special pair from a newly formed string. Repeate the process until no such pair remains in a string.

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

-----Output:-----
For each testcase, output in a single line answer, new String with no "abc" special pair.

-----Constraints:-----
$T \leq 2 $
$1 \leq String length \leq 1000 $

-----Sample Input:-----
2
aabcc
bababccc

-----Sample Output:-----
ac
bc

-----EXPLANATION:-----
For 1) after removing "abc" at middle we get a new string as ac.
For 2) string = bababccc
newString1 = babcc  // After removing middle "abc"
newString2 = bc   //After removing "abc"

for _ in range(int(input())):
    has = input()
    while "abc" in has:
        has = has.replace("abc", "")
    print(has)


Solve in Python:
The chef is placing the laddus on the large square plat. The plat has the side of length N. Each laddu takes unit sq.unit area. Cheffina comes and asks the chef one puzzle to the chef as, how many squares can be formed in this pattern with all sides of new square are parallel to the original edges of the plate.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $N$.

-----Output:-----
For each test case, output in a single line answer as maximum squares on plate satisfying the condition.

-----Constraints-----
- $1 \leq T \leq 1000$
- $1 \leq N \leq 10^5$

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

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

-----EXPLANATION:-----
For 1) Only 1 Square
For 2) 4 squares with area 1 sq.unit
1 square with area 4 sq.unit

# cook your dish here
for t in range(int(input())):
 x=0
 n=int(input())
 x=n*(n+1)*(2*n+1)//6
 print(x)


Solve in Python:
The chef is playing a game of long distance. Chef has a number K and he wants to find the longest distance between the index of the first and the last occurrence of K in a given array of N numbers.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains two lines of input.
- Next line with Two integers in one line $K, N$.
- Next line with $N$ space-separated integers.

-----Output:-----
For each test case, output in a single line answer as the index of first and last occurrence of K in the given array.
Note: Here Indexing is from 1 not  0 based.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq k \leq 10^5$
- $1 \leq N \leq 10^5$

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

-----Sample Output:-----
3
0

-----EXPLANATION:-----
For 1) Index of First and last occurrence of 2 in the given array is at 1 and 4, i.e. distance is 3.
For 2) 4 occurs only once in the given array hence print 0.

# cook your dish here
t=int(input())
for _ in range(t):
    k,n=map(int,input().split())
    l=list(map(int,input().split()))
    f=-1
    s=-1
    for i in range(n):
        if l[i]==k:
            f=i
            break
    for  i in range(n-1,-1,-1):
        if l[i]==k:
            s=i
            break
    if f==-1 or s==-1:
        print(0)
    else:
        s+=1
        f+=1
        print(s-f)


Solve in Python:
The chef is trying to decode some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq K \leq 10$

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

-----Sample Output:-----
0
0
1 1
0
1 1
2 3 5
0
1 1
2 3 5
8 13 21 34

-----EXPLANATION:-----
No need, else pattern can be decode easily.

# cook your dish here
t = int(input())
tp = [];
tp.append(0)
tp.append(1)
for i in range(2,5050):
 tp.append(tp[i-1]+tp[i-2])
for i in range(t):
 n = int(input())
 c = 0
 for j in range(1,n+1):
  for k in range(1,j+1):
   print(tp[c],sep = ' ',end=' ')
   c += 1;
  print()


Solve in Python:
The chef is trying to decode some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$

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

-----Sample Output:-----
0
01
10
010
101
010
0101
1010
0101
1010

-----EXPLANATION:-----
No need, else pattern can be decode easily.

# cook your dish here
t=int(input())
for _ in range(t):
    n=int(input())
    s=""
    for i in range(1,n+1):
        if i%2!=0:
            s+='1'
        else:
            s+='0'
    s1=''
    for i in range(1,n+1):
        if i%2==0:
            s1+='1'
        else:
            s1+='0'
    for i in range(1,n+1):
        if i%2==0:
            print(s)
        else:
            print(s1)


Solve in Python:
The chef is trying to decode some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$

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

-----Sample Output:-----
0
01
10
012
101
210
0123
1012
2101
3210

-----EXPLANATION:-----
No need, else pattern can be decode easily.

import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")
inp = lambda: list(map(int,sys.stdin.readline().rstrip("\r\n").split()))
#______________________________________________________________________________________________________
# from math import *
# from bisect import *
# from heapq import *
# from collections import defaultdict as dd
# from collections import OrderedDict as odict
from collections import Counter as cc
# from collections import deque
# sys.setrecursionlimit(2*(10**5)+100) this is must for dfs
mod = 10**9+7; md = 998244353
# ______________________________________________________________________________________________________
# segment tree for range minimum query
# sys.setrecursionlimit(10**5)
# n = int(input())
# a = list(map(int,input().split()))
# st = [float('inf') for i in range(4*len(a))]
# def build(a,ind,start,end):
# 	if start == end:
# 		st[ind] = a[start]
# 	else:
# 		mid = (start+end)//2
# 		build(a,2*ind+1,start,mid)
# 		build(a,2*ind+2,mid+1,end)
# 		st[ind] = min(st[2*ind+1],st[2*ind+2])
# build(a,0,0,n-1)
# def query(ind,l,r,start,end):
# 	if start>r or end<l:
# 		return float('inf')
# 	if l<=start<=end<=r:
# 		return st[ind]
# 	mid = (start+end)//2
# 	return min(query(2*ind+1,l,r,start,mid),query(2*ind+2,l,r,mid+1,end))
# ______________________________________________________________________________________________________
# Checking prime in O(root(N))
# def isprime(n):
#     if (n % 2 == 0 and n > 2) or n == 1: return 0
#     else:
#         s = int(n**(0.5)) + 1
#         for i in range(3, s, 2):
#             if n % i == 0:
#                 return 0
#         return 1
# def lcm(a,b):
#   return (a*b)//gcd(a,b)
# ______________________________________________________________________________________________________
# nCr under mod
# def C(n,r,mod):
#   if r>n:
#       return 0
#   num = den = 1
#   for i in range(r):
#       num = (num*(n-i))%mod
#       den = (den*(i+1))%mod
#   return...


Solve in Python:
The chef is trying to decode some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$

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

-----Sample Output:-----
1
10
10
101
101
101
1010
1010
1010
1010

-----EXPLANATION:-----
No need, else pattern can be decode easily.

for _ in range(0,int(input())):
    a=int(input())
    for i in range(0,a):
        for j in range(0,a):
            if j%2==0:
                print(1,end="")
            else:
                print(0,end="")
        print()


Solve in Python:
The chef is trying to decode some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$

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

-----Sample Output:-----
1
12
3
123
45
6
1234
567
89
10

-----EXPLANATION:-----
No need, else pattern can be decode easily.

# cook your dish here
# cook your dish here
for _ in range(int(input())):
    n=int(input())
    t=n
    s=0
    for i in range(n):

        for j in range(n-i):
            t-=1
            s+=1
            print(s,end="")
        print("\r")


Solve in Python:
The chef is trying to decode some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$

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

-----Sample Output:-----
1
1 01
11 001
1 01 11
001 101 011
111 0001 1001
1 01 11 001
101 011 111 0001
1001 0101 1101 0011
1011 0111 1111 00001

-----EXPLANATION:-----
No need, else pattern can be decode easily.

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

    K = 1
    for i in range(N):
        for j in range(N):
            B = bin(K)[2:]
            K += 1
            print(B[::-1], end = " ")
        print()


Solve in Python:
The chef is trying to decode some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$

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

-----Sample Output:-----
2
23
34
234
345
456
2345
3456
4567
5678

-----EXPLANATION:-----
No need, else pattern can be decode easily.

t = int(input())

for i in range(t):
    k = int(input())
    ini = [x + 2 for x in range(0, k)]
    for j in range(0, k):
        print("".join([str(x + j) for x in ini]))


Solve in Python:
The chef is trying to decode some pattern problems, Chef wants your help to code it. Chef has one number K(odd) to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$

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

-----Sample Output:-----
1
111
111
111
11111
11 11
1 1 1
11 11
11111
1111111
11   11
1 1 1 1
1  1  1
1 1 1 1
11   11
1111111

-----EXPLANATION:-----
No need, else pattern can be decode easily.


Solve in Python:
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K (odd) to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$

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

-----Sample Output:-----
*
*
**
*
*
**
* *
**
*
*
**
* *
*  *
* *
**
*

-----EXPLANATION:-----
No need, else pattern can be decode easily.


Solve in Python:
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$

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

-----Sample Output:-----
2
21
210
21
2
4
43
432
4321
43210
4321
432
43
4

-----EXPLANATION:-----
No need, else pattern can be decode easily.

# cook your dish here
for _ in range(int(input())):
    n = int(input())
    a=[]
    for i in range(n,0,-1):
        a.append(i)
    for i in range(1,n+1):
        print(" "*(n+1-i),end="")
        for j in a[0:i]:
            print(j, end="")
        print("")
    a.append(0)
    for i in a:
        print(i,end="")

    a.pop()
    print("")
    for i in range(1,n+1):
        print(" " * (i), end="")
        for j in a[0:n-i+1]:
            print(j, end="")
        print("")


Solve in Python:
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$

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

-----Sample Output:-----
0
*1
**2
0
*1
**2
***3
0
*1
**2
***3
****4

-----EXPLANATION:-----
No need, else pattern can be decode easily.

t=int(input())
while t>0:
    t-=1
    n=int(input())
    a=[]
    print(0)
    for i in range(1,n+1):
        for j in range(i+1):
            if j==i:
                print(i,end="")
            else:
                print("*",end="")
        print()


Solve in Python:
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$

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

-----Sample Output:-----
1121
1222
112131
122232
132333
11213141
12223242
13233343
14243444

-----EXPLANATION:-----
No need, else pattern can be decode easily.

# cook your dish here
t=int(input(""))
while(t!=0):
    s=''
    k=int(input(""))
    #print(k)
    for i in range(k):
        for j in range(k):
            s=s+str(j+1)+str(i+1)
        print(s)
        s=''
    t-=1


Solve in Python:
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$

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

-----Sample Output:-----
12
21
123
231
312
1234
2341
3412
4123

-----EXPLANATION:-----
No need, else pattern can be decode easily.

t=int(input())
for i in range(t):
    k=int(input())
    arr=[]
    for i in range(1,k+1):
        arr.append(i)

    for i in range(k):
        for j in range(i,k):
            print(arr[j],end="")
        for j in range(0,i):
            print(arr[j],end="")
        print()


Solve in Python:
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$

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

-----Sample Output:-----
21
1
123
21
1
4321
123
21
1

-----EXPLANATION:-----
No need, else pattern can be decode easily.

t=int(input())
for i in range(t):
 k=int(input())
 for j in range(k,0,-1):
   if j%2==0:
    for m in range(j,0,-1):
     print(m,end="")
   else:
    for m in range(1,j+1):
     print(m,end="")
   print()


Solve in Python:
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$

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

-----Sample Output:-----
1   1
2 2
3
4 4
5   5
1 1
2
3 3
1  1
22
33
4  4

-----EXPLANATION:-----
No need, else pattern can be decode easily.

try:
    t = int(input())
    for a in range(t):
        k = int(input())
        x = 0
        y = k-1
        n = 1
        for i in range(k):
            for j in range(k):
                if (j==x or j==y):
                    print(n,end="")
                else:
                    print(" ",end="")
            x+=1
            y-=1
            n+=1
            print()
except EOFError:
    pass


Solve in Python:
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$

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

-----Sample Output:-----
*
*
*
*
***
***
*
*
***
***
*****
*****
*
*
***
***
*****
*****
*******
*******

-----EXPLANATION:-----
No need, else pattern can be decode easily.

# cook your dish here
for i in range(int(input())):
    n=int(input())
    p=1
    l=n-1
    for j in range(n):
        for k in range(l):
            print(" ",end='')
        for k in range(p):
            print("*",end='')
        print()
        for k in range(l):
            print(" ",end='')
        for k in range(p):
            print("*",end='')
        print()
        p+=2
        l-=1


Solve in Python:
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$

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

-----Sample Output:-----
1
12
34
123
456
789
1234
5678
9101112
13141516

-----EXPLANATION:-----
No need, else pattern can be decode easily.

# cook your dish here
# cook your dish here
for case in range(int(input())):
    n=int(input())

    k=1
    for i in range(0,n):
        for j in range(0,n):
            print(k,end="")
            k+=1
        print("")


Solve in Python:
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$

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

-----Sample Output:-----
1
13
57
135
7911
131517
1357
9111315
17192123
25272931

-----EXPLANATION:-----
No need, else pattern can be decode easily.

# cook your dish here
# cook your dish here
for case in range(int(input())):
    n=int(input())

    k=1
    for i in range(0,n):
        for j in range(0,n):
            print(k,end="")
            k+=2
        print("")


Solve in Python:
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$

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

-----Sample Output:-----
1
21
*1
321
*21
**1
4321
*321
**21
***1

-----EXPLANATION:-----
No need, else pattern can be decode easily.

# cook your dish here

for _ in range(int(input())):
    k=int(input())
    for i in range(k):
        print('*'*i,end='')
        for j in range(k-i,0,-1):
                print(j,end="")
        print()


Solve in Python:
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$

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

-----Sample Output:-----
1
1 10
11 100
1 10 11
100 101 110
111 1000 1001
1 10 11 100
101 110 111 1000
1001 1010 1011 1100
1101 1110 1111 10000

-----EXPLANATION:-----
No need, else pattern can be decode easily.

from sys import stdin, stdout
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
mod = pow(10, 9) + 7
mod2 = 998244353
def inp(): return stdin.readline().strip()
def out(var, end="\n"): stdout.write(str(var)+"\n")
def outa(*var, end="\n"): stdout.write(' '.join(map(str, var)) + end)
def lmp(): return list(mp())
def mp(): return map(int, inp().split())
def smp(): return map(str, inp().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]
def remadd(x, y): return 1 if x%y else 0
def ceil(a,b): return (a+b-1)//b

def isprime(x):
    if x<=1: return False
    if x in (2, 3): return True
    if x%2 == 0: return False
    for i in range(3, int(sqrt(x))+1, 2):
        if x%i == 0: return False
    return True

for _ in range(int(inp())):
    n = int(inp())
    c = 1
    for i in range(n):
        for j in range(n):
            print(bin(c)[2:], end=" ")
            c += 1
        print()


Solve in Python:
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$

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

-----Sample Output:-----
2
24
68
246
81012
141618
2468
10121416
18202224
26283032

-----EXPLANATION:-----
No need, else pattern can be decode easily.

def solve(n):
    j=2
    for i in range(1,n+1):
        for k in range(n):
            print(j,end='')
            j+=2
        print()
for _ in range(int(input())):
    n=int(input())
    #s=input()
    #a,b=map(int,input().split())
    #l=list(map(int,input().split()))
    solve(n)


Solve in Python:
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$

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

-----Sample Output:-----
*
*
**
*
**
***
*
**
* *
****
*
**
* *
*  *
*****

-----EXPLANATION:-----
No need, else pattern can be decode easily.

t=int(input())
for _ in range(t):
    n=int(input())
    for i in range(n):
        if i==n-1:
            print('*'*(i+1))
        else:
            if i==0:
                print('*')
            else:
                print('*'+" "*(i+1-2)+'*')


Solve in Python:
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$

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

-----Sample Output:-----
1
1
32
1
32
654
1
32
654
10987
1
32
654
10987
1514131211

-----EXPLANATION:-----
No need, else pattern can be decode easily.

t=int(input())
for _ in range(t):
    n=int(input())
    c=0
    for i in range(n):
        ans=""
        c+=i+1
        for j in range(i+1):
            ans+=str(c)
            c-=1
        c+=i+1
        print(ans)


Solve in Python:
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 50$
- $1 \leq K \leq 50$

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

-----Sample Output:-----
*
*
***
*
* *
*****
*
* *
*   *
*******
*
* *
*   *
*     *
*********

-----EXPLANATION:-----
No need, else pattern can be decode easily.

try:
    t=int(input())
    for _ in range(t):
        n=int(input())
        i=1
        while(i<=n):
            j=i
            while(j<=n-1):
                print(" ",end="")
                j+=1
            print("*",end="")
            if i>1 and i<n:
                for j in range((i-1)*2-1):
                    print(" ",end="")
                print("*",end="")
            if(i==n):
                for j in range(2*(i-1)):
                    print("*",end="")
            print()

            i+=1
except EOFError:
    pass


Solve in Python:
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 50$
- $1 \leq K \leq 50$

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

-----Sample Output:-----
1
1
23
1
23
456
1
23
4 5
6789
1
23
4 5
6  7
89101112

-----EXPLANATION:-----
No need, else pattern can be decode easily.

def f(n):
    if n==1:
        return print(1)

    p = 2
    print(1)

    line = 2
    while line < n:
        print(p, " "*(line-2), p+1, sep="")
        p += 2
        line += 1

    for i in range(n):
        print(p, end="")
        p += 1
    print()

t = int(input())
answers = list()
for _ in range(t):
    n = int(input())
    answers.append(n)

for answer in answers:
    f(answer)


Solve in Python:
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
-First-line will contain $T$, the number of test cases. Then the test cases follow.
-Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 26$
- $1 \leq K \leq 26$

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

-----Sample Output:-----
A
12
A
12
ABC
1234

-----EXPLANATION:-----
No need, else pattern can be decode easily.

# cook your dish here
t = int(input())
for i in range(t):
 n = int(input())
 for i in range(1,n+1):
  str1 = ""
  print(" "*(n-i),end="")
  if i%2==1:
   for j in range(1,i+1):
    str1 = str1 + chr(64+j)
   print(str1)
  else:
   for i in range(1,i+1):
    print(i,end="")
   print()# cook your dish here


Solve in Python:
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form new pattern. Help the chef to code this pattern problem.

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

-----Output:-----
For each testcase, output as pattern.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$

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

-----Sample Output:-----
2
12
012
12
2

4
34
234
1234
01234
1234
234
34
4

-----EXPLANATION:-----
No need, else pattern can be decode easily.

# cook your dish here
for u in range(int(input())):
    n=int(input())
    l=[]
    x=0
    f=[]
    for i in range(n+1):
        f.append(' ')
    for i in range(n+1):
        f=[]
        for i in range(n+1):
            f.append(' ')
        for j in range(x,n+1):
            f[j]=str(j)
        x+=1
        l.append(f)
    d=l[1:][::-1]
    for i in d:
        print(''.join(i))
    for i in l:
        print(''.join(i))


Solve in Python:
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K(odd) to form a new pattern. Help the chef to code this pattern problem.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 50$
- $1 \leq K \leq 50$

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

-----Sample Output:-----
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*

-----EXPLANATION:-----
No need, else pattern can be decode easily.

for _ in range(int(input())):
    n = int(input())
    print('*')
    for i in range(1, n // 2):
        print(' ' * (i) + '*')
    for i in range(n // 2, 0, -1):
        print(' ' * (i) + '*')
    if n > 1:
        print('*')


Solve in Python:
The chef is trying to solve some series problems, Chef wants your help to code it. Chef has one number N. Help the chef to find N'th number in the series.
0, 1, 5, 14, 30, 55 …..

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $N$.

-----Output:-----
For each test case, output as the pattern.

-----Constraints-----
- $1 \leq T \leq 10^4$
- $1 \leq N \leq 10^4$

-----Sample Input:-----
3
1
7
8

-----Sample Output:-----
0
91
140

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


Solve in Python:
The chef is very expert in coding, so to keep his password safe from the hackers. He always enters a decoded code of his password. You are a hacker and your work is to find the maximum number of possible ways to unlock his password in encoded form.

The encoded message containing only letters from A-Z is being encoded with numbers using the following mapping:

'A' -> 1

'B' -> 2 ...

'Z' -> 26

You have given a non-empty string containing only digits, determine the total number of ways to encode it.

If the total number of ways are even then you are able to unlock the password.

Input:
The first line has a single integer T, denoting the number of test cases. The first line of each test case contains string “S” decoded number.

Output:
For each test case, in a new line, print 'YES' if number of maximum ways are even, otherwise
'NO'. (without quotes)

Constraints:
1 ≤ T ≤ 50

1 ≤ S ≤ 30

Sample Input:
2

12

223

Sample Output:
YES

NO

Explanation:
For first test case, It could be encoded as "AB" (1 2) or "L" (12), hence the number of
maximum possible ways are 2 so output is “YES”.

def numDecodings(s):
 s = '10' + s
 dec = [1] * (len(s) + 2)

 for i in range(2, len(s)):
  # invalid case or '10, 20'
  if s[i] == '0':
   if s[i - 1] != '1' and s[i - 1] != '2':
    return 0
   dec[i] = dec[i - 2]
  # 1 - 9, 27 -
  elif int(s[i - 1: i + 1]) > 26 or int(s[i - 1: i + 1]) < 10:
   dec[i] = dec[i - 1]
   # 11 - 26 (except for 20)
  else:
   dec[i] = dec[i - 1] + dec[i - 2]

 return dec[len(s) - 1]

for _ in range(int(input()))    :
 nums = input()
 ways = numDecodings(nums)
 print(["NO", "YES"][ ways % 2 == 0])


Solve in Python:
The chef likes to play with numbers. He takes some integer number x, writes it down on his iPad, and then performs with it n−1 operations of the two kinds:
- divide the number x by 3 (x must be divisible by 3);
- multiply the number x by 2.
After each iteration, Chef writes down the result on his iPad and replaces x with the result. So there will be n numbers on the iPad after all.
You are given a sequence of length n — the numbers that Chef wrote down. This sequence is given in the order of the sequence can mismatch the order of the numbers written on the iPad.
Your problem is to rearrange elements of this sequence in such a way that it can match a possible Chef's game in the order of the numbers written on the board. I.e. each next number will be exactly two times the previous number or exactly one-third of the previous number.
I can give a guarantee that the answer exists.

-----Input:-----
- The first line of the input contains an integer number N i.e the number of the elements in the sequence.
- The second line of the input contains n integer numbers a1,a2,…, an i.e rearranged (reordered) sequence that Chef can write down on the iPad.

-----Output:-----
Print N integer numbers — rearranged (reordered) input sequence that can be the sequence that Chef could write down on the iPad.
It is guaranteed that the answer exists

-----Constraints-----
- $2 \leq N \leq 100$
- $1 \leq A[i] \leq  3* 10^{18} $

-----Sample Input:-----
6
4 8 6 3 12 9

-----Sample Output:-----
9 3 6 12 4 8

-----EXPLANATION:-----
In the first example, the given sequence can be rearranged in the following way: [9,3,6,12,4,8]. It can match possible Polycarp's game which started with x=9.

def abc(v):
    for j in d[v]:
        k.append(j)
    if d[v]:
        abc(d[v][-1])
n=int(input())
l=list(map(int,input().split()))
l.sort()
d={}
k=[]
for i in l:
    a=[]
    b=[]
    req=2*i
    for j in l:
        if j==req:
            a.append(j)
            req = 2*j
    if not i%3:
        req=i//3
    else:
        req=-1
    for j in range(n-1,-1,-1):
        if req==-1:
            break
        if l[j]==req:
            b.append(l[j])
            if not l[j]%3:
                req=l[j]//3
            else:
                req=-1
    if a and b:
        d[i]=[]
    elif a:
        d[i]=a
    elif b:
        d[i]=b
    else:
        d[i]=a
for i in l:
    k=[i]
    abc(i)
    #print(i,k)
    if len(k)==n:
        print(*k)
        break
    k=[]


Solve in Python:
The chef was busy in solving algebra, he found some interesting results, that there are many numbers which can be formed by sum of some numbers which are prime. Chef wrote those numbers in dairy. Cheffina came and saw what the chef was doing. Cheffina immediately closed chef's dairy and for testing chef's memory, she starts asking numbers and chef needs to answer wheater given number N can be formed by the sum of K prime numbers if it yes then print 1 else print 0.

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

-----Output:-----
For each test case, output in a single line answer as 1 or 0.

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

-----Sample Input:-----
2
12 2
11 2

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

#https://www.geeksforgeeks.org/check-number-can-written-sum-k-prime-numbers/
from sys import stdin, stdout
def isprime(x):
	i = 2
	while(i * i <= x):
		if (x % i == 0):
			return 0
		i+=1
	return 1
def isSum(N, K):
	if (N < 2 * K):
		return 0
	if (K == 1):
		return isprime(N)
	if (K == 2):
		if (N % 2 == 0):
			return 1
		return isprime(N - 2);
	return 1
test = int(stdin.readline())
for _ in range(test):
    n,k = map(int, stdin.readline().split())
    if (isSum(n, k)):
    	stdout.write("1"+'\n')
    else:
    	stdout.write("0"+'\n')


Solve in Python:
The chef was busy in solving algebra, he found some interesting results, that there are many numbers which can be formed by the sum of the factorial of the digits, he wrote all those interesting numbers in the diary(in increasing order) and went to sleep. Cheffina came and stole his diary, in morning chef found that his diary is missing. Now the chef wants your help to find those numbers, Chef asks you whether N is that interesting number or not. If N is an interesting number then print 1. Else print 0.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, $N$.

-----Output:-----
For each test case, output in a single line answer 1 or 0.

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

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

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

-----EXPLANATION:-----
For 1) Factorial of 2 is 2, hence it is an interesting number.
For 2) conversion for 10 is 1! + 0! = 2, which is not equal to 10, hence not an interesting number.

# cook your dish here
for _ in range(int(input())):
    n = int(input())
    if n==1 or n==2 or n==145 or n==40585:
        print(1)
    else:
        print(0)


Solve in Python:
The chef was chatting with his friend who was a mathematician.
Chef said "Hi !".

His friend replied that '!' is the symbol of factorial.

Chef had never heard about it and he asked more about it. Then his friend taught him how to calculate the factorial of a number.

Chef loved that But as always he got tired after calculating a few values and asked you to do it for him.

-----Input-----
N : Number of inputs
then N lines with input T

N<10

T<=200

-----Output-----
The result for the corresponding value of T

-----Example-----
Input:
3
5
4
6

Output:
120
24
720

import sys

def Fact(n):
 s = 1
 for i in range(2, n + 1):
  s *= i
 return s

N = int(sys.stdin.readline())

for i in range(N):
 T = int(sys.stdin.readline())
 print(Fact(T))


Solve in Python:
The chef was not happy with the binary number system, so he designed a new machine which is having 6 different states, i.e. in binary there is a total of 2 states as 0 and 1. Now, the chef is confused about how to correlate this machine to get an interaction with Integer numbers, when N(Integer number) is provided to the system, what will be the Nth number that system will return(in Integer form), help the chef to design this system.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, $N$.

-----Output:-----
For each test case, output in a single line answer given by the system.

-----Constraints-----
- $1 \leq T \leq 10^5$
- $1 \leq N \leq 10^5$

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

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

-----EXPLANATION:-----
Initial numbers for system = [1, 6, 7, 36, 37, 42, 43, 216, …..
For 1) 3rd Number for the system will be 7.
For 2) 5th Number for the system will be 37.

for _ in range(int(input())):
    n = bin(int(input()))
    n = int(n[2:], 6)
    print(n)


Solve in Python:
The chef was playing with numbers and he found that natural number N can be obtained by sum various unique natural numbers, For challenging himself chef wrote one problem statement, which he decided to solve in future.
Problem statement: N can be obtained as the sum of Kth power of integers in multiple ways, find total number ways?
After that Cheffina came and read what chef wrote in the problem statement, for having some fun Cheffina made some changes in the problem statement as.
New problem statement: N can be obtained as the sum of Kth power of unique +ve integers in multiple ways, find total number ways?
But, the chef is now confused, how to solve a new problem statement, help the chef to solve this new problem statement.

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

-----Output:-----
For each test case, output in a single line answer to the problem statement.

-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq N \leq 1000$
- $1 \leq K \leq 6$

-----Sample Input:-----
2
4 1
38 2

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

-----EXPLANATION:-----
For 1) 4 can be obtained by as [ 4^1 ], [1^1, 3^1], [2^1, 2^1]. (here ^ stands for power)
But here [2^1, 2^1] is not the valid way because it is not made up of unique +ve integers.
For 2) 38 can be obtained in the way which is [2^2, 3^2, 5^2] = 4 + 9 + 25

for _ in range(int(input())):
    x,n = map(int,input().split())
    reach = [0]*(x+1)
    reach[0] = 1
    i=1
    while i**n<=x:
        j = 1
        while j+i**n<=x:
            j+=1
        j-=1
        while j>=0:
            if reach[j]>0:
                reach[j+i**n]+=reach[j]
            j-=1
        i+=1
    #print(reach)
    print(reach[-1])


Solve in Python:
The chef was searching for his pen in the garage but he found his old machine with a display and some numbers on it. If some numbers entered then some different output occurs on the display. Chef wants to crack the algorithm that the machine is following.
Example to identify the pattern :
Input                            Output
9                                   36
5                                   10
1                                    0
2                                    1

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, $N$.

-----Output:-----
For each test case, output in a single line answer as displayed on the screen.

-----Constraints-----
- $1 \leq T \leq 10^6$
- $1 \leq N \leq 10^6$

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

-----Sample Output:-----
21

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

for _ in range(t):
    n = int(input())
    sum = int((n*(n-1) )/ 2)
    print(sum)


Solve in Python:
The chef won a duet singing award at Techsurge & Mridang 2012. From that time he is obsessed with the number 2.

He just started calculating the powers of two. And adding the digits of the results.

But he got puzzled after a few calculations. So gave you the job to generate the solutions to 2^n and find their sum of digits.

-----Input-----
N : number of inputs N<=100

then N lines with input T<=2000

-----Output-----
The output for the corresponding input T

-----Example-----
Input:
3
5
10
4

Output:
5
7
7

Explanation:
2^5=32
3+2=5
2^10=1024
1+0+2+4=7
2^4=16
1+6=7

testcases = int(input())
while testcases:
 n = int(input())
 print(sum([int(digit) for digit in str(2**n)]))
 testcases -= 1


Solve in Python:
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess diagram below:

We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).

Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7.

Example 1:
Input: n = 1
Output: 10
Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.

Example 2:
Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]

Example 3:
Input: n = 3
Output: 46

Example 4:
Input: n = 4
Output: 104

Example 5:
Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.

Constraints:

1 <= n <= 5000

class Solution:
    def knightDialer(self, n: int) -> int:
        if n == 0:
            return 0
        if n == 1:
            return 10

        pad = {
            0: (4,6),
            1: (6, 8),
            2: (7,9),
            3: (4,8),
            4: (0, 3, 9),
            5: tuple(),
            6: (0,1,7),
            7: (2,6),
            8: (1,3),
            9: (2,4),
        }

        current = [0]*10
        prev = [1]*10

        for _ in range(n-1):
            current = [0]*10

            for key in range(10):
                for bro in pad[key]:
                    current[key] += prev[bro]
            prev = current

        return sum(current) %(10**9 + 7)


Solve in Python:
The citizens of Codeland read each word from right to left, meaning that lexicographical comparison works differently in their language. Namely, string ```a``` is lexicographically smaller than string ```b``` if either: ```a``` is a suffix of ```b``` (in common sense, i.e. ```b``` ends with a substring equal to ```a```); or their last ```k``` characters are the same but the ```(k + 1)th``` character from the right in string ```a``` is smaller than the same character in string ```b```.

Given an array of words in Codeland language, sort them lexicographically according to Codeland's unique rules.

For ```words = ["nigeb", "ta", "eht", "gninnigeb"]```, the output should be
```unusualLexOrder(words) = ["ta", "nigeb", "gninnigeb", "eht"]```.

In particular, ```"ta" < "nigeb"``` because ```'a' < 'b'``` and ```"nigeb" < "gninnigeb"``` because the former word is a suffix of the latter.

S: codefights.com

def unusual_lex_order(a):
    return sorted(a, key=lambda k: k[::-1])


Solve in Python:
The city of Siruseri is impeccably planned. The city is divided into a rectangular array of cells with $M$ rows and $N$ columns. Each cell has a metro station. There is one train running left to right and back along each row, and one running top to bottom and back along each column. Each trains starts at some time $T$ and goes back and forth along its route (a row or a column) forever.
Ordinary trains take two units of time to go from one station to the next. There are some fast trains that take only one unit of time to go from one station to the next. Finally, there are some slow trains that take three units of time to go from one station the next. You may assume that the halting time at any station is negligible.
Here is a description of a metro system with $3$ rows and $4$ columns:
$ $
S(1)  F(2)  O(2)  F(4)
F(3)    .     .     .     .
S(2)    .     .     .     .
O(2)    .     .     .     .

$ $
The label at the beginning of each row/column indicates the type of train (F for fast, O for ordinary, S for slow) and its starting time. Thus, the train that travels along row 1 is a fast train and it starts at time $3$. It starts at station ($1$, $1$) and moves right, visiting the stations along this row at times $3, 4, 5$ and $6$ respectively. It then returns back visiting the stations from right to left at times $6, 7, 8$ and $9$. It again moves right now visiting the stations at times $9, 10, 11$ and $12$, and so on. Similarly, the train along column $3$ is an ordinary train starting at time $2$. So, starting at the station ($3$,$1$), it visits the three stations on column $3$ at times $2, 4$ and $6$, returns back to the top of the column visiting them at times $6,8$ and $10$, and so on.
Given a starting station, the starting time and a destination station, your task is to determine the earliest time at which one can reach the destination using these trains.
For example suppose we start at station ($2$,$3$) at time $8$ and our aim is to reach the station ($1$,$1$). We may take the slow train of the second row...

from queue import PriorityQueue
m,n=list(map(int,input().split()))
rr=[]
cc=[]
speed={'S':3,'O':2,'F':1}
visited=set()
dp=[]

def qwerty(cur,x,y,f):
	if f==0:
		gg=rr[x][1]+y*rr[x][0]
		while gg<cur:
			gg+=(2*(n-1))*rr[x][0]
		return gg-cur+rr[x][0]
	elif f==1:
		gg=rr[x][1]+(2*(n-1)-y)*rr[x][0]
		while gg<cur:
			gg+=(2*(n-1))*rr[x][0]
		return gg-cur+rr[x][0]
	elif f==2:
		gg=cc[y][1]+x*cc[y][0]
		while gg<cur:
			gg+=(2*(m-1))*cc[y][0]
		return gg-cur+cc[y][0]
	elif f==3:
		gg=cc[y][1]+(2*(m-1)-x)*cc[y][0]
		while gg<cur:
			gg+=(2*(m-1))*cc[y][0]
		return gg-cur+cc[y][0]

dirx=[0, 0, 1, -1]
diry=[1, -1, 0, 0]

for i in range(m):
	o=[x for x in input().split()]
	o[0]=speed[o[0]]
	o[1]=int(o[1])
	rr.append(o)

for i in range(n):
	o=[x for x in input().split()]
	o[0]=speed[o[0]]
	o[1]=int(o[1])
	cc.append(o)

sx,sy,stt,dx,dy=list(map(int,input().split()))
sx-=1
sy-=1
dx-=1
dy-=1

for i in range(m):
	dp.append([10**9]*n)

dp[sx][sy]=stt
pq = PriorityQueue()
pq.put((stt, sx, sy))
while not pq.empty():
	#print(dp)
	(t,cxx,cyy)=pq.get()
	if (cxx,cyy) in visited:
		continue
	visited.add((cxx,cyy))
	for i in range(len(dirx)):
		nxx=cxx+dirx[i]
		nyy=cyy+diry[i]
		if nxx>=0 and nxx<m and nyy>=0 and nyy<n and (nxx,nyy) not in visited:
			coo=qwerty(dp[cxx][cyy],cxx,cyy,i)
			if coo+dp[cxx][cyy]<dp[nxx][nyy]:
					dp[nxx][nyy]=coo+dp[cxx][cyy]
					pq.put((dp[nxx][nyy],nxx,nyy))

print(dp[dx][dy])


Solve in Python:
The cockroach is one of the fastest insects. Write a function which takes its speed in km per hour and returns it in cm per second, rounded down to the integer (= floored).

For example:

```python
cockroach_speed(1.08) == 30
```

Note! The input is a Real number (actual type is language dependent) and is >= 0. The result should be an Integer.

def cockroach_speed(s):
    return (s * 100000) // (60 * 60)


Solve in Python:
The code provided is supposed replace all the dots `.` in the specified String `str` with dashes `-`

But it's not working properly.

# Task

Fix the bug so we can all go home early.

# Notes

String `str` will never be null.

import re
def replace_dots(s):
    return re.sub(r"[.+]", "-", s)


Solve in Python:
The concept of "[smooth number](https://en.wikipedia.org/wiki/Smooth_number)" is applied to all those numbers whose prime factors are lesser than or equal to `7`: `60` is a smooth number (`2 * 2 * 3 * 5`), `111` is not (`3 * 37`).

More specifically, smooth numbers are classified by their highest prime factor and your are tasked with writing a `isSmooth`/`is_smooth` function that returns a string with this classification as it follows:

* 2-smooth numbers should be all defined as a `"power of 2"`, as they are merely that;
* 3-smooth numbers are to return a result of `"3-smooth"`;
* 5-smooth numbers will be labelled as `"Hamming number"`s (incidentally, you might appreciate [this nice kata on them](https://www.codewars.com/kata/hamming-numbers));
* 7-smooth numbers are classified as `"humble numbers"`s;
* for all the other numbers, just return `non-smooth`.

Examples:
```python
is_smooth(16) == "power of 2"
is_smooth(36) == "3-smooth"
is_smooth(60) == "Hamming number"
is_smooth(98) == "humble number"
is_smooth(111) == "non-smooth"
```
The provided input `n` is always going to be a positive number `> 1`.

def is_smooth(n):
    for v in [2,3,5,7]:
        while n%v==0:n/=v
        if n==1:return['','','power of 2','3-smooth','','Hamming number','','humble number'][v]
    return 'non-smooth'


Solve in Python:
The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     1
2.     11
3.     21
4.     1211
5.     111221

1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.

Given an integer n, generate the nth term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:

Input: 1
Output: "1"

Example 2:

Input: 4
Output: "1211"

class Solution:
     def countAndSay(self, n):
         """
         :type n: int
         :rtype: str
         """
         L="1"
         if(n==1):
             return L
         while(n>1):
             M=""
             i=0
             while(i<len(L)):
                 k=1
                 x=L[i];
                 while(i<len(L)-1 and L[i+1]==x):
                     i=i+1
                     k=k+1
                 M=M+str(k)+x
                 i=i+1
             n=n-1
             L=M
         return L


Solve in Python:
The country has n cities and n - 1 bidirectional roads, it is possible to get from every city to any other one if you move only along the roads. The cities are numbered with integers from 1 to n inclusive.

All the roads are initially bad, but the government wants to improve the state of some roads. We will assume that the citizens are happy about road improvement if the path from the capital located in city x to any other city contains at most one bad road.

Your task is — for every possible x determine the number of ways of improving the quality of some roads in order to meet the citizens' condition. As those values can be rather large, you need to print each value modulo 1 000 000 007 (10^9 + 7).

-----Input-----

The first line of the input contains a single integer n (2 ≤ n ≤ 2·10^5) — the number of cities in the country. Next line contains n - 1 positive integers p_2, p_3, p_4, ..., p_{n} (1 ≤ p_{i} ≤ i - 1) — the description of the roads in the country. Number p_{i} means that the country has a road connecting city p_{i} and city i.

-----Output-----

Print n integers a_1, a_2, ..., a_{n}, where a_{i} is the sought number of ways to improve the quality of the roads modulo 1 000 000 007 (10^9 + 7), if the capital of the country is at city number i.

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

Output
4 3 3
Input
5
1 2 3 4

Output
5 8 9 8 5

class Graph:
    def __init__(self, n_vertices, edges, directed=True, weighted=False):
        self.n_vertices = n_vertices
        self.edges = edges
        self.directed = directed
        self.weighted = weighted

    @property
    def adj(self):
        try:
            return self._adj
        except AttributeError:
            adj = [[] for _ in range(self.n_vertices)]
            def d_w(e):
                adj[e[0]].append((e[1],e[2]))
            def ud_w(e):
                adj[e[0]].append((e[1],e[2]))
                adj[e[1]].append((e[0],e[2]))
            def d_uw(e):
                adj[e[0]].append(e[1])
            def ud_uw(e):
                adj[e[0]].append(e[1])
                adj[e[1]].append(e[0])
            helper = (ud_uw, d_uw, ud_w, d_w)[self.directed+self.weighted*2]
            for e in self.edges:
                helper(e)
            self._adj = adj
            return adj

class RootedTree(Graph):
    def __init__(self, n_vertices, edges, root_vertex):
        self.root = root_vertex
        super().__init__(n_vertices, edges, False, False)

    @property
    def parent(self):
        try:
            return self._parent
        except AttributeError:
            adj = self.adj
            parent = [None]*self.n_vertices
            parent[self.root] = -1
            stack = [self.root]
            for i in range(self.n_vertices):
                v = stack.pop()
                for u in adj[v]:
                    if parent[u] is None:
                        parent[u] = v
                        stack.append(u)
            self._parent = parent
            return parent

    @property
    def children(self):
        try:
            return self._children
        except AttributeError:
            children = [None]*self.n_vertices
            for v,(l,p) in enumerate(zip(self.adj,self.parent)):
                children[v] = [u for u in l if u != p]
            self._children = children
            return children

    @property
    def dfs_order(self):
        try:
      ...


Solve in Python:
The country of Siruseri has A∗B$A*B$ districts. You want to create A$A$ states from these districts, such that each state has exactly B$B$ districts, and each district is part of exactly one state. You don't care about the geographical location of the districts. You can pick any B$B$ districts and make it into a state.
There are only two parties contesting in the coming elections: P1$P_1$ and P2$P_2$. You know the number of votes that each party receives in each district. In the i-th district, P1$P_1$ gets ci$c_i$ votes and P2$P_2$ gets di$d_i$ votes. You are guaranteed that all these 2∗A∗B$2*A*B$ integers (the number of votes received by each party in the districts) are distinct. Also, both A$A$ and B$B$ are odd.
Suppose you have chosen which districts belong to which states, then, to find out who wins any particular state, they follow a weird rule: Suppose the number of votes that P1$P_1$ gets in the B$B$ districts of a particular state are x1,x2,…,xB$x_1, x_2, \ldots, x_B$, and the number of votes that P2$P_2$ gets in the B$B$ districts of this state are y1,y2,…,yB$y_1, y_2, \ldots, y_B$. Then among all these 2∗B$2*B$ numbers, the largest number is chosen (note that we are guaranteed of an unique largest number). If that number is some xi$x_i$, then P1$P_1$ wins this state. If the largest number is some yj$y_j$, then P2$P_2$ wins this state.
You secretly support the party P1$P_1$, and hence you want to assign the districts to states, in such a way, that the number of states won by P1$P_1$ is maximized. Find this maximum number of states that P1$P_1$ can win.
Note that ci$c_i$ and di$d_i$ will always remain associated with the i-th district. If the i-th district gets assigned to a particular state, then both ci$c_i$ and di$d_i$ will be considered when deciding who won that state.

-----Input:-----
- The first line of the input contains a single integer, T$T$, the number of testcases. The description of each testcase follows.
- The first line of each testcase contains two integers, A$A$ and B$B$.
- The...

T=int(input())
for _ in range(T):
    A,B=list(map(int,input().split()))
    cs=list(map(int,input().split()))
    ds=list(map(int,input().split()))

    for i in range(A*B):
     if cs[i]<ds[i]:
      cs[i]=0
     else:
      ds[i]=0

    cs.sort(reverse=True)
    ds.sort(reverse=True)

    w,c,d=0,0,0
    for _ in range(A):
     if cs[c]>ds[d]:
      w+=1
      c+=1
      d+=B-1
     else:
      d+=B

    print(w)


Solve in Python:
The date is March 24, 2437 and the the Earth has been nearly completely destroyed by the actions of its inhabitants. Our last hope in this disaster lies in a shabby time machine built from old toasters and used microwave parts.

The World Time Agency requires you to travel back in time to prevent disaster.  You are ordered to "remove" certain babies from the timeline.

Historical newspapers and records provide the Date, Month, and Year for each mission.  Unfortunately the time machine takes input only as the number of days to travel back in time.  It is your job to calculate how many days you will need to travel back from today's date (March 24, 2437) for each mission.

For example, if a historical newspaper says a dangerous baby was born on:
Date = 21, Month = 3, Year = 2437
Then your function must compute that it was 3 Days ago.

Another example would be that a baby born on Date = 24, Month = 3, Year = 2436 would have been born 365 days ago.

You will not have time travel past the year 0.

Note that while this is a fairly simple task, it is complicated by the fact that newspapers used the Julian calendar instead of the current Gregorian calendar prior to September 14, 1752.  In 1752, it was declared that Sep 2, 1752 was proceeded immediately by September 14, 1752, entirely omitting September 3-13. Furthermore, the rules for leap years changed on that date.

After 1752, leap years are on any year divisible by four, except for years which are divisible by 100. An exception to that exception is that years divisible by 400 are always leap years.  For example, 1803, 1900, 2001, 2019, and 2100 are not leap years, but 1804, 2000 and 2020 are leap years.
However in the Julian calander prior to and including 1752, leap years were on every year divisible by 4, without the exception of years divisible by 100.  The years 1752, 1700, 1600, and 0 were all leap years.

Good luck agent, the world depends on you!

Note: It is not required, but if you find it helpful to visualize the switch from the Julian to the...

# Let's do this without the builtin date library
# and without looking up formulas in wikipedia

def is_leap_year(year):
    if year % 4 != 0:
        return False
    # year is divisible by 4.
    # If the year is in the Gregorian calendar, that's it
    if year <= 1752:
        return True

    # Julian calendar rule
    return (year % 100 != 0) or (year % 400 == 0)

# Day number of the first day of the month, minus one.
# Doesn't count leap years.
DOM = {
    1: 0,
    2: 31,
    3: 59,
    4: 90,
    5: 120,
    6: 151,
    7: 181,
    8: 212,
    9: 243,
    10: 273,
    11: 304,
    12: 334,
}

def is_julian_period(date, month, year):
    if year > 1752: return True
    if year < 1752: return False
    # year == 1752
    if month < 9: return False
    if month > 9: return True
    return date >= 14

# This could be rewritten as a one-liner (see wikipedia) but I'm not sure that I can derive the formula.
def normalized_day(date, month, year):
    """Number of days between given date and an arbitrary origin. normalized_day(1, 1, 0) == 1
    """
    orig_year = 0
    days = date + DOM[month] + (year - orig_year) * 365

    # Leap year adjustment for the current year
    if is_leap_year(year) and month >= 3:
        days += 1
    # Leap year adjustment for the intervening years
    # It could be done without a loop (count 4-year intervals,
    # subtract centuries, re-add 400-years) but it would be less
    # readable given the Gregorian stuff.
    for y in range(orig_year, year, 4):
        if is_leap_year(y):
            days += 1
    # Gregorian->Julian transition adjustment
    if is_julian_period(date, month, year):
        days -= 11

    return days

def days(date, month, year):
    return normalized_day(24, 3, 2437) - normalized_day(date, month, year)


Solve in Python:
The description is rather long but it tries to explain what a financing plan is.

The fixed monthly payment for a fixed rate mortgage is the amount paid by the borrower every month that ensures
that the loan is paid off in full with interest at the end of its term.

The monthly payment formula is based on the annuity formula.
The monthly payment `c` depends upon:

- `rate` - the monthly interest rate is expressed as a decimal, not a percentage.
The monthly rate is simply the **given** yearly percentage rate divided by 100 and then by 12.

- `term` - the number of monthly payments, called the loan's `term`.
- `principal` - the amount borrowed, known as the loan's principal (or `balance`).

First we have to determine `c`.

We have: `c = n /d` with `n = r * balance` and `d = 1 - (1 + r)**(-term)` where `**` is the `power` function (you can look at the reference below).

The payment `c` is composed of two parts. The first part pays the interest (let us call it `int`)
due for the balance of the given month, the second part repays the balance (let us call this part `princ`) hence for the following month we get a `new balance = old balance - princ` with `c = int + princ`.

Loans are structured so that the amount of principal returned to the borrower starts out small and increases with each mortgage payment.
While the mortgage payments in the first years consist primarily of interest payments, the payments in the final years consist primarily of principal repayment.

A mortgage's amortization schedule provides a detailed look at precisely what portion of each mortgage payment is dedicated to each component.

In an example of a $100,000, 30-year mortgage with a rate of 6 percents the amortization schedule consists of 360 monthly payments.
The partial amortization schedule below shows with 2 decimal floats
the balance between principal and interest payments.

--|num_payment|c          |princ      |int        |Balance    |
--|-----------|-----------|-----------|-----------|-----------|
--|1          |599.55    ...

amort=lambda r,b,t,n,c=0,p=0,i=0,m=-1:m<0and amort(r/1200,b,t,n,r/1200*b/(1-(1+r/1200)**-t),p,i,0)or m==n and"num_payment %d c %.0f princ %.0f int %.0f balance %.0f"%(n,c,p,i,b)or amort(r,r*b+b-c,t-1,n,c,c-r*b,r*b,m+1)


Solve in Python:
The description is rather long but you are given all needed formulas (almost:-)

John has bought a bike but before going moutain biking he wants us to do a few simulations.

He gathered information:

- His trip will consist of an ascent of `dTot` kilometers with an average slope of `slope` *percent*
- We suppose that: there is no wind, John's mass is constant `MASS = 80 (kg)`, his power (generated at time `t` by pedaling and measured in watts)
at the start of the trip is `WATTS0 = 225 (watts)`
- We don't take account of the rolling resistance
- When he starts climbing at t = 0 his initial speed (pushed start) is `v0 (km/h)`
- His initial acceleration `gamma` is 0.
`gamma` is in `km/h/min` at time `t`. It is the number of kilometers per hour he gains or loses in the next *minute*.
- Our time step is `DELTA_T = 1.0 / 60.0` (in minutes)

Furthermore (constants in uppercase are given below):

 - Because of tiredness, he *loses* D_WATTS * DELTA_T of power at each DELTA_T.
 - calcul of acceleration:

  Acceleration has three components:
    - 1) on an ascent where the slope is `slope` the effect of earth gravity is given by:

    `- GRAVITY_ACC * function(slope)`

    (Beware: here the `slope`is a percentage, it is not an angle. You have to determine `function(slope)`).

    Some help for `function(slope)`:

    a) slope:

    b) earth gravity:

    https://en.wikipedia.org/wiki/Gravity_of_Earth

    - 2) air drag is

    `- DRAG * abs(v) * abs(v) / MASS` where `v` is his current speed

    - 3) if his power and his speed are both strictly positive we add the thrust (by pedaling) which is:

    `+ G_THRUST * watts / (v * MASS)` where `watts` is his current power

    - 4) if his total `acceleration is <= 1e-5` we set acceleration to 0
 - If `v - 3.0 <= 1e-2` John gives up

```
Constants:
GRAVITY_ACC = 9.81 * 3.6 * 60.0                        // gravity acceleration
DRAG        = 60.0 * 0.3 / 3.6                         // force applied by air on the...

from math import atan, sin
def temps(v, slope, d_tot):
    answer = 0
    travelled = 0
    mass = 80
    power = 225
    power_loss = 0.5 / 60
    angle = atan(slope / 100)
    gravity_acc = 9.81 * 3.6 * 60
    gravityParallel = gravity_acc * sin(angle)
    drag = 60 * 0.3 / 3.6
    g_thrust = 60 * 3.6 * 3.6
    while travelled < d_tot:
        answer += 1
        airDrag = drag * v * v / mass
        thrust = 0
        if power > 0 and v > 0:
            thrust = g_thrust * power / v / mass
        gamma = - gravityParallel - airDrag + thrust
        if abs(gamma) <= 1e-5:
            gamma = 0
        v += gamma / 60
        if v - 3 <= 1e-2:
            return -1
        travelled += v / 60 / 60
        power -= power_loss
    return round(answer / 60)


Solve in Python:
The dragon's curve is a self-similar fractal which can be obtained by a recursive method.

Starting with the string `D0 = 'Fa'`, at each step simultaneously perform the following operations:

```
replace 'a' with: 'aRbFR'
replace 'b' with: 'LFaLb'
```

For example (spaces added for more visibility) :

```
1st iteration: Fa -> F aRbF R
2nd iteration: FaRbFR -> F aRbFR R LFaLb FR
```

After `n` iteration, remove `'a'` and `'b'`. You will have a string with `'R'`,`'L'`, and `'F'`. This is a set of instruction. Starting at the origin of a grid looking in the `(0,1)` direction, `'F'` means a step forward, `'L'` and `'R'` mean respectively turn left and right. After executing all instructions, the trajectory will give a beautifull self-replicating pattern called 'Dragon Curve'

The goal of this kata is to code a function wich takes one parameter `n`, the number of iterations needed and return the string of instruction as defined above. For example:

```
n=0, should return: 'F'
n=1, should return: 'FRFR'
n=2, should return: 'FRFRRLFLFR'
```

`n` should be a number and non-negative integer. All other case should return the empty string: `''`.

def Dragon(n):
    if not isinstance(n, int) or n < 0:
        return ''

    value = 'Fa'

    for i in range(n):
        value = value.replace('a', 'aRcFR')
        value = value.replace('b', 'LFaLb')
        value = value.replace('c', 'b')

    return value.replace('a', '').replace('b', '')


Solve in Python:
The entire network is under the inspection and direct control of the Decepticons. They have learned our language through the World Wide Web and can easily understand the messages which are being sent. Sam is trying to send the information to Autobots to locate “ALL SPARK” which is the only source of energy that can be used to create universe. He is bit cautious in sending the message. He is sending the messages in a form of special pattern of string that contains important message in form of substrings. But Decepticons have learnt to recognize the Data Mining and string comparison patterns. He is sending a big message in form of a string (say M) and let there are N smaller substrings. Decepticons have to find whether each of these N substrings is a sub-string of M. All strings consist of only alphanumeric characters.

-----Input-----
Input to the program consists of two line. The first line contains the string M (where size of M should be <=40). The next line contain a string S.

-----Output-----
Output should consist of a line with a character 'Y'/'N' indicating whether the string S is a sub-string of String M or not.

-----Example-----
Input:
techtrishna online event
onlin
Output:
Y

x = input()
y = input()
z = x.find(y)
if z == -1 :
 print('N')
else :
 print('Y')


Solve in Python:
The factorial of a number, `n!`, is defined for whole numbers as the product of all integers from `1` to `n`.

For example, `5!` is `5 * 4 * 3 * 2 * 1 = 120`

Most factorial implementations use a recursive function to determine the value of `factorial(n)`. However, this blows up the stack for large values of `n` - most systems cannot handle stack depths much greater than 2000 levels.

Write an implementation to calculate the factorial of arbitrarily large numbers, *without recursion.*

# Rules

* `n < 0` should return `nil`/  `None`
* `n = 0` should return `1`
* `n > 0` should return `n!`

# Note

Codewars limits the amount of data it will send back and forth, which may introduce a false ceiling for how high of a value of `n` it will accept. All tests use values less than this limit.

import math
def factorial(n):
    return math.factorial(n) if n >= 0 else None


Solve in Python:
The faculty of application management and consulting services (FAMCS) of the Berland State University (BSU) has always been popular among Berland's enrollees. This year, N students attended the entrance exams, but no more than K will enter the university. In order to decide who are these students, there are series of entrance exams. All the students with score strictly greater than at least (N-K) students' total score gets enrolled.
In total there are E entrance exams, in each of them one can score between 0 and M points, inclusively. The first E-1 exams had already been conducted, and now it's time for the last tribulation.
Sergey is the student who wants very hard to enter the university, so he had collected the information about the first E-1 from all N-1 enrollees (i.e., everyone except him). Of course, he knows his own scores as well.
In order to estimate his chances to enter the University after the last exam, Sergey went to a fortune teller. From the visit, he learnt about scores that everyone except him will get at the last exam. Now he wants to calculate the minimum score he needs to score in order to enter to the university. But now he's still very busy with minimizing the amount of change he gets in the shops, so he asks you to help him.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains four space separated integers N, K, E, M denoting the number of students, the maximal number of students who'll get enrolled, the total number of entrance exams and maximal number of points for a single exam, respectively.
The following N-1 lines will contain E integers each, where the first E-1 integers correspond to the scores of the exams conducted. The last integer corresponds to the score at the last exam, that was predicted by the fortune-teller.
The last line contains E-1 integers denoting Sergey's score for the first E-1 exams.

-----Output-----

For each test case, output a...

t=int(input())
for i in range(t):
 n,k,e,m=map(int,input().split())
 p=[]
 for i in range(n-1):
  p.append(sum(map(int,input().split())))
 q=sum(map(int,input().split()))
 p.sort()
 d=p[n-k-1]-q
 if(d+1>m):
  print('Impossible')
 elif(d<=-1):
  print(0)
 else:
  print(d+1)