Solve in Python:
-----
__CLEAR CUTTER'S NEEDS YOUR HELP!__
-----

The logging company Clear Cutter's makes its money by optimizing the price-to-length of each log they cut before selling them. An example of one of their price tables is included:

```python
# So a price table p
p = [ 0,  1,  5,  8,  9, 10]

# Can be imagined as:
# length i | 0  1  2  3  4  5 *in feet*
# price pi | 0  1  5  8  9 10 *in money*
```

They hired an intern last summer to create a recursive function for them to easily calculate the most profitable price for a log of length _n_ using price table _p_ as follows:

```python
def cut_log(p, n):
   if (n == 0):
      return 0
   q = -1
   for i in range(1, n+1)
      q = max(q, p[i] + cut_log(p, n-i))
   return q
```

An example of the working code:
```python
cut_log(p, 5) # => 13
# 5ft = $10, BUT 2ft + 3ft = 5ft -> $5 + $8 = $13 which is greater in value
```

However, their senior software engineer realized that the number of recursive calls in the function gives it an awful running time of 2^n (as this function iterates through ALL 2^n-1 possibilities for a log of length n).

Having discovered this problem just as you've arrived for your internship, he responsibly delegates the issue to you.

Using the power of Stack Overflow and Google, he wants you to create a solution that runs in Θ(n^2) time so that it doesn't take 5 hours to calculate the optimal price for a log of size 50. (He also suggests to research the problem using the keywords in the tags)

__(Be aware that if your algorithm is not efficient, it will attempt to look at 2^49 = 562949953421312 nodes instead of 49^2 = 2401... The solution will automatically fail if it takes longer than 6 seconds... which occurs at right around Log 23)__

def cut_log(p, n):
    q = [0]
    for j in range(1, n+1):
        q.append(max(p[i] + q[j-i] for i in range(1, j+1)))
    return q[n]


Solve in Python:
----- Statement -----

You need to find a string which has exactly K positions in it such that the character at that position comes alphabetically later than the character immediately after it. If there are many such strings, print the one which has the shortest length. If there is still a tie, print the string which comes the lexicographically earliest (would occur earlier in a dictionary).

-----Input-----
The first line contains the number of test cases T. Each test case contains an integer K (≤ 100).

-----Output-----
Output T lines, one for each test case, containing the required string.  Use only lower-case letters a-z.

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

-----Sample Output-----
ba
cba

def printrev(start):
 for s in range(start , ord('a')-1, -1) :
  print(chr(s), end='')

testcase = int(input())
while testcase:

 k = int(input())

 if k > 25 :
  rem = k % 25
  quo = k // 25
  if rem != 0 :
   printrev(97 + rem)

  for _ in range(quo) :
   printrev(ord('z'))

  print()

 else:
  printrev(97 + k)
  print()

 testcase -= 1


Solve in Python:
-----Coal Company -----

The Tunisian Coal Mining company uses a train to ferry out coal blocks from its coal mines. The train has N containers numbered from 1 to N which need to

be filled with blocks of coal. Assume there are infinite coal blocks. The containers are arranged in increasing order of capacity, and the ith container

has capacity i. Every container has a specific loading cost ci. The workers fill the containers in rounds. In every round, they choose a subset of

containers and load them with coal blocks. This subset should be such that each subsequent container chosen in a round should be more spacious than the

previous one. Also, the difference in loading cost of consecutive containers should be at least K.

What is the least number of rounds in which all containers can be filled?

-----
Input
-----

The first line contains the number of test cases T. T test cases follow.

Each case contains an integer N and K on the first line, followed by integers c1,...,cn on the second line.

1 <= T <= 100

1 <= N <= 300

1 <= ci <= 1000

1 <= K <= 1000

-----
Output
-----

Output T lines, one for each test case, containing the minimum number of rounds in which all containers could be filled.

-----
Example
-----

Input:

2

3 2

5 4 7

5 1

5 3 4 5 6

Output:

2

1

Explanation:

For the first example, workers can fill the containers of cost 5 and 7 in the first round and the container with cost 4 in the next round. Note that the

containers with cost 5 and 4 cannot be filled consecutively because the loading costs should differ by at least K (which is 2). Also, the containers cannot

be filled in order 5, 7, 4 in one round because the containers filled in a round should be in increasing capacity.

for _ in range(int(input())):
 n,k=list(map(int,input().split()))
 c=list(map(int,input().split()))
 count=1
 for i in range(n):
  if i+1<n:
   if c[i]-c[i+1]>=k or c[i+1]-c[i]>=k:
    continue
   else:
    count+=1
    c[i],c[i+1]=c[i+1],c[i]
 print(count)


Solve in Python:
-----Description-----
The Antique Comedians of India prefer comedies to tragedies. Unfortunately, most of the ancient plays are tragedies. Therefore the dramatic advisor of ACI has decided to transfigure some tragedies into comedies. Obviously, this work is very hard because the basic sense of the play must be kept intact, although all the things change to their opposites. For example the numbers: if any number appears in the tragedy, it must be converted to its reversed form before being accepted into the comedy play. A reversed number is a number written in Arabic numerals but the order of digits is reversed. The first digit becomes last and vice versa. For example, if the main hero had 1245 strawberries in the tragedy, he has 5421 of them now. Note that all the leading zeros are omitted. That means if the number ends with a zero, the zero is lost by reversing (e.g. 1200 gives 21). Also, note that the reversed number never has any trailing zeros. ACI needs to calculate with reversed numbers. Your task is to add two reversed numbers and output their reversed sum. Of course, the result is not unique because any particular number is a reversed form of several numbers (e.g. 23 could be 32, 320, or 3200 before reversing). Thus we must assume that no zeros were lost by reversing (e.g. assume that the original number was 23).

-----Input-----
The input consists of N cases. The first line of the input contains only positive integer N. Then follow the cases. Each case consists of exactly one line with two positive integers separated by space. These are the reversed numbers you are to add. Numbers will be at most 200 characters long.

-----Output-----
For each case, print exactly one line containing only one integer - the reversed sum of two reversed numbers. Omit any leading zeros in the output.

-----Sample Input-----
3
24 1
4358 754
305 794

-----Sample Output-----
34
1998
1

#include<stdio.h>
int reverse(int n)
{
int rev = 0, remainder;
while (n != 0) {
remainder = n % 10;
rev = rev * 10 + remainder;
n /= 10;
}
return rev;
}
int main()
{
int t;
scanf("%d",&t);

while(t--)

{

int a,b,sum=0;

scanf("%d %d",&a,&b);

sum=reverse(reverse(a)+reverse(b));

printf("%d\n",sum);

}

}


Solve in Python:
-----General Statement:-----
Given the actual high and low temperatures for the day and the normal high and low temperatures for that day, calculate the average difference from normal.

-----Input:-----
The first line of the data set for this problem is an integer that represents the number of data sets that follow. Each data set is on a separate line and consists of today’s high, today’s low, normal high, and normal low – in that order.

-----Output:-----
If the average difference is negative, do not output the negative sign (-).
Output the amount of deviation from normal, followed by the words
DEGREE(S) ABOVE NORMAL, or by the words
DEGREE(S) BELOW NORMAL.
Round to 1 decimal place. A trailing zero is required if the average is an integer.
The output is to be formatted exactly like that for the sample output given below.

-----Assumptions:-----
Temperatures are in the range –15..100 degrees.
The average temperature difference will not be zero.

-----Discussion:-----
Determine the average of the difference of the high temperatures and the difference of the low temperatures.

-----Sample Input:-----
3
75 45 78 40
50 32 45 30
56 48 62 45

-----Sample Output:-----
1.0 DEGREE(S) ABOVE NORMAL
3.5 DEGREE(S) ABOVE NORMAL
1.5 DEGREE(S) BELOW NORMAL

# cook your dish her
for _ in range(int(input())):
    l=list(map(int,input().split()))
#print(l)
    avg=((l[0]-l[2])+(l[1]-l[3]))/2
    if(avg>0):
        print(str(avg)+" DEGREE(S) ABOVE NORMAL")
    else:
        print(str(avg*-1)+" DEGREE(S) BELOW NORMAL")


Solve in Python:
-----General Statement:-----
Read a number in scientific notation and output its equivalent decimal value.

-----Input:-----
All data is on a single line. The first integer indicates how many pairs of numbers follow. The first of each pair is A, the base number, and the second is E, the power of 10.

-----Output:-----
Round each answer to 2 decimal places. Trailing zeros to the right of the decimal point are required. A leading zero to the left of the decimal point is not required.
The output is to be formatted exactly like that for the sample output given below.

-----Assumptions:-----
E is in the range –10 .. 10. A is 1 or larger but less than 10.
Discussion:
If A = 3.926 and E = 4, the number represented is 3.926 X 104 or 39260, which is 39260.00 when rounded to 2 decimal places.

-----Sample Input:-----
4 4.296 3 3.8 -2 1.8 2 2.8678 1

-----Sample Output:-----
4296.00
0.04
180.00
28.68

nums = [x for x in input().split()]
x = 1
for _ in range(int(nums[0])):
    b, exp = float(nums[x]),float(nums[x+1])
    x += 2
    ans = b * (10 ** exp)
    print( f'{ans:.2f}')


Solve in Python:
-----Indian National Olympiad in Informatics 2014-----
Nikhil’s slogan has won the contest conducted by Drongo Airlines and he is entitled to a free ticket between any two destinations served by the airline. All cities served by Drongo Airlines can be reached from each other by some sequence of connecting flights. Nikhil is allowed to take as many connecting flights as needed, but he must take the cheapest route between his chosen destinations.
Each direct flight between two cities has a fixed price. All pairs of cities connected by direct flights have flights in both directions and the price is the same in either direction. The price for a sequence of connecting flights is the sum of the prices of the direct flights along the route.
Nikhil has information about the cost of each direct flight. He would like to maximize the value of his prize, so he would like to choose a pair of cities on the network for which the cost of the cheapest route is as high as possible.
For instance, suppose the network consists of four cities {1, 2, 3, 4}, connected as shown on the right.
In this case, Nikhil should choose to travel between 1 and 4, where the cheapest route has cost 19. You can check that for all other pairs of cities, the cheapest route has a smaller cost. For instance, notice that though the direct flight from 1 to 3 costs 24, there is a cheaper route of cost 12 from 1 to 2 to 3.

-----Input Format:-----
- Line 1 : Two space-separated integers, C and F . C is the number of cities on the network, numbered 1, 2, . . . , C. F is the number of pairs of cities connected by a direct flight
- Lines 2 to F + 1 : Each line describes one direct flight between a pair of cities and consists of three integers, x, y and p, where x and y are the two cities connected by this flight and p is the price of this
For all direct flights, $x \neq y$, and no pair of cities is connected by more than one direct flight. If there is a direct flight from x to y with price p, there is also a flight from y to x with price p and exactly one of...

I = int(10e15)
c , f = [int(i) for i in input().split()]
arr = [[0 for i in range(c)] for j in range(c)]

sdc = []
for x in range(f):
    sdc.append( list(int(x) for x in input().split()))

for i in sdc:
    arr[i[0]-1][i[1]-1]=i[2]
    arr[i[1]-1][i[0]-1]=i[2]

for x in range(c):
    for y in range(c):
        if x != y :
            if arr[x][y] == 0:
                arr[x][y] = I

def f_w(v, arr):
	for k in range(0, v):
		for i in range(0, v):
			for j in range(0, v):
				arr[i][j] = min(arr[i][j], arr[i][k] + arr[k][j])

f_w(c,arr)
m = -1
for x in range(c):
    m = max(m, max(arr[x]))

print(m)


Solve in Python:
-----Problem Statement-----
A classroom has several students, half of whom are boys and half of whom are girls. You need to arrange all of them in a line for the morning assembly such that the following conditions are satisfied:
- The students must be in order of non-decreasing height.
- Two boys or two girls must not be adjacent to each other.
You have been given the heights of the boys in the array $b$ and the heights of the girls in the array $g$. Find out whether you can arrange them in an order which satisfies the given conditions. Print "YES" if it is possible, or "NO" if it is not.
For example, let's say there are $n = 3$ boys and $n = 3$ girls, where the boys' heights are $b = [5, 3, 8]$ and the girls' heights are $g = [2, 4, 6]$. These students can be arranged in the order $[g_0, b_1, g_1, b_0, g_2, b_2]$, which is $[2, 3, 4, 5, 6, 8]$. Because this is in order of non-decreasing height, and no two boys or two girls are adjacent to each other, this satisfies the conditions. Therefore, the answer is "YES".

-----Input-----
- The first line contains an integer, $t$, denoting the number of test cases.
- The first line of each test case contains an integer, $n$, denoting the number of boys and girls in the classroom.
- The second line of each test case contains $n$ space separated integers, $b_1,b_2, ... b_n$, denoting the heights of the boys.
- The second line of each test case contains $n$ space separated integers, $g_1,g_2,... g_n$, denoting the heights of the girls.

-----Output-----
Print exactly $t$ lines. In the $i^{th}$ of them, print a single line containing "$YES$" without quotes if it is possible to arrange the students in the $i^{th}$ test case, or "$NO$" without quotes if it is not.

-----Constraints-----
- $1 \leq t \leq 10$
- $1 \leq n \leq 100$
- $1 \leq b_i, g_i \leq 100$

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

-----Sample Output-----
YES

-----EXPLANATION-----
The following arrangement would satisfy the given conditions: $[b_1, g_1, b_2, g_2]$. This is because the boys and girls and...

# cook your dish here
a = int(input())
for i in range(a):
    n = int(input())
    b = list(map(int,input().split()))
    g = list(map(int,input().split()))
    b.sort()
    g.sort()
    h1 =[]
    h2= []
    for i in range(n):
        h1.append(b[i])
        h1.append(g[i])
    for i in range(n):
        h2.append(g[i])
        h2.append(b[i])
    if h1 == sorted(h1) or h2 ==  sorted(h2):
        print("YES")
    else:
        print("NO")


Solve in Python:
-----Problem Statement-----
Chef has a sequence of N segments: [L1, R1], [L2, R2], ..., [LN, RN]. He wants to transform the first segment to the last one (with index N). His plan is to do this big deal with a number of transformations: firstly he will transform

the first segment to the second one, then to the third one, then to the fourth one, and so on till N-th one.

Chef can use operation of a single type: shift one segment border by one unit. So, if he has segment [L, R], he can transform it into one of the following segments: [L + 1, R] (we will denote such operation with string L+), [L, R + 1] (will be denoted as R+), [L - 1, R] (L-), [L, R - 1] (R-). Chef doesn't like empty segments, therefore he cannot use any operation that makes a segment empty (L = R).

Chef really wants to transform his segment as fast as possible. Please, help him. Find the sequence with minimal number of operations that transforms his segment. If there are multiple such sequences pick the lexicographically minimal one.

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

The first line of each test case contains a single integer N denoting the number of segments Chef has.

The following N lines contain pairs of integers. The i-th line contains integers Li, Ri, denoting i-th Chef's segment.

-----Output-----
For each test case print an answer - two lines. The first line should contain the minimal number of operations. The second line should contain the sequence of operations

without any whitespaces.

-----Constraints-----
- 1 ≤ T, N ≤ 1000.
- -1000 ≤ Li < Ri ≤ 1000.
The total sum of N values for all test cases doesn't exceed 1000.

-----Example-----
Input:
4
3
-1 0
0 1
3 5
1
0 1
3
-2 -1
-2 -1
-2 0
4
4 6
3 5
-1 1
1 2

Output:
9
R+L+R+L+R+L+R+L+R+
0

1
R+
13
L-R-L-L-L-L-R-R-R-R-L+R+L+

for tc in range(int(input())):
 N = int(input())
 a, b = list(map(int, input().split()))
 pr = []

 # 'L' is lexicographically lower than 'R'.
 # so, we should first try to apply L+ or L-
 # if we can't then only we'll try to apply R+ or R-

 for i in range(N - 1):
  l, r = list(map(int, input().split()))

  #continue the following process until a == l and b == r
  while a != l or b != r:
   # trying to apply L-
   if a > l:
    a -= 1
    pr.append('L-')

   # now, trying to apply L+ (if a < b)
   elif a + 1 < b and a < l:
    a += 1
    pr.append('L+')

   # ok, so far, so good... now, let's try to apply R+
   elif b < r:
    b += 1
    pr.append('R+')

   # finally, lastly, trying to apply R- (if a < b)
   elif b - 1 > a and b > r:
    b -= 1
    pr.append('R-')

 print(len(pr))
 print(''.join(pr))


Solve in Python:
-----Problem Statement-----
Chef studies combinatorics. He tries to group objects by their rang (a positive integer associated with each object). He also gives the formula for calculating the number of different objects with rang N as following:

the number of different objects with rang N = F(N) = A0 + A1 * N + A2 * N2 + A3 * N3.

Now Chef wants to know how many different multisets of these objects exist such that sum of rangs of the objects in the multiset equals to S. You are given the coefficients in F(N) and the target sum S. Please, find the number of different multisets modulo 1,000,000,007.

You should consider a multiset as an unordered sequence of integers. Two multisets are different if and only if there at least exists one element which occurs X times in the first multiset but Y times in the second one, where (X ≠ Y).

-----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 integers A0, A1, A2, A3. The second line contains an integer S.

-----Output-----
For each test case, output a single line containing a single integer - the answer to the test case modulo 1,000,000,007.

-----Constraints-----
- 1 ≤ T ≤ 500
- 1 ≤ S ≤ 100
- 0 ≤ Ai ≤ 1000
- Sum of all S for all test cases is not greater than 500. It's guaranteed that at least one Ai is non-zero.

-----Example-----
Input:
4
1 0 0 0
1
1 0 0 0
3
0 1 0 0
2
2 3 1 4
10

Output:
1
3
3
213986343

-----Explanation-----
Example case 2.

In the second example function looks as follows F(N) = 1. So for each rang there is a single object of the rang. To get multiset with sum of rangs equal to 3, you can pick: three objects of rang 1, or one object of rang 1 and one of rang 2, or only one object of rang 3.
Example case 3.

In the third example function looks as follows F(N) = N. So, you have one distinct object of rang 1, two distinct objects of rang 2, three distinct objects of rang 3 and so on. To get
multiset with sum of...

# cook your dish here
import sys

mod_val = 1000000007
rang = [0]*101
pow_cache = [0]*102
multisets = {}

def mod_pow(base, pow):
 result = 1
 while pow:
  if pow&1:
   result = (result*base) % mod_val
  base = (base*base) % mod_val
  pow = pow>>1
 return result

def precalculate():

 for i in range(1, 102):
  pow_cache[i] = mod_pow(i, mod_val-2)

def cal_recurse(i, target_sum):
 if target_sum == 0:
  return 1
 if i>=target_sum:
  return 0
 if (i, target_sum) in multisets:
  return multisets[(i, target_sum)]
 ans = cal_recurse(i+1, target_sum)
 max_pos = target_sum//(i+1)
 choose = rang[i+1]%mod_val
 for j in range(1, max_pos+1):
  temp = choose*cal_recurse(i+1, target_sum-j*(i+1))
  # temp%=mod_val
  ans += temp
  ans %= mod_val
  choose *= rang[i+1]+j
  # choose %= mod_val
  choose *= pow_cache[j+1]
  choose %= mod_val
 multisets[i, target_sum] = ans
 return ans

def calculate(target_sum, rang_index):
 populate(target_sum, rang_index)
 return cal_recurse(0, target_sum)

def populate(target_sum, rang_i):
 for i in range(1, target_sum+1):
  rang[i] = rang_i[0] + (rang_i[1] + (rang_i[2] + rang_i[3]*i)*i)*i

_test_cases = int(input())
precalculate()
for _a_case in range(_test_cases):
 rang = [0]*101
 multisets = {}
 _rang_index = [int(i) for i in input().split(' ')]
 _target_sum = int(input())
 print(calculate(_target_sum, _rang_index))


Solve in Python:
-----Problem Statement-----
Harry Potter has one biscuit and zero rupee in his pocket. He will perform the following operations exactly $K$ times in total, in the order he likes:
- Hit his pocket, which magically increases the number of biscuits by one.
- Exchange $A$ biscuits to $1$ rupee.
- Exchange $1$ rupee to $B$ biscuits.
Find the maximum possible number of biscuits in Harry's pocket after $K$ operations.

-----Input-----
Input is given in the following format:
K A B

-----Output-----
Print the maximum possible number of biscuits in Harry's pocket after $K$operations.

-----Constraints-----
- $1 \leq K, A, B \leq 10^9$
- $K$, $A$ and  are integers.

-----Sample Input-----
4 2 6

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

-----EXPLANATION-----
The number of biscuits in Harry's pocket after $K$ operations is maximized as follows:
- Hit his pocket. Now he has $2$ biscuits and $0$ rupee.
- Exchange $2$ biscuits to $1$ rupee in his pocket .Now he has $0$ biscuits and $1$ rupee.
- Hit his pocket. Now he has $1$ biscuits and $1$ rupee.
- Exchange $1$ rupee to $6$ biscuits. his pocket. Now he has $7$ biscuits and $0$ rupee.

K,A,B = map(int,input().split())

if A + 2 > B:
    print(K + 1)
    return

start = A - 1
K -= start
ans = K//2 * (B-A) + K%2 + start + 1
print(ans)


Solve in Python:
-----Problem Statement-----
Levy's conjecture, named after Hyman Levy, states that all odd integers greater than 5 can be represented as the sum of an odd prime number and an even semiprime. To put it algebraically, 2n + 1 = p + 2q always has a solution in primes p and q (not necessary to be distinct) for n > 2. (Source: Wikipedia)
In this problem, given a positive integer N (not necessary to be odd integer greater than 5). Your task is to calculate how many distinct ordered pairs (p, q) such that N = p + 2q, where p and q are primes.

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

Each test case consists of exactly one line containing an integer N.

-----Constraints-----
- 1 ≤ T ≤ 100000 (105)
- 1 ≤ N ≤ 10000 (104)

-----Output-----
For each test case, output the number of ordered pairs (p, q) of primes such that N = p + 2q.

-----Example-----
Input:
3
2
7
11

Output:
0
1
2

-----Explanation-----
Case #1: There are no ordered pairs (p, q) such that p + 2q = 2.
Case #2: There is only one ordered pair (p, q) = (3, 2) such that p + 2q = 7.
Case #3: There are two ordered pairs (p, q) = (7, 2), (5, 3) such that p + 2q = 11.

def sieve(n):
 '''
    Sieve of eratosthenes
    Returns primesd: dictionary of primes upto n
      primesl: list of primes upto n
    '''
 l = [True]*(n+1)
 l[0] = False
 l[1] = False
 for i in range(2, n+1):
  j = i*i
  while j < n+1:
   l[j]=False
   j+=i
 primesd={}
 primesl = []
 for i in range(2, n+1):
  if l[i]:
   primesd[i]=True
   primesl.append(i)
 return primesd, primesl

primesd, primesl = sieve(10000)
pc = [0]*10001 # pc:- pair count

# pre-computing the counts for fast retreival
for e in primesl:
 for f in primesl:
  temp = e+2*f
  if temp > 10000:
   break
  pc[temp]+=1

t =int(input())

for __ in range(t):
 n = int(input())
 print(pc[n])


Solve in Python:
-----Problem Statement-----
One of the things JEC is known for is its GR (Group Recreation) where juniors and seniors do friendly interaction ;P
As for the new session of 2020 seniors decided to have their first GR and give them some treat. Juniors were excited about it they came to college canteen aligned in a line and counted themselves one by one from left to right so that every junior gets his/her treat. But seniors played a game and they will treat only the ones who passes in this game. Game is simple all they need to do is to alternate their language (between Hindi and English) while telling their positions that is if the junior just before you told 2 in English you need to say 3 in Hindi . You do not want to be the one left without a treat.
You are the junior standing at position $X$ from left and the counting could start from left or right you have to predict which number you have to speak and in which language when your turn comes.

-----Input:-----
-
First line will contain $T$, number of testcases. Then the testcases follow.
-
Each testcase contains 2 lines first consist 2 space separated integers, $N$ (total count) , $X$ (your position from left), next line consist of 2 space separated characters  L or R (Direction from which counting starts L-left, R-Right) and H or E (the language to start counting).

-----Output:-----
For each testcase, output a single line consisting space seperated Integer P and Character L
where P is the number you will speak and L is the language (H or E).

-----Constraints-----
- $1 \leq T \leq 1000$
- $1 \leq N \leq 120$
- $1 \leq X \leq N$

-----Sample Input:-----
2
15 5
L H
20 14
R E

*try to trim extra white spaces like new line during input in case of wrong answer

-----Sample Output:-----
5 H
7 E

-----EXPLANATION:-----
- When counting starts from left with H it alternates like H E H E H….. on the fifth position H comes
- When Count starts from right with E it alternates like E H E H E H E….. with E on the position of 14th student from right.


Solve in Python:
-----Problem Statement-----
Sereja has a sequence of n integers a[1], a[2], ..., a[n]. Sereja can do following transformation of the array:

- create a new sequence of n integers b[1], b[2], ..., b[n]in this way:    (1 ≤ i ≤ n)

- Replace the sequence a by b, i.e., a[i] = b[i] for all i in [1, n]

Sereja decided to use his transformation k times. Then he computed the value of      , where r — the sequence obtained after k transformations of sequence a, as described above.

Sereja lost sequence a, but he was left with the numbers q(r) and k. Now Sereja is interested in the question : what is the number of the sequences of the integers с[1], с[2], ..., с[n], such that 1 ≤ c[i] ≤ m and q(d) = q(r), where d — the sequence obtained after k transformations of sequence c, as described above.

-----Input-----
The first lines contains a single integer T, denoting the number of test cases. Each  test case consist of four integers : n, m, q(r), k.

-----Output-----
In a single line print the remainder of division the answer of the problem on number 10^9 + 7.

-----Constraints-----

- 1 ≤ T ≤ 10000
- 1 ≤ n, m, q(r), k ≤ 10^9

-----Example-----
Input:
3
1 1 1 1
2 2 1 1
2 3 1 1

Output:
0
2
4

def mod(a,b,c):
 x = 1
 y = a
 while(b>0):
  if(b%2==1):
   x = (x*y)%c
  y = (y*y)%c
  b /=2
 return x%c
t = int(input())
num = 10**9+7
for i in range(t):
 n,m,q,k = list(map(int,input().split()))
 if m<=q:
  print(0)
 else:
  a1 = m-q
  a2 = mod(q+1,n,num)
  a3 = mod(q-1,n,num)
  a4 = mod(q,n,num)
  a5 = a2-2*a4+a3
  ans = a1*a5
  print(ans%num)


Solve in Python:
-----Problem Statement-----
We have an integer sequence $A$, whose length is $N$.
Find the number of the non-empty contiguous subsequences of $A$ whose sum is $0$. Note that we are counting the ways to take out subsequences. That is, even if the contents of some two subsequences are the same, they are counted individually if they are taken from different positions.

-----Input-----
Input is given in the following format:
$N$
$A_1$ $A_2$  . . .  $A_N$

-----Output-----
Find the number of the non-empty contiguous subsequences of $A$ whose sum is $0$.

-----Constraints-----
- $1 \leq N \leq 2\times10^5$
- $-10^9 \leq A_i \leq 10^9$
- All values in input are integers.

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

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

-----EXPLANATION-----
There are three contiguous subsequences whose sums are $0$: $(1, 3, -4)$, $(-4, 2, 2)$ and $(2, -2)$

'''
n=int(input())
a=list(map(int,input().split()))
sum=0
c=0
for i in range(len(a)):
    sum+=a[i]
    #print(sum)
    if sum==0:
     c+=1
     sum=a[i]
print(c)

'''
from collections import Counter
n=int(input())
a=list(map(int,input().split()))
res=0
#lst=[a[0]]
sum=0
lst=[]
#print(lst)
#print(lst[-1])
for i in range(n):
 sum+=a[i]
 lst.append(sum)
#print(lst)
count=Counter(lst)
#print(count[0])
#print(count.values())
count[0]+=1
#print(count[0])
#print(count.values())
for i in list(count.values()):
 res+=i*(i-1)//2
print(res)


Solve in Python:
-----Problem Statement-----
Write a program that accepts a number, n, and outputs the same.

-----Input-----
The only line contains a single integer.

-----Output-----
Output the answer in a single line.

-----Constraints-----
- 0 ≤ n ≤ 105

-----Sample Input-----
123

-----Sample Output-----
123

# cook your dish here
a = int(input())
print(a)


Solve in Python:
-----Problem Statement-----
You all must have played the game candy crush. So here is a bomb which works much the fruit bomb in candy crush. A designer, Anton, designed a very powerful bomb. The bomb, when placed on a location $(x, y)$ in a $R \times C$ grid, wipes out the row $x$ and column $y$ completely.
You are given a $R\times C$ grid with $N$ targets. You have only one bomb. Your aim is to maximize the damage and hence destroy most number of targets. Given the location of targets on the grid, find out the number of targets that can destroyed.
The grid system uses index starting with $0$.

-----Input-----
- First line contains three space separated integers, $R$, $C$ and $N$. Then, $N$ lines follow.
- Each line contains space separated integers $r$ and $c$ mentioning the location of the target.

-----Output-----
A single integer giving the number of targets that can be destroyed.

-----Constraints-----
- $1 \leq R, C \leq 3 \times 10^5$
- $1 \leq N \leq min(R \times C,  3 \times 10^5)$
- $0 \leq r < R$
- $0 \leq c < C$
- Any input pair $(r, c)$ is not repeated.

-----Subtasks-----
The total marks will be divided into:
- 20% : $R, C \leq 10^3$
- 80% : Original Constraints

-----Sample Input-----
2 3 3
1 1
0 0
0 2

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

-----EXPLANATION-----
It is possible to destroy all the targets if we place the bomb at $(0, 1)$. Hence, total number of targets destroyed is $3$, which is our answer.

r,c,n=list(map(int,input().split()))
ro=[0]*(r+1)
co=[0]*(c+1)
for i in range(n):
    a,b=list(map(int,input().split()))
    ro[a]+=1
    co[b]+=1
ma=0
ma+=max(ro)
ma+=max(co)
print(ma)


Solve in Python:
-----Problem description-----
As a holiday gift, Tojo received a probability problem. The problem read as follows
Consider an N by M grid. Rows are numbered 1 to N, from top to bottom. Columns are numbered 1 to M, from left to right. You are initially at cell (1, 1) and want to go to cell (N, M). From any cell you can move to the cell below it or to the cell right to it. You should never go out of the grid. At any point you should consider all the possibilities of movement with equal probability
Let P[i][j] be the probability of visiting cell (i, j). You need to calculate the sum of P[i][j] for 1 ≤ i ≤ N, 1 ≤ i ≤ M.
As we all know, Tojo really hates probability related problems. He wants you to solve this task

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.Only line of each test case has two integer N and M.

-----Output-----
For each test case, output a single line containing the required answer. Answers within an absolute or relative error of 10-6 will be accepted.

-----Constraints-----
- 1 ≤ T ≤ 1000
- 1 ≤ N ≤ 1000
- 1 ≤ M ≤ 1000

-----Example-----
Input:
2
2 2
1 6

Output:
3.000000
6.000000

-----Explanation-----
Example case 1
Probability matrix P for N=2, M=2 is

1.0 0.5

0.5 1.0

You are at (1, 1) initially. So the probablity of visiting (1, 1) is 1. At (1, 1) you have 2 options, move below to (2, 1) or to right cell (1, 2). Probablity of going to (1, 2) is 0.5. Probability of going to (2, 1) is 0.5. You always end up at (2, 2), so P[2][2] is 1. Required sum = 1.0 + 0.5 + 0.5 + 1.0 = 3.0
Example case 2
Probability matrix P for N=1, M=6 is

1.0 1.0 1.0 1.0 1.0 1.0

Because at any position there is only one possible next position.

T = int(input())
for i in range(T):
 n, m = list(map(int, input().split()))
 print(n + m - 1)


Solve in Python:
-----Problem description.-----
This problem deals with the I/O methods used in codechef.
You are supposed to print the integer in its reverse form , or in simple words, print the reverse of the given integer . For instance , reverse of  120 is 21  (not 021)  .

-----Input-----
- The first line of each test case contains an integer T .

- following T lines contains distinct integers N .

-----Output-----
- Output should contain T line , each line with the distinct integer as asked in question .

-----Constraints-----
- 1 ≤ T ≤ 105

- 1 ≤ N ≤ 1018

Subtask 1 :  N ≤ 105
Subtask 2 :  N ≤ 109
Subtask 3 :  N ≤ 1018

-----Example-----
Input:
3
1234
4567
1

Output:
4321
7654
1

-----Explanation-----
reverse of 1234 is 4321 , 4567 is 7654 & of 1 is 1

NOTE: testcases may contain large range of data, use datatypes accordingly .

for i in range(int(input())):
 print(int(input()[::-1]))


Solve in Python:
-----Problem-----

			Nikki's latest work is writing a story of letters. However, she finds writing story so boring that, after working for three hours, she realized that all she has written are M long words consisting entirely of letters A and B. Having accepted that she will never finish the story in time, Nikki has decided to at least have some fun with it by counting bubbly words.

			Now Nikki is connecting pairs of identical letters (A with A, B with B) by drawing lines above the word. A given word is bubbly if each letter can be connected to exactly one other letter in such a way that no two lines intersect. So here is your task. Help Nikki count how many words are bubbly.

-----Input-----
-
			The first line of input contains the positive integer M, the number of words written down by Nikki.

-
			Each of the following M lines contains a single word consisting of letters A and B, with length

			between 2 and 10^5, inclusive. The sum of lengths of all words doesn't exceed 10^6.

-----Output-----

			The first and only line of output must contain the number of bubbly words.

-----Constraints-----
-
			1 ≤ M ≤ 100

-----Sample Input-----

3

ABAB

AABB

ABBA

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

-----Explanation-----
-
					 ABAB - It is not bubbly as A(indexed 1) will connect to A(indexed 3) by a line and when we try to connect B(indexed 2) with B(indexed 4) by a line then it will intersect with the line b/w A and A.

-
					AABB - It is bubbly as line b/w A and A will not intersect with the line b/w B and B.

-
ABBA -It is also bubbly as lines will not intersect. We can draw line b/w A and A above the line b/w B and B.
				 p { text-align:justify }

def check(s):
 arr=[s[0]]
 l=len(s)
 f1=0
 for i in range(1,l):
  if arr==[]: arr.append(s[i])
  elif arr[-1]!=s[i]:arr.append(s[i])
  else: del arr[-1]
 if arr==[]: return True
 else: return False

count = 0
for t in range(eval(input())):
 s=input().strip()
 if check(s): count+=1
print(count)


Solve in Python:
-----Problem-----

			Once THANMAY met PK who is from a different planet visiting earth. THANMAY was very fascinate to learn PK's language. The language contains only lowercase English letters and is based on a simple logic that only certain characters can follow a particular character.

			Now he is interested in calculating the number of possible words of length L and ending at a particular character C. Help THANMAY to calculate this value.

-----Input-----

			The input begins with 26 lines, each containing 26 space-separated integers. The integers can be either 0 or 1. The jth integer at ith line depicts whether jth English alphabet can follow ith English alphabet or not.

			 Next line contains an integer T. T is the number of queries.

			 Next T lines contains a character C and an integer L.

-----Output-----

			For each query output the count of words of length L ending with the character C. Answer to each query must be followed by newline character.

			The answer may be very large so print it modulo 1000000007.

-----Constraints-----
-
					1 ≤ T ≤ 100
-
C is lowercase English alphabet.

-
					2 ≤ L ≤ 10000000

-----Sample Input-----
0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0 0...

d = {}
for i in range(26):
 char = chr(i+ord('a'))
 d[char] = []
for i in range(26):
 char = chr(i+ord('a'))
 temp = list(map(int,input().strip().split()))
 for j in range(26):
  if (temp[j] == 1):
   follow= chr(j+ord('a'))
   d[follow].append(char)

def f(char,i,n,count):
 if (i==n):
  return count+1
 else:
  ans = 0
  for c in d[char]:
   ans+=f(c,i+1,n,0)
   ans%=(10**9+7)
  return ans

for q in range(int(input().strip())):
 c, n = input().strip().split()
 n = int(n)
 print(f(c,1,n,0))


Solve in Python:
-----Problem-----

Suppose there is a circle. There are N Juice shops on that circle. Juice shops are numbered 0 to N-1 (both inclusive). You have two pieces of information corresponding to each of the juice shop:
(1) the amount of Juice that a particular Juice shop can provide and
(2) the distance from that juice shop to the next juice shop.

Initially, there is a man with a bottle of infinite capacity carrying no juice. He can start the tour at any of the juice shops. Calculate the first point from where the man will be able to complete the circle. Consider that the man will stop at every Juice Shop. The man will move one kilometer for each litre of the juice.

-----Input-----
-
The first line will contain the value of N.

-
The next N lines will contain a pair of integers each, i.e. the amount of juice that a juice shop can provide(in litres) and the distance between that juice shop and the next juice shop.

-----Output-----

An integer which will be the smallest index of the juice shop from which he can start the tour.

-----Constraints-----
-
					1 ≤ N ≤ 105
-
					1 ≤ amt of juice, distance  ≤ 109

-----Sample Input-----
3

1 5

10 3

3 4

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

-----Explanation-----

			He can start the tour from the SECOND Juice shop.
		 p { text-align:justify }

import re,sys
def isCirlePossible(juices,distances):
 if juices == [] or distances == []:
  return -1;
 total_juice_consumed = 0
 juice_consumed = 0
 start=0
 for i in range(0,len(juices)):
  diff = juices[i] - distances[i]
  if juice_consumed >= 0:
   juice_consumed += diff
  else:
   juice_consumed = diff
   start = i
  total_juice_consumed += diff
 return start if total_juice_consumed >= 0 else -1

juices = []
distances = []
numLines = int(input())
for each in range(0,numLines):
 line = input()
 result = [int(x) for x in re.findall('\d+',line)]
 if result != []:
  juices.append(result[0])
  distances.append(result[1])

print(isCirlePossible(juices,distances))
return


Solve in Python:
-----Problem-----

There is an infinite one dimensional array ranging from (-infinity, infinity).A Zombie is currently at cell number 0. The zombie wants to reach cell number H. The Zombie moves in only two ways. The Zombie either

Makes U steps to the right (positive side) or

Makes D steps to the left (negative side).

Your task is to find the minimum number of moves the Zombie require to reach the goal.

-----Input-----

The first line contains the number of test cases T. Each of the next T lines contains 3 space

separated integers, H U D.

-----Output-----

For each test case, output one line with an integer, the minimum number of moves required to reach H from 0. If it is impossible, print -1 instead.

-----Constraints-----

-

T ≤ 10000

-

1 ≤ H, U, D ≤ 109

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

3 2 1

3 2 2

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

-1

-----Explanation-----

-

In the first sample case, first move 2 steps to the right to reach cell number 2. Then 1 step to the left  to reach cell number 1 and finally 2 more steps to the right to reach the goal. Thus 3 moves are required

which is the minimum.

-

Because both U and D are even, you will always be in an even cell.Thus there is no way to reach cell      number 3.

p { text-align:justify }

import fractions
for t in range(int(input())):
 h,u,d = list(map(int,input().split()))
 g = fractions.gcd(u,d)
 if (h%g!=0):
  print(-1)
 else:
  m = 0
  n = -1
  while (True):
   n = (float(m)*u-h)/d
   if (n>0 and int(n) == n):
    break
   m+=1
  print(int(m+n))


Solve in Python:
.task {
  background: #fff;
  color: #333;
  padding: 25px;
  box-sizing: border-box;
  font-family: Comfortaa, sans-serif !important;
  position: relative;
}
.task code, .task_code {
  display: inline-block;
  padding: 0;
  border-radius: 2px;
  margin: 0;
  position: relative;
  top: 6px;
  background: bisque;
  border: 1px solid #f9d2a4;
  padding: 3px;
  line-height: 1em;
}
.task_code {
  top: -1px;
}
.task_header {
  color: #333 !important;
  margin-top: 0;
  font-size: 30px !important;
}
.task_inner {
  box-shadow: 0 2px 11px -3px rgba(0,0,0,.6);
  padding: 20px;
  border-radius: 3px;
}
.task_devil {
  float: right;
  margin-left: 15px;
  shape-outside: circle(150px);
}
.task_devil img {
  max-width: 150px;
}
.task_part-header {
  font-size: 20px !important;
  font-weight: 800;
  color: #333;
  padding: 20px 0 10px;
}
.task_part-header:first-of-type {
  padding-top: 0;
}
.task_list {
  padding: 0;
  margin: 10px 0;
  padding-left: 30px;
}
.task_list ul {
  padding: 0;
  margin: 0;
}
.font-effect-canvas-print { color: black; }

Devil's Sequence

Problem

    Robodevil likes to do some mathematics between rehearsals of his orchestra. Today he invented devilish sequence No. 1729:

x0 = 0,
x1 = 1,
xn = (xn - 1 + xn - 2) / 2.

    For example, x10 = 0.666015625. Robodevil became interested at once how many `sixes` there were at the beginning of an arbitrary xn. In 6 nanoseconds, he had a formula. Can you do the same?
    Input
    You are given an integer n; `2 ≤ n ≤ 100000`.
    Output
    Output the number of sixes at the beginning of xn in decimal notation.
    Example

Input
Output

10
3

from math import floor, log
def count_sixes(n):
    return floor((n - n % 2) * log(2, 10))


Solve in Python:
10^{10^{10}} participants, including Takahashi, competed in two programming contests.
In each contest, all participants had distinct ranks from first through 10^{10^{10}}-th.
The score of a participant is the product of his/her ranks in the two contests.
Process the following Q queries:
 - In the i-th query, you are given two positive integers A_i and B_i. Assuming that Takahashi was ranked A_i-th in the first contest and B_i-th in the second contest, find the maximum possible number of participants whose scores are smaller than Takahashi's.

-----Constraints-----
 - 1 \leq Q \leq 100
 - 1\leq A_i,B_i\leq 10^9(1\leq i\leq Q)
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
Q
A_1 B_1
:
A_Q B_Q

-----Output-----
For each query, print the maximum possible number of participants whose scores are smaller than Takahashi's.

-----Sample Input-----
8
1 4
10 5
3 3
4 11
8 9
22 40
8 36
314159265 358979323

-----Sample Output-----
1
12
4
11
14
57
31
671644785

Let us denote a participant who was ranked x-th in the first contest and y-th in the second contest as (x,y).
In the first query, (2,1) is a possible candidate of a participant whose score is smaller than Takahashi's. There are never two or more participants whose scores are smaller than Takahashi's, so we should print 1.

#!python3

# input
Q = int(input())
A, B = [None] * Q, [None] * Q
for i in range(Q):
    A[i], B[i] = sorted(map(int, input().split()))

def solve(a, b):
    w = a * b - 1
    left, right = 0, b - a
    while right - left > 1:
        x = (left + right) // 2
        v = w // (a + x)
        if v < a:
            right = x
        else:
            left = x

    n = left
    left, right = 0, n
    while right - left > 1:
        x = (left + right) // 2
        v = w // (a + x)
        if v < a + x:
            right = x
        else:
            left = x

    return right + (w // (a + right)) - (w // (a + n))

def main():
    for a, b in zip(A, B):
        ans = 2 * (a - 1) + solve(a, b)
        print(ans)

def __starting_point():
    main()

__starting_point()


Solve in Python:
12:17 (UTC): The sample input 1 and 2 were swapped. The error is now fixed. We are very sorry for your inconvenience.
There are N children in AtCoder Kindergarten, conveniently numbered 1 through N. Mr. Evi will distribute C indistinguishable candies to the children.
If child i is given a candies, the child's happiness will become x_i^a, where x_i is the child's excitement level. The activity level of the kindergarten is the product of the happiness of all the N children.
For each possible way to distribute C candies to the children by giving zero or more candies to each child, calculate the activity level of the kindergarten. Then, calculate the sum over all possible way to distribute C candies. This sum can be seen as a function of the children's excitement levels x_1,..,x_N, thus we call it f(x_1,..,x_N).
You are given integers A_i,B_i (1≦i≦N). Find  modulo 10^9+7.

-----Constraints-----
 - 1≦N≦400
 - 1≦C≦400
 - 1≦A_i≦B_i≦400 (1≦i≦N)

-----Partial Score-----
 - 400 points will be awarded for passing the test set satisfying A_i=B_i (1≦i≦N).

-----Input-----
The input is given from Standard Input in the following format:
N C
A_1 A_2 ... A_N
B_1 B_2 ... B_N

-----Output-----
Print the value of  modulo 10^9+7.

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

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

This case is included in the test set for the partial score, since A_i=B_i.
We only have to consider the sum of the activity level of the kindergarten where the excitement level of both child 1 and child 2 are 1 (f(1,1)).
 - If child 1 is given 0 candy, and child 2 is given 3 candies, the activity level of the kindergarten is 1^0*1^3=1.
 - If child 1 is given 1 candy, and child 2 is given 2 candies, the activity level of the kindergarten is 1^1*1^2=1.
 - If child 1 is given 2 candies, and child 2 is given 1 candy, the activity level of the kindergarten is 1^2*1^1=1.
 - If child 1 is given 3 candies, and child 2 is given 0 candy, the activity level of the kindergarten is 1^3*1^0=1.
Thus, f(1,1)=1+1+1+1=4, and the sum over all f is also 4.

import sys
input = sys.stdin.readline
import numpy as np

MOD = 10 ** 9 + 7

N,C = map(int,input().split())
A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]

# (i,j) に j^i を入れる
kth_pow = np.ones((1024, 401), dtype=np.int64)
rng = np.arange(401, dtype=np.int64)
for i in range(1,C+1):
    kth_pow[i] = kth_pow[i-1] * rng % MOD
kth_pow_cum = kth_pow.cumsum(axis = 1) % MOD
kth_pow_cum[C+1:] = 0

def convolve(A,B,n=32):
    if n == 8:
        return np.rint(np.fft.irfft(np.fft.rfft(A) * np.fft.rfft(B))).astype(np.int64)
    n //= 2
    M = 1 << n
    A1 = A // M
    A2 = A - M * A1
    B1 = A // M
    B2 = B - M * B1
    X = convolve(A1,B1,n)
    Y = convolve(A1-A2,B1-B2,n)
    Z = convolve(A2,B2,n)
    return (X * (M * M % MOD) + (X + Z - Y) * M + Z) % MOD

dp = np.zeros(1024, dtype=np.int64) # これまで配った個数、合計点
dp[0] = 1
for a,b in zip(A,B):
    arr = kth_pow_cum[:,b] - kth_pow_cum[:,a-1]
    dp = convolve(dp,arr)
    dp[C+1:] = 0

answer = dp[C]
print(answer)


Solve in Python:
2021 was approaching and the world was about to end. So 2 gods Saurabhx and Saurabhy (from Celesta) created the Cyberverse. But this time disappointed with humans both the gods decided not to have humans in this world. So they created a world of cyborgs. A world without humans. Isn’t it interesting? So let us dive into the cyberverse and have a look at their problems.
There are $N$ kid cyborgs with Chief Cyborg '100gods' and he has $K$ weapons with him. He wants to distribute those $K$ weapons among $N$ kid cyborgs. Since all the kid cyborgs are very good friends, so they set a rule among themselves for taking those weapons. The rule states that the difference between kid cyborg having the maximum weapons and the kid cyborg having minimum weapons should be less than or equal to $1$.

Find the value of the minimum number of weapons a kid cyborg can have when all the $K$ weapons are distributed among them.

-----Input:-----
- The first line contains an integer $T$, denoting the number of test cases.
- Each of the next $T$ lines will contain two space-separated integers denoting $N$ and $K$ respectively.

-----Output:-----
- For each test case ,output a single line containing an integer $X$ denoting the minimum number of weapons a kid cyborg can have in that test case.

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

-----Sample Input:-----
1
5 8

-----Expected Output:-----
1

-----Explanation-----
- There are $5$ kids and $8$ weapons.
- Hence we will distribute the weapons such that $3$ kids have $2$ weapons each and the remaining $2$ kids have $1$ weapon each.
- Hence the minimum number of weapons a kid cyborg has is $1$. (  That is, $min(1,2)$ = $1$ )

# cook your dish here
t=int(input())
for i in range(0,t):
 s=input().split(" ")
 k=list(map(int,s))
 print(k[1]//k[0])


Solve in Python:
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
Task:
Write
```
smallest(n)
```
that will find the smallest positive number that is evenly divisible by all of the numbers from 1 to n (n <= 40).
E.g
```python
smallest(5) == 60 # 1 to 5 can all divide evenly into 60
smallest(10) == 2520
```

def smallest(n):
    previous = 1
    for i in range(1,n+1):
        previous = mmc(previous,i)                         #mmc stands for least common multiple
        previous = int(previous)                           #the mmc function returns float
    return previous

def mmc(num1, num2):
    a = num1
    b = num2

    resto = None
    while resto is not 0:
        resto = a % b
        a  = b
        b  = resto

    return (num1 * num2) / a


Solve in Python:
3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or alive

NEKO#ΦωΦ has just got a new maze game on her PC!

The game's main puzzle is a maze, in the forms of a $2 \times n$ rectangle grid. NEKO's task is to lead a Nekomimi girl from cell $(1, 1)$ to the gate at $(2, n)$ and escape the maze. The girl can only move between cells sharing a common side.

However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.

After hours of streaming, NEKO finally figured out there are only $q$ such moments: the $i$-th moment toggles the state of cell $(r_i, c_i)$ (either from ground to lava or vice versa).

Knowing this, NEKO wonders, after each of the $q$ moments, whether it is still possible to move from cell $(1, 1)$ to cell $(2, n)$ without going through any lava cells.

Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?

-----Input-----

The first line contains integers $n$, $q$ ($2 \le n \le 10^5$, $1 \le q \le 10^5$).

The $i$-th of $q$ following lines contains two integers $r_i$, $c_i$ ($1 \le r_i \le 2$, $1 \le c_i \le n$), denoting the coordinates of the cell to be flipped at the $i$-th moment.

It is guaranteed that cells $(1, 1)$ and $(2, n)$ never appear in the query list.

-----Output-----

For each moment, if it is possible to travel from cell $(1, 1)$ to cell $(2, n)$, print "Yes", otherwise print "No". There should be exactly $q$ answers, one after every update.

You can print the words in any case (either lowercase, uppercase or mixed).

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

Output
Yes
No
No
No
Yes

-----Note-----

We'll crack down the example test here:  After the first query, the girl still able to reach the goal. One of the shortest path ways should be: $(1,1) \to (1,2) \to (1,3) \to (1,4)...

import sys
readline = sys.stdin.readline

N, Q = list(map(int, readline().split()))
state = [[False]*(N+2) for _ in range(2)]

cnt = 0

Ans = [None]*Q
for qu in range(Q):
    r, c = list(map(int, readline().split()))
    r -= 1
    c -= 1
    state[r][c] = not state[r][c]
    res = state[r-1][c-1] + state[r-1][c] + state[r-1][c+1]
    if state[r][c]:
        cnt += res
    else:
        cnt -= res
    Ans[qu] = 'No' if cnt else 'Yes'
print('\n'.join(Ans))


Solve in Python:
< PREVIOUS KATA
NEXT KATA >

## Task:

You have to write a function `pattern` which returns the following Pattern(See Examples) upto desired number of rows.

* Note:`Returning` the pattern is not the same as `Printing` the pattern.

## Parameters:

    pattern(        n        ,        y        );
                    ^                 ^
                    |                 |
             Term upto which   Number of times
              Basic Pattern     Basic Pattern
                should be         should be
                 created          repeated
                                 vertically

* Note: `Basic Pattern` means what we created in Complete The Pattern #12 i.e. a `simple X`.

## Rules/Note:

* The pattern should be created using only unit digits.
* If `n < 1` then it should return "" i.e. empty string.
* If `y <= 1` then the basic pattern should not be repeated vertically.
* `The length of each line is same`, and is equal to the length of longest line in the pattern.
* Range of Parameters (for the sake of CW Compiler) :
  + `n ∈ (-∞,50]`
  + `y ∈ (-∞,25]`
* If only one argument is passed then the function `pattern` should run as if `y <= 1`.
* The function `pattern` should work when extra arguments are passed, by ignoring the extra arguments.

## Examples:

#### Having Two Arguments:

##### pattern(4,3):

        1     1
         2   2
          3 3
           4
          3 3
         2   2
        1     1
         2   2
          3 3
           4
          3 3
         2   2
        1     1
         2   2
          3 3
           4
          3 3
         2   2
        1     1

##### pattern(10,2):

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


Solve in Python:
< PREVIOUS KATA
NEXT KATA >

## Task:

You have to write a function `pattern` which returns the following Pattern(See Examples) upto desired number of rows.

* Note:```Returning``` the pattern is not the same as ```Printing``` the pattern.

### Parameters:

    pattern(        n        ,        x        ,        y        );
                    ^                 ^                 ^
                    |                 |                 |
             Term upto which   Number of times   Number of times
              Basic Pattern     Basic Pattern     Basic Pattern
                should be         should be         should be
                 created          repeated           repeated
                                horizontally        vertically

* Note: `Basic Pattern` means what we created in Complete The Pattern #12

## Rules/Note:

* The pattern should be created using only unit digits.
* If `n < 1` then it should return "" i.e. empty string.
* If `x <= 1` then the basic pattern should not be repeated horizontally.
* If `y <= 1` then the basic pattern should not be repeated vertically.
* `The length of each line is same`, and is equal to the length of longest line in the pattern.
* Range of Parameters (for the sake of CW Compiler) :
  + `n ∈ (-∞,25]`
  + `x ∈ (-∞,10]`
  + `y ∈ (-∞,10]`
* If only two arguments are passed then the function `pattern` should run as if `y <= 1`.
* If only one argument is passed then the function `pattern` should run as if `x <= 1` & `y <= 1`.
* The function `pattern` should work when extra arguments are passed, by ignoring the extra arguments.

## Examples:

* Having Three Arguments-

 + pattern(4,3,2):

        1     1     1     1
         2   2 2   2 2   2
          3 3   3 3   3 3
           4     4     4
          3 3   3 3   3 3
         2   2 2   2 2   2
        1     1     1     1
         2   2 2   2 2   2
          3 3   3 3   3 3
           4     4     4
          3 3   3 3   3 3
         2   2 2   2 2   2
        1     1     1 ...

pattern=lambda n,x=1,y=1,*args: "\n".join((lambda h: h+(["\n".join(h[1:]) for k in range(1,y)]))([(lambda r: "".join(r)+"".join(["".join(r[1:]) for j in range(1,x)]))([" "]*(i-1)+[str(i%10)]+[" "]*(2*(n-i)-1)+[str(i%10)]+[" "]*(i-1)) for i in range(1,n)]+[(lambda r: r+"".join([r[1:] for j in range(1,x)]) )(" "*(n-1)+str(n%10)+" "*(n-1))]+[(lambda r: "".join(r)+"".join(["".join(r[1:]) for j in range(1,x)]))([" "]*(i-1)+[str(i%10)]+[" "]*(2*(n-i)-1)+[str(i%10)]+[" "]*(i-1)) for i in range(n-1,0,-1)])) if n>0 else ""

#this one-liner was not so easy :D Dedicated to my fellow codewarrior ChristianECooper:
#knowing that my code can be read by someone that good and precise keeps me surely
#motivated; against him I may have the upper hand just with regexes (and he
#certainly is better at explaining), but I won't give up that easily ;)


def pattern(n):
    if n == 1:
        return "1"
    if n < 1:
        return ""
    top = "\n".join([" " * (n - 1) + str(i % 10) * n + " " * (n - 1) for i in range(1, n)])
    result = [top]
    nums = [str(i % 10) for i in range(1, n)]
    result.append("\n".join(["".join(nums) + str(n % 10) * n + "".join(nums[::-1])] * n))
    result.append(top[::-1])
    return "\n".join(result)


Solve in Python:
=====Example=====
In Python, a string can be split on a delimiter.

Example:
>>> a = "this is a string"
>>> a = a.split(" ") # a is converted to a list of strings.
>>> print a
['this', 'is', 'a', 'string']

Joining a string is simple:

>>> a = "-".join(a)
>>> print a
this-is-a-string

=====Problem Statement=====
You are given a string. Split the string on a " " (space) delimiter and join using a - hyphen.

=====Input Format=====
The first line contains a string consisting of space separated words.

=====Output Format=====
 Print the formatted string as explained above.

# Enter your code here. Read input from STDIN. Print output to STDOUT
print(("-").join(input().strip().split()))


Solve in Python:
=====Function Descriptions=====
 min

The tool min returns the minimum value along a given axis.

import numpy

my_array = numpy.array([[2, 5],
                        [3, 7],
                        [1, 3],
                        [4, 0]])

print numpy.min(my_array, axis = 0)         #Output : [1 0]
print numpy.min(my_array, axis = 1)         #Output : [2 3 1 0]
print numpy.min(my_array, axis = None)      #Output : 0
print numpy.min(my_array)                   #Output : 0

By default, the axis value is None. Therefore, it finds the minimum over all the dimensions of the input array.

max

The tool max returns the maximum value along a given axis.

import numpy

my_array = numpy.array([[2, 5],
                        [3, 7],
                        [1, 3],
                        [4, 0]])

print numpy.max(my_array, axis = 0)         #Output : [4 7]
print numpy.max(my_array, axis = 1)         #Output : [5 7 3 4]
print numpy.max(my_array, axis = None)      #Output : 7
print numpy.max(my_array)                   #Output : 7

By default, the axis value is None. Therefore, it finds the maximum over all the dimensions of the input array.

=====Problem Statement=====
You are given a 2-D array with dimensions NXM.
Your task is to perform the min function over axis 1 and then find the max of that.

=====Input Format=====
The first line of input contains the space separated values of N and M.
The next N lines contains M space separated integers.

=====Output Format=====
Compute the min along axis 1 and then print the max of that result.

import numpy
n,m = list(map(int,input().split()))
ar = []
for i in range(n):
    tmp = list(map(int,input().split()))
    ar.append(tmp)
np_ar = numpy.array(ar)
print((numpy.max(numpy.min(np_ar,axis=1))))


Solve in Python:
=====Function Descriptions=====
*This section assumes that you understand the basics discussed in HTML Parser - Part 1

.handle_comment(data)
This method is called when a comment is encountered (e.g. <!--comment-->).
The data argument is the content inside the comment tag:

from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):
    def handle_comment(self, data):
          print "Comment  :", data

.handle_data(data)
This method is called to process arbitrary data (e.g. text nodes and the content of <script>...</script> and <style>...</style>).
The data argument is the text content of HTML.

from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):
    def handle_data(self, data):
        print "Data     :", data

=====Problem Statement=====
You are given an HTML code snippet of N lines.
Your task is to print the single-line comments, multi-line comments and the data.

Print the result in the following format:

>>> Single-line Comment
Comment
>>> Data
My Data
>>> Multi-line Comment
Comment_multiline[0]
Comment_multiline[1]
>>> Data
My Data
>>> Single-line Comment:

Note: Do not print data if data == '\n'.

=====Input Format=====
The first line contains integer N, the number of lines in the HTML code snippet.
The next N lines contains HTML code.

=====Constraints=====
0<N<100

=====Output Format=====
Print the single-line comments, multi-line comments and the data in order of their occurrence from top to bottom in the snippet.

Format the answers as explained in the problem statement.

from html.parser import HTMLParser
class CustomHTMLParser(HTMLParser):
    def handle_comment(self, data):
        number_of_line = len(data.split('\n'))
        if number_of_line>1:
            print('>>> Multi-line Comment')
        else:
            print('>>> Single-line Comment')
        if data.strip():
            print(data)

    def handle_data(self, data):
        if data.strip():
            print(">>> Data")
            print(data)

parser = CustomHTMLParser()

n = int(input())

html_string = ''
for i in range(n):
    html_string += input().rstrip()+'\n'

parser.feed(html_string)
parser.close()


Solve in Python:
=====Function Descriptions=====
.difference()

The tool .difference() returns a set with all the elements from the set that are not in an iterable.
Sometimes the - operator is used in place of the .difference() tool, but it only operates on the set of elements in set.
Set is immutable to the .difference() operation (or the - operation).

>>> s = set("Hacker")
>>> print s.difference("Rank")
set(['c', 'r', 'e', 'H'])

>>> print s.difference(set(['R', 'a', 'n', 'k']))
set(['c', 'r', 'e', 'H'])

>>> print s.difference(['R', 'a', 'n', 'k'])
set(['c', 'r', 'e', 'H'])

>>> print s.difference(enumerate(['R', 'a', 'n', 'k']))
set(['a', 'c', 'r', 'e', 'H', 'k'])

>>> print s.difference({"Rank":1})
set(['a', 'c', 'e', 'H', 'k', 'r'])

>>> s - set("Rank")
set(['H', 'c', 'r', 'e'])

=====Problem Statement=====
Students of District College have a subscription to English and French newspapers. Some students have subscribed to only the English newspaper, some have subscribed to only the French newspaper, and some have subscribed to both newspapers.

You are given two sets of student roll numbers. One set has subscribed to the English newspaper, and one set has subscribed to the French newspaper. Your task is to find the total number of students who have subscribed to only English newspapers.

=====Input Format=====
The first line contains the number of students who have subscribed to the English newspaper.
The second line contains the space separated list of student roll numbers who have subscribed to the English newspaper.
The third line contains the number of students who have subscribed to the French newspaper.
The fourth line contains the space separated list of student roll numbers who have subscribed to the French newspaper.

=====Constraints=====
0<Total number of students in college<1000

=====Output Format=====
Output the total number of students who are subscribed to the English newspaper only.

e = int(input())
eng = set(map(int,input().split()))
f = int(input())
fre = set(map(int,input().split()))
print((len(eng - fre)))


Solve in Python:
=====Function Descriptions=====
.intersection()

The .intersection() operator returns the intersection of a set and the set of elements in an iterable.
Sometimes, the & operator is used in place of the .intersection() operator, but it only operates on the set of elements in set.
The set is immutable to the .intersection() operation (or & operation).

>>> s = set("Hacker")
>>> print s.intersection("Rank")
set(['a', 'k'])

>>> print s.intersection(set(['R', 'a', 'n', 'k']))
set(['a', 'k'])

>>> print s.intersection(['R', 'a', 'n', 'k'])
set(['a', 'k'])

>>> print s.intersection(enumerate(['R', 'a', 'n', 'k']))
set([])

>>> print s.intersection({"Rank":1})
set([])

>>> s & set("Rank")
set(['a', 'k'])

=====Problem Statement=====
The students of District College have subscriptions to English and French newspapers. Some students have subscribed only to English, some have subscribed only to French, and some have subscribed to both newspapers.

You are given two sets of student roll numbers. One set has subscribed to the English newspaper, one set has subscribed to the French newspaper. Your task is to find the total number of students who have subscribed to both newspapers.

=====Input Format=====
The first line contains n, the number of students who have subscribed to the English newspaper.
The second line contains n space separated roll numbers of those students.
The third line contains b, the number of students who have subscribed to the French newspaper.
The fourth line contains b space separated roll numbers of those students.

=====Constraints=====
0 < Total number of students in college < 1000

=====Output Format=====
Output the total number of students who have subscriptions to both English and French newspapers.

e = int(input())
eng = set(map(int,input().split()))
f = int(input())
fre = set(map(int,input().split()))
print((len(eng & fre)))


Solve in Python:
=====Function Descriptions=====
.remove(x)

This operation removes element x from the set.
If element x does not exist, it raises a KeyError.
The .remove(x) operation returns None.

Example

>>> s = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> s.remove(5)
>>> print s
set([1, 2, 3, 4, 6, 7, 8, 9])
>>> print s.remove(4)
None
>>> print s
set([1, 2, 3, 6, 7, 8, 9])
>>> s.remove(0)
KeyError: 0

.discard(x)

This operation also removes element x from the set.
If element x does not exist, it does not raise a KeyError.
The .discard(x) operation returns None.

Example

>>> s = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> s.discard(5)
>>> print s
set([1, 2, 3, 4, 6, 7, 8, 9])
>>> print s.discard(4)
None
>>> print s
set([1, 2, 3, 6, 7, 8, 9])
>>> s.discard(0)
>>> print s
set([1, 2, 3, 6, 7, 8, 9])

.pop()

This operation removes and return an arbitrary element from the set.
If there are no elements to remove, it raises a KeyError.

Example

>>> s = set([1])
>>> print s.pop()
1
>>> print s
set([])
>>> print s.pop()
KeyError: pop from an empty set

=====Problem Statement=====
You have a non-empty set s, and you have to execute N commands given in N lines.
The commands will be pop, remove and discard.

=====Input Format=====
The first line contains integer n, the number of elements in the set s.
The second line contains n space separated elements of set s. All of the elements are non-negative integers, less than or equal to 9.
The third line contains integer N, the number of commands.
The next N lines contains either pop, remove and/or discard commands followed by their associated value.

=====Constraints=====
0 < n < 20
0 < N < 20

=====Output Format====
Print the sum of the elements of set s on a single line.

#!/usr/bin/env python3

def __starting_point():
    n = int(input())
    s = set(map(int, input().split()))
    num_cmds = int(input())

    for _ in range(num_cmds):
        cmd = list(input().strip().split(' '))
        if cmd[0] == 'pop':
            s.pop()
        elif cmd[0] == 'remove':
            s.remove(int(cmd[1]))
        elif cmd[0] == 'discard':
            s.discard(int(cmd[1]))

    print((sum(s)))

__starting_point()


Solve in Python:
=====Function Descriptions=====
.symmetric_difference()

The .symmetric_difference() operator returns a set with all the elements that are in the set and the iterable but not both.
Sometimes, a ^ operator is used in place of the .symmetric_difference() tool, but it only operates on the set of elements in set.
The set is immutable to the .symmetric_difference() operation (or ^ operation).

>>> s = set("Hacker")
>>> print s.symmetric_difference("Rank")
set(['c', 'e', 'H', 'n', 'R', 'r'])

>>> print s.symmetric_difference(set(['R', 'a', 'n', 'k']))
set(['c', 'e', 'H', 'n', 'R', 'r'])

>>> print s.symmetric_difference(['R', 'a', 'n', 'k'])
set(['c', 'e', 'H', 'n', 'R', 'r'])

>>> print s.symmetric_difference(enumerate(['R', 'a', 'n', 'k']))
set(['a', 'c', 'e', 'H', (0, 'R'), 'r', (2, 'n'), 'k', (1, 'a'), (3, 'k')])

>>> print s.symmetric_difference({"Rank":1})
set(['a', 'c', 'e', 'H', 'k', 'Rank', 'r'])

>>> s ^ set("Rank")
set(['c', 'e', 'H', 'n', 'R', 'r'])

=====Problem Statement=====
Students of District College have subscriptions to English and French newspapers. Some students have subscribed to English only, some have subscribed to French only, and some have subscribed to both newspapers.

You are given two sets of student roll numbers. One set has subscribed to the English newspaper, and one set has subscribed to the French newspaper. Your task is to find the total number of students who have subscribed to either the English or the French newspaper but not both.

=====Input Format=====
The first line contains the number of students who have subscribed to the English newspaper.
The second line contains the space separated list of student roll numbers who have subscribed to the English newspaper.
The third line contains the number of students who have subscribed to the French newspaper.
The fourth line contains the space separated list of student roll numbers who have subscribed to the French newspaper.

=====Constraints=====
0 < Total number of students in college < 1000

=====Output Format=====
Output...

e = int(input())
eng = set(map(int,input().split()))
f = int(input())
fre = set(map(int,input().split()))
print((len(eng ^ fre)))


Solve in Python:
=====Function Descriptions=====
.union()

The .union() operator returns the union of a set and the set of elements in an iterable.
Sometimes, the | operator is used in place of .union() operator, but it operates only on the set of elements in set.
Set is immutable to the .union() operation (or | operation).

Example

>>> s = set("Hacker")
>>> print s.union("Rank")
set(['a', 'R', 'c', 'r', 'e', 'H', 'k', 'n'])

>>> print s.union(set(['R', 'a', 'n', 'k']))
set(['a', 'R', 'c', 'r', 'e', 'H', 'k', 'n'])

>>> print s.union(['R', 'a', 'n', 'k'])
set(['a', 'R', 'c', 'r', 'e', 'H', 'k', 'n'])

>>> print s.union(enumerate(['R', 'a', 'n', 'k']))
set(['a', 'c', 'r', 'e', (1, 'a'), (2, 'n'), 'H', 'k', (3, 'k'), (0, 'R')])

>>> print s.union({"Rank":1})
set(['a', 'c', 'r', 'e', 'H', 'k', 'Rank'])

>>> s | set("Rank")
set(['a', 'R', 'c', 'r', 'e', 'H', 'k', 'n'])

=====Problem Statement=====

The students of District College have subscriptions to English and French newspapers. Some students have subscribed only to English, some have subscribed to only French and some have subscribed to both newspapers.

You are given two sets of student roll numbers. One set has subscribed to the English newspaper, and the other set is subscribed to the French newspaper. The same student could be in both sets. Your task is to find the total number of students who have subscribed to at least one newspaper.

=====Input Format=====
The first line contains an integer, n, the number of students who have subscribed to the English newspaper.
The second line contains n space separated roll numbers of those students.
The third line contains b, the number of students who have subscribed to the French newspaper.
The fourth line contains b space separated roll numbers of those students.

=====Constraints=====
0 < Total number of students in college < 1000

=====Output Format=====
Output the total number of students who have at least one subscription.

#!/usr/bin/env python3

def __starting_point():
    n = int(input().strip())
    english = set(map(int, input().strip().split(' ')))
    m = int(input().strip())
    french = set(map(int, input().strip().split(' ')))

    print((len(english.union(french))))

__starting_point()


Solve in Python:
=====Function Descriptions=====
A set is an unordered collection of elements without duplicate entries.
When printed, iterated or converted into a sequence, its elements will appear in an arbitrary order.

=====Example=====
>>> print set()
set([])

>>> print set('HackerRank')
set(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R'])

>>> print set([1,2,1,2,3,4,5,6,0,9,12,22,3])
set([0, 1, 2, 3, 4, 5, 6, 9, 12, 22])

>>> print set((1,2,3,4,5,5))
set([1, 2, 3, 4, 5])

>>> print set(set(['H','a','c','k','e','r','r','a','n','k']))
set(['a', 'c', 'r', 'e', 'H', 'k', 'n'])

>>> print set({'Hacker' : 'DOSHI', 'Rank' : 616 })
set(['Hacker', 'Rank'])

>>> print set(enumerate(['H','a','c','k','e','r','r','a','n','k']))
set([(6, 'r'), (7, 'a'), (3, 'k'), (4, 'e'), (5, 'r'), (9, 'k'), (2, 'c'), (0, 'H'), (1, 'a'), (8, 'n')])

Basically, sets are used for membership testing and eliminating duplicate entries.

=====Problem Statement=====
Now, let's use our knowledge of sets and help Mickey.

Ms. Gabriel Williams is a botany professor at District College. One day, she asked her student Mickey to compute the average of all the plants with distinct heights in her greenhouse.

Formula used:
Average = Sum of Distinct Heights / Total Number of Distinct Heights

=====Input Format=====
The first line contains the integer, N, the total number of plants.
The second line contains the N space separated heights of the plants.

=====Constraints=====
0<N≤100

=====Output Format=====
Output the average height value on a single line.

n = input()
ar = list(map(int,input().split(' ')))
ar=set(ar)
print((sum(ar) / len(ar)))


Solve in Python:
=====Function Descriptions=====
Basic mathematical functions operate element-wise on arrays. They are available both as operator overloads and as functions in the NumPy module.

import numpy

a = numpy.array([1,2,3,4], float)
b = numpy.array([5,6,7,8], float)

print a + b                     #[  6.   8.  10.  12.]
print numpy.add(a, b)           #[  6.   8.  10.  12.]

print a - b                     #[-4. -4. -4. -4.]
print numpy.subtract(a, b)      #[-4. -4. -4. -4.]

print a * b                     #[  5.  12.  21.  32.]
print numpy.multiply(a, b)      #[  5.  12.  21.  32.]

print a / b                     #[ 0.2         0.33333333  0.42857143  0.5       ]
print numpy.divide(a, b)        #[ 0.2         0.33333333  0.42857143  0.5       ]

print a % b                     #[ 1.  2.  3.  4.]
print numpy.mod(a, b)           #[ 1.  2.  3.  4.]

print a**b                      #[  1.00000000e+00   6.40000000e+01   2.18700000e+03   6.55360000e+04]
print numpy.power(a, b)         #[  1.00000000e+00   6.40000000e+01   2.18700000e+03   6.55360000e+04]

=====Problem Statement=====
You are given two integer arrays, A and B of dimensions NXM.
Your task is to perform the following operations:
1. Add (A + B)
2. Subtract (A - B)
3. Multiply (A * B)
4. Integer Division (A / B)
5. Mod (A % B)
6. Power (A ** B)

=====Input Format=====
The first line contains two space separated integers, N and M.
The next N lines contains M space separated integers of array A.
The following N lines contains M space separated integers of array B.

=====Output Format=====
Print the result of each operation in the given order under Task.

import numpy

n, m = [int(x) for x in input().strip().split()]

a = numpy.array([[int(x) for x in input().strip().split()] for _ in range(n)])
b = numpy.array([[int(x) for x in input().strip().split()] for _ in range(n)])

print((a + b))
print((a - b))
print((a * b))
print((a // b))
print((a % b))
print((a**b))


import calendar

def __starting_point():
    date = list(map(int, input().strip().split(' ')))
    print(calendar.day_name[calendar.weekday(date[2], date[0], date[1])].upper())
__starting_point()


Solve in Python:
=====Function Descriptions=====
Concatenate

Two or more arrays can be concatenated together using the concatenate function with a tuple of the arrays to be joined:

import numpy

array_1 = numpy.array([1,2,3])
array_2 = numpy.array([4,5,6])
array_3 = numpy.array([7,8,9])

print numpy.concatenate((array_1, array_2, array_3))

#Output
[1 2 3 4 5 6 7 8 9]

If an array has more than one dimension, it is possible to specify the axis along which multiple arrays are concatenated. By default, it is along the first dimension.

import numpy

array_1 = numpy.array([[1,2,3],[0,0,0]])
array_2 = numpy.array([[0,0,0],[7,8,9]])

print numpy.concatenate((array_1, array_2), axis = 1)

#Output
[[1 2 3 0 0 0]
 [0 0 0 7 8 9]]

=====Problem Statement=====
You are given two integer arrays of size NXP and MXP (N & M are rows, and P is the column). Your task is to concatenate the arrays along axis 0.

=====Input Format=====
The first line contains space separated integers N, M and P .
The next N lines contains the space separated elements of the P columns.
After that, the next M lines contains the space separated elements of the P columns.

=====Output Format=====
Print the concatenated array of size (N + M)XP.

import numpy
n,m,p=list(map(int,input().split()))

ar1 = []
ar2 = []
for i in range(n):
    tmp = list(map(int,input().split()))
    ar1.append(tmp)
for i in range(m):
    tmp = list(map(int,input().split()))
    ar2.append(tmp)
np_ar1 = numpy.array(ar1)
np_ar2 = numpy.array(ar2)
print((numpy.concatenate((np_ar1,np_ar2),axis = 0)))


Solve in Python:
=====Function Descriptions=====
Exceptions
Errors detected during execution are called exceptions.

Examples:
ZeroDivisionError
This error is raised when the second argument of a division or modulo operation is zero.
>>> a = '1'
>>> b = '0'
>>> print int(a) / int(b)
>>> ZeroDivisionError: integer division or modulo by zero

ValueError
This error is raised when a built-in operation or function receives an argument that has the right type but an inappropriate value.
>>> a = '1'
>>> b = '#'
>>> print int(a) / int(b)
>>> ValueError: invalid literal for int() with base 10: '#'

Handling Exceptions
The statements try and except can be used to handle selected exceptions. A try statement may have more than one except clause to specify handlers for different exceptions.

#Code
try:
    print 1/0
except ZeroDivisionError as e:
    print "Error Code:",e
Output

Error Code: integer division or modulo by zero

=====Problem Statement=====
You are given two values a and b.
Perform integer division and print a/b.

=====Input Format=====
The first line contains T, the number of test cases.
The next T lines each contain the space separated values of a and b.

=====Constraints=====
0<T<10

=====Output Format=====
Print the value of a/b.
In the case of ZeroDivisionError or ValueError, print the error code.

n = int(input())
for i in range(n):
    a,b=input().split()
    try:
        print((int(a)//int(b)))
    except Exception as e:
        print(("Error Code: "+str(e)))


Solve in Python:
=====Function Descriptions=====
HTML
Hypertext Markup Language is a standard markup language used for creating World Wide Web pages.

Parsing
Parsing is the process of syntactic analysis of a string of symbols. It involves resolving a string into its component parts and describing their syntactic roles.

HTMLParser
An HTMLParser instance is fed HTML data and calls handler methods when start tags, end tags, text, comments, and other markup elements are encountered.

Example (based on the original Python documentation):

Code

from HTMLParser import HTMLParser

# create a subclass and override the handler methods
class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print "Found a start tag  :", tag
    def handle_endtag(self, tag):
        print "Found an end tag   :", tag
    def handle_startendtag(self, tag, attrs):
        print "Found an empty tag :", tag

# instantiate the parser and fed it some HTML
parser = MyHTMLParser()
parser.feed("<title>HTML Parser - I</title>"
            +"
HackerRank

")

Output

Found a start tag  : html
Found a start tag  : head
Found a start tag  : title
Found an end tag   : title
Found an end tag   : head
Found a start tag  : body
Found a start tag  : h1
Found an end tag   : h1
Found an empty tag : br
Found an end tag   : body
Found an end tag   : html

.handle_starttag(tag, attrs)

This method is called to handle the start tag of an element. (For example:
)
The tag argument is the name of the tag converted to lowercase.
The attrs argument is a list of (name, value) pairs containing the attributes found inside the tag’s <> brackets.

.handle_endtag(tag)

This method is called to handle the end tag of an element. (For example:
)
The tag argument is the name of the tag converted to lowercase.

.handle_startendtag(tag,attrs)

This method is called to handle the empty tag of an element. (For example:
)
The tag argument is the name of the tag converted to lowercase.
The...

import re
from html.parser import HTMLParser

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print("Start".ljust(6) + ":", tag)
        for at in attrs:
            print("-> {} > {}".format(at[0], at[1]))
    def handle_endtag(self, tag):
        print("End".ljust(6) + ":", tag)
    def handle_startendtag(self, tag, attrs):
        print("Empty".ljust(6) + ":", tag)
        for at in attrs:
            print("-> {} > {}".format(at[0], at[1]))

def __starting_point():
    parser = MyHTMLParser()
    n = int(input().strip())
    for _ in range(n):
        line = input()
        parser.feed(line)
__starting_point()


Solve in Python:
=====Function Descriptions=====
If we want to add a single element to an existing set, we can use the .add() operation.
It adds the element to the set and returns 'None'.

=====Example=====
>>> s = set('HackerRank')
>>> s.add('H')
>>> print s
set(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R'])
>>> print s.add('HackerRank')
None
>>> print s
set(['a', 'c', 'e', 'HackerRank', 'H', 'k', 'n', 'r', 'R'])

=====Problem Statement=====
Apply your knowledge of the .add() operation to help your friend Rupal.
Rupal has a huge collection of country stamps. She decided to count the total number of distinct country stamps in her collection. She asked for your help. You pick the stamps one by one from a stack of N country stamps.
Find the total number of distinct country stamps.

=====Input Format=====
The fist line contains an integer N, the total number of country stamps.
The next N lines contains the name of the country where the stamp is from.

=====Constraints=====
0<N<1000

=====Output Format=====
Output the total number of distinct country stamps on a single line.

n = int(input())
country_set = set()
for i in range(n):
    country_name = input()
    country_set.add(country_name)
print((len(country_set)))


Solve in Python:
=====Function Descriptions=====
In Python, a string of text can be aligned left, right and center.

.ljust(width)

This method returns a left aligned string of length width.

>>> width = 20
>>> print 'HackerRank'.ljust(width,'-')
HackerRank----------

.center(width)

This method returns a centered string of length width.

>>> width = 20
>>> print 'HackerRank'.center(width,'-')
-----HackerRank-----

.rjust(width)

This method returns a right aligned string of length width.

>>> width = 20
>>> print 'HackerRank'.rjust(width,'-')
----------HackerRank

=====Problem Statement=====
You are given a partial code that is used for generating the HackerRank Logo of variable thickness.
Your task is to replace the blank (______) with rjust, ljust or center.

=====Input Format=====
A single line containing the thickness value for the logo.

=====Constraints=====
The thickness must be an odd number.
0 < thickness < 50

=====Output Format=====
Output the desired logo.

#Replace all ______ with rjust, ljust or center.

thickness = int(input()) #This must be an odd number
c = 'H'

#Top Cone
for i in range(thickness):
    print(((c*i).rjust(thickness-1)+c+(c*i).ljust(thickness-1)))

#Top Pillars
for i in range(thickness+1):
    print(((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6)))

#Middle Belt
for i in range((thickness+1)//2):
    print(((c*thickness*5).center(thickness*6)))

#Bottom Pillars
for i in range(thickness+1):
    print(((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6)))

#Bottom Cone
for i in range(thickness):
    print((((c*(thickness-i-1)).rjust(thickness)+c+(c*(thickness-i-1)).ljust(thickness)).rjust(thickness*6)))


Solve in Python:
=====Function Descriptions=====
One of the built-in functions of Python is divmod, which takes two arguments a and b and returns a tuple containing the quotient of first and then the remainder.

=====Problem Statement=====
For example:
>>> print divmod(177,10)
(17, 7)

Here, the integer division is 177/10 => 17 and the modulo operator is 177%10 => 7.

Task
Read in two integers, a and b, and print three lines.
The first line is the integer division a//b (While using Python2 remember to import division from __future__).
The second line is the result of the modulo operator: a%b.
The third line prints the divmod of a and b.

=====Input Format=====
The first line contains the first integer, a, and the second line contains the second integer, b.

=====Output Format=====
Print the result as described above.

# Enter your code here. Read input from STDIN. Print output to STDOUT
a=int(input())
b=int(input())
d=divmod(a,b)
print((d[0]))
print((d[1]))
print(d)


Solve in Python:
=====Function Descriptions=====
Polar coordinates are an alternative way of representing Cartesian coordinates or Complex Numbers.
A complex number z
z = x + yj
is completely determined by its real part y. Here, j is the imaginary unit.

A polar coordinate (r, φ) is completely determined by modulus r and phase angle φ.
If we convert complex number z to its polar coordinate, we find:
r: Distance from z to origin, i.e., sqrt(x^2 + y^2)
φ: Counter clockwise angle measured from the positive -axis to the line segment that joins z to the origin.

Python's cmath module provides access to the mathematical functions for complex numbers.
cmath.phase
This tool returns the phase of complex number z (also known as the argument of z).
>>> phase(complex(-1.0, 0.0))
3.1415926535897931

abs
This tool returns the modulus (absolute value) of complex number z.
>>> abs(complex(-1.0, 0.0))
1.0

=====Problem Statement=====
You are given a complex z. Your task is to convert it to polar coordinates.

=====Input Format=====
A single line containing the complex number z. Note: complex() function can be used in python to convert the input as a complex number.

=====Constraints=====
Given number is a valid complex number

=====Output Format=====
Output two lines:
The first line should contain the value of r.
The second line should contain the value of φ.

import cmath
z = complex(input())
p = cmath.polar(z)
print((p[0]))
print((p[1]))


Solve in Python:
=====Function Descriptions=====
Python has built-in string validation methods for basic data. It can check if a string is composed of alphabetical characters, alphanumeric characters, digits, etc.

str.isalnum()
This method checks if all the characters of a string are alphanumeric (a-z, A-Z and 0-9).

>>> print 'ab123'.isalnum()
True
>>> print 'ab123#'.isalnum()
False

str.isalpha()
This method checks if all the characters of a string are alphabetical (a-z and A-Z).

>>> print 'abcD'.isalpha()
True
>>> print 'abcd1'.isalpha()
False

str.isdigit()
This method checks if all the characters of a string are digits (0-9).

>>> print '1234'.isdigit()
True
>>> print '123edsd'.isdigit()
False

str.islower()
This method checks if all the characters of a string are lowercase characters (a-z).

>>> print 'abcd123#'.islower()
True
>>> print 'Abcd123#'.islower()
False

str.isupper()
This method checks if all the characters of a string are uppercase characters (A-Z).

>>> print 'ABCD123#'.isupper()
True
>>> print 'Abcd123#'.isupper()
False

=====Problem Statement=====
You are given a string S.
Your task is to find out if the string S contains: alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters.

=====Input Format=====
A single line containing a string S.

=====Constraints=====
0 < len(S) < 1000

=====Output Format=====
In the first line, print True if S has any alphanumeric characters. Otherwise, print False.
In the second line, print True if S has any alphabetical characters. Otherwise, print False.
In the third line, print True if S has any digits. Otherwise, print False.
In the fourth line, print True if S has any lowercase characters. Otherwise, print False.
In the fifth line, print True if S has any uppercase characters. Otherwise, print False.

# Enter your code here. Read input from STDIN. Print output to STDOUT
inputStr=input()
resalnum = False
resalpha = False
resdigit = False
reslower = False
resupper = False
for i in inputStr:
    if(i.isalnum()):
        resalnum=True
    if(i.isalpha()):
        resalpha=True
    if(i.isdigit()):
        resdigit=True
    if(i.islower()):
        reslower=True
    if(i.isupper()):
        resupper=True

print(resalnum)
print(resalpha)
print(resdigit)
print(reslower)
print(resupper)


Solve in Python:
=====Function Descriptions=====
So far, we have only heard of Python's powers. Now, we will witness them!

Powers or exponents in Python can be calculated using the built-in power function. Call the power function a^b as shown below:
>>> pow(a,b)

or

>>> a**b

It's also possible to calculate a^b mod m.
>>> pow(a,b,m)

This is very helpful in computations where you have to print the resultant % mod.

Note: Here, a and b can be floats or negatives, but, if a third argument is present, b cannot be negative.

Note: Python has a math module that has its own pow(). It takes two arguments and returns a float. Frankly speaking, we will never use math.pow().

=====Problem Statement=====
You are given three integers: a, b, and m, respectively. Print two lines.
The first line should print the result of pow(a,b). The second line should print the result of pow(a,b,m).

=====Input Format=====
The first line contains a, the second line contains b, and the third line contains m.

=====Constraints=====
1≤a≤10
1≤b≤10
2≤m≤1000

# Enter your code here. Read input from STDIN. Print output to STDOUT
a=int(input())
b=int(input())
c=int(input())
print((pow(a,b)))
print((pow(a,b,c)))


Solve in Python:
=====Function Descriptions=====
The NumPy (Numeric Python) package helps us manipulate large arrays and matrices of numeric data.

To use the NumPy module, we need to import it using:

import numpy

Arrays

A NumPy array is a grid of values. They are similar to lists, except that every element of an array must be the same type.

import numpy

a = numpy.array([1,2,3,4,5])
print a[1]          #2

b = numpy.array([1,2,3,4,5],float)
print b[1]          #2.0

In the above example, numpy.array() is used to convert a list into a NumPy array. The second argument (float) can be used to set the type of array elements.

=====Problem Statement=====
You are given a space separated list of numbers.
Your task is to print a reversed NumPy array with the element type float.

=====Input Format=====
A single line of input containing space separated numbers.

=====Output Format=====
Print the reverse NumPy array with type float.

import numpy
ar = list(map(float,input().split()))
np_ar = numpy.array(ar,float)
print((np_ar[::-1]))


Solve in Python:
=====Function Descriptions=====
The NumPy module also comes with a number of built-in routines for linear algebra calculations. These can be found in the sub-module linalg.

linalg.det

The linalg.det tool computes the determinant of an array.

print numpy.linalg.det([[1 , 2], [2, 1]])       #Output : -3.0

linalg.eig

The linalg.eig computes the eigenvalues and right eigenvectors of a square array.

vals, vecs = numpy.linalg.eig([[1 , 2], [2, 1]])
print vals                                      #Output : [ 3. -1.]
print vecs                                      #Output : [[ 0.70710678 -0.70710678]
                                                #          [ 0.70710678  0.70710678]]

linalg.inv

The linalg.inv tool computes the (multiplicative) inverse of a matrix.

print numpy.linalg.inv([[1 , 2], [2, 1]])       #Output : [[-0.33333333  0.66666667]
                                                #          [ 0.66666667 -0.33333333]]

=====Problem Statement=====
You are given a square matrix A with dimensions NXN. Your task is to find the determinant. Note: Round the answer to 2 places after the decimal.

=====Input Format=====
The first line contains the integer N.
The next N lines contains the space separated elements of array A.

=====Output Format=====
Print the determinant of A.

import numpy
n = int(input())
ar = []
for i in range(n):
    tmp = list(map(float,input().split()))
    ar.append(tmp)
np_ar = numpy.array(ar,float)
print((numpy.linalg.det(np_ar)))


Solve in Python:
=====Function Descriptions=====
The eval() expression is a very powerful built-in function of Python. It helps in evaluating an expression. The expression can be a Python statement, or a code object.

For example:
>>> eval("9 + 5")
14
>>> x = 2
>>> eval("x + 3")
5

Here, eval() can also be used to work with Python keywords or defined functions and variables. These would normally be stored as strings.

For example:
>>> type(eval("len"))
<type 'builtin_function_or_method'>

Without eval()
>>> type("len")
<type 'str'>

=====Problem Statement=====
You are given an expression in a line. Read that line as a string variable, such as var, and print the result using eval(var).
NOTE: Python2 users, please import from __future__ import print_function.

=====Constraints=====
Input string is less than 100 characters.


Solve in Python:
=====Function Descriptions=====
Transpose

We can generate the transposition of an array using the tool numpy.transpose.
It will not affect the original array, but it will create a new array.

import numpy

my_array = numpy.array([[1,2,3],
                        [4,5,6]])
print numpy.transpose(my_array)

#Output
[[1 4]
 [2 5]
 [3 6]]

Flatten

The tool flatten creates a copy of the input array flattened to one dimension.

import numpy

my_array = numpy.array([[1,2,3],
                        [4,5,6]])
print my_array.flatten()

#Output
[1 2 3 4 5 6]

=====Problem Statement=====
You are given a NXM integer array matrix with space separated elements (N = rows and M = columns).
Your task is to print the transpose and flatten results.

=====Input Format=====
The first line contains the space separated values of N and M.
The next N lines contains the space separated elements of M columns.

=====Output Format=====
First, print the transpose array and then print the flatten.

import numpy
n, m = [int(x) for x in input().strip().split()]
arr = []
for _ in range(n):
    arr.append([int(x) for x in input().strip().split()])
print(numpy.array(arr).transpose())
print(numpy.array(arr).flatten())