Solve in Python:
A penguin Rocher has $n$ sticks. He has exactly one stick with length $i$ for all $1 \le i \le n$.

He can connect some sticks. If he connects two sticks that have lengths $a$ and $b$, he gets one stick with length $a + b$. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his set and can be used for the next connections.

He wants to create the maximum number of sticks that have the same length. It is not necessary to make all sticks have the same length, some sticks can have the other length. How many sticks with the equal length he can create?

-----Input-----

The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases. Next $t$ lines contain descriptions of test cases.

For each test case, the only line contains a single integer $n$ ($1 \le n \le 10^{9}$).

-----Output-----

For each test case, print a single integer  — the answer to the problem.

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

Output
1
1
2
2

-----Note-----

In the third case, he can connect two sticks with lengths $1$ and $2$ and he will get one stick with length $3$. So, he will have two sticks with lengths $3$.

In the fourth case, he can connect two sticks with lengths $1$ and $3$ and he will get one stick with length $4$. After that, he will have three sticks with lengths $\{2, 4, 4\}$, so two sticks have the same length, and one stick has the other length.

import sys
input = lambda :sys.stdin.readline().rstrip()
for _ in range(int(input())):
	n=int(input())
	print(n//2 + (1 if n%2 else 0))


Solve in Python:
A permutation $p_1,p_2...p_N$ of $\{1, 2, ..., N\}$ is beautiful if $p_i \& p_{i+1}$ is greater than 0 for every $1 \leq i < N$ . You are given an integer $N$, and your task is toconstruct a beautiful permutation of length $N$ or determine that it's impossible.
Note that $a \& b$ denotes the bitwise AND of $a$ and $b$.

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

-----Output:-----
For each test case output $-1$ if there is no suitable permutation of length $N$, otherwise output $N$ integers in a single line which form a beautiful permutation. If there are multiple answers output any of them.

-----Constraints-----
- $1 \leq N \leq 10^5$
- The sum of $N$ over all test cases does not exceed $10^6$

-----Subtasks-----
- 50 points : $1 \leq N,T \leq 9$
- 50 points : Original constraints

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

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

# cook your dish here
import math
for x in range(int(input())):
 N=int(input())
 permutations=list()
 l=6
 m=3
 a=2**m
 if (N!=1 and math.ceil(math.log(N,2)))==math.floor(math.log(N,2)):
  print('-1')
  continue
 elif N==1:
  print('1')
 elif(N==3):
  print("2 3 1")
 elif(N==5):
  print("2 3 1 5 4")
 if(N>5):
  print("2 3 1 5 4",end=' ')
  while(l<=N):
   if(l==a):
    m=m+1
    a=2**m
    print(l+1,end=" ")
    print(l,end=" ")
    l=l+2
   else:
    print(l,end=" ")
    l=l+1
   print(' ')


Solve in Python:
A permutation of length $n$ is a sequence of integers from $1$ to $n$ of length $n$ containing each number exactly once. For example, $[1]$, $[4, 3, 5, 1, 2]$, $[3, 2, 1]$ are permutations, and $[1, 1]$, $[0, 1]$, $[2, 2, 1, 4]$ are not.

There was a permutation $p[1 \dots n]$. It was merged with itself. In other words, let's take two instances of $p$ and insert elements of the second $p$ into the first maintaining relative order of elements. The result is a sequence of the length $2n$.

For example, if $p=[3, 1, 2]$ some possible results are: $[3, 1, 2, 3, 1, 2]$, $[3, 3, 1, 1, 2, 2]$, $[3, 1, 3, 1, 2, 2]$. The following sequences are not possible results of a merging: $[1, 3, 2, 1, 2, 3$], [$3, 1, 2, 3, 2, 1]$, $[3, 3, 1, 2, 2, 1]$.

For example, if $p=[2, 1]$ the possible results are: $[2, 2, 1, 1]$, $[2, 1, 2, 1]$. The following sequences are not possible results of a merging: $[1, 1, 2, 2$], [$2, 1, 1, 2]$, $[1, 2, 2, 1]$.

Your task is to restore the permutation $p$ by the given resulting sequence $a$. It is guaranteed that the answer exists and is unique.

You have to answer $t$ independent test cases.

-----Input-----

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

The first line of the test case contains one integer $n$ ($1 \le n \le 50$) — the length of permutation. The second line of the test case contains $2n$ integers $a_1, a_2, \dots, a_{2n}$ ($1 \le a_i \le n$), where $a_i$ is the $i$-th element of $a$. It is guaranteed that the array $a$ represents the result of merging of some permutation $p$ with the same permutation $p$.

-----Output-----

For each test case, print the answer: $n$ integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$), representing the initial permutation. It is guaranteed that the answer exists and is unique.

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

Output
1 2
1 3 4 2
1 2 3 4 5
1 2 3
2 3 4 1

def solve():
    n = int(input())
    a = list(map(int, input().split()))
    vis = [False] * (n + 1)
    p = []
    for i in a:
        if vis[i]:
            continue
        vis[i] = True
        p.append(i)
    print(*p)

t = int(input())
for _ in range(t):
    solve()


Solve in Python:
A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).

Let $p$ be any permutation of length $n$. We define the fingerprint $F(p)$ of $p$ as the sorted array of sums of adjacent elements in $p$. More formally,

$$F(p)=\mathrm{sort}([p_1+p_2,p_2+p_3,\ldots,p_{n-1}+p_n]).$$

For example, if $n=4$ and $p=[1,4,2,3],$ then the fingerprint is given by $F(p)=\mathrm{sort}([1+4,4+2,2+3])=\mathrm{sort}([5,6,5])=[5,5,6]$.

You are given a permutation $p$ of length $n$. Your task is to find a different permutation $p'$ with the same fingerprint. Two permutations $p$ and $p'$ are considered different if there is some index $i$ such that $p_i \ne p'_i$.

-----Input-----

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

The first line of each test case contains a single integer $n$ ($2\le n\le 100$)  — the length of the permutation.

The second line of each test case contains $n$ integers $p_1,\ldots,p_n$ ($1\le p_i\le n$). It is guaranteed that $p$ is a permutation.

-----Output-----

For each test case, output $n$ integers $p'_1,\ldots, p'_n$ — a permutation such that $p'\ne p$ and $F(p')=F(p)$.

We can prove that for every permutation satisfying the input constraints, a solution exists.

If there are multiple solutions, you may output any.

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

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

-----Note-----

In the first test case, $F(p)=\mathrm{sort}([1+2])=[3]$.

And $F(p')=\mathrm{sort}([2+1])=[3]$.

In the second test case, $F(p)=\mathrm{sort}([2+1,1+6,6+5,5+4,4+3])=\mathrm{sort}([3,7,11,9,7])=[3,7,7,9,11]$.

And $F(p')=\mathrm{sort}([1+2,2+5,5+6,6+3,3+4])=\mathrm{sort}([3,7,11,9,7])=[3,7,7,9,11]$.

In the third test case,...

for T in range(int(input())) :
    n = int(input())
    l = input().split()
    print(*l[::-1])


Solve in Python:
A permutation of length n is an array of size n consisting of n distinct integers in the range [1, n]. For example, (3, 2, 4, 1) is a permutation of length 4, but (3, 3, 1, 4) and (2, 3, 4, 5) are not, as (3, 3, 1, 4) contains duplicate elements, and (2, 3, 4, 5) contains elements not in range [1,4].
A permutation p of length n is good if and only if for any 1 ≤ i ≤ n, pi ≠ i.
Please find the lexicographically smallest good permutation p.
Definition for "lexicographically smaller":
For two permutations p and q, we say that p is lexicographically smaller than q if and only if there exists a index 1 ≤ l ≤ n such that:
- For any 1 ≤ i < l, pi = qi. Note that if l = 1, this constraint means nothing.
- and, pl < ql.

For example, (2, 3, 1, 4) < (2, 3, 4, 1) < (3, 4, 1, 2). The lexicographically smallest permutation is, of course, (1, 2, ..., n), though this one is not good.

-----Input-----
First line of the input contains an integer T denoting number of test cases.
For each test case, the only line contains an integer n.

-----Output-----
For each test case, output the lexicographically smallest good permutation of length n. It's guaranteed that this permutation exists.

-----Constraints-----
- 1 ≤ T ≤ 10
- 2 ≤ n ≤ 105

-----Subtasks-----
- Subtask #1 (17 points): 2 ≤ n ≤ 9
- Subtask #2 (83 points): Original Constraints

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

Output:
2 1
2 3 1
2 1 4 5 3
2 1 4 3 6 5

-----Explanation-----
Example case 1. The only good permutation of length 2 is (2, 1).
Example case 2. Consider all permutations of length 3, they are(in lexicographically order):
- p = (1, 2, 3), it's not good since p[1] = 1, p[2] = 2 and p[3] = 3;
- p = (1, 3, 2), it's not good since p[1] = 1;
- p = (2, 1, 3), it's not good since p[3] = 3;
- p = (2, 3, 1), it's good since p[1] ≠ 1, p[2] ≠ 2 and p[3] ≠ 3;
- p = (3, 1, 2), it's good since p[1] ≠ 1, p[2] ≠ 2 and p[3] ≠ 3;
- p = (3, 2, 1), it's not good since p[2] = 2.
Thus the minimum good one is (2, 3, 1).
Example case 3. Consider two good permutations for third test...

# cook your dish here
for _ in range(int(input())):

    n=int(input())

    if n%2==0:

        ans=[]
        for i in range(1,n+1,2):
            ans.append(i+1)
            ans.append(i)

    else:

        ans=[]

        for i in range(1,n+1-3,2):
            ans.append(i+1)
            ans.append(i)

        ans.extend([n-1,n,n-2])

    print(*ans)


Solve in Python:
A permutation p of size n is the sequence p_1, p_2, ..., p_{n}, consisting of n distinct integers, each of them is from 1 to n (1 ≤ p_{i} ≤ n).

A lucky permutation is such permutation p, that any integer i (1 ≤ i ≤ n) meets this condition p_{p}_{i} = n - i + 1.

You have integer n. Find some lucky permutation p of size n.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^5) — the required permutation size.

-----Output-----

Print "-1" (without the quotes) if the lucky permutation p of size n doesn't exist.

Otherwise, print n distinct integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ n) after a space — the required permutation.

If there are multiple answers, you can print any of them.

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

Output
1

Input
2

Output
-1

Input
4

Output
2 4 1 3

Input
5

Output
2 5 3 1 4


Solve in Python:
A pixmap shall be turned from black to white, turning all pixels to white in the process.  But for optical reasons this shall *not* happen linearly, starting at the top and continuing line by line to the bottom:

```python
for y in range(height):
  for x in range(width):
     setBit(x, y)
```

Instead it shall be done by a systematic dithering routine which selects the coordinates on which pixels are to be set in a precise pattern so that the geometrical distance between two consecutive pixels is large and a specific optical effect results.

The following diagrams show the order of the coordinates the algorithm shall produce:

2×2:
```
1 3
4 2
```
4×4:
```
 1  9  3 11
13  5 15  7
 4 12  2 10
16  8 14  6
```
8×8:
```
 1  33   9  41   3  35  11  43
49  17  57  25  51  19  59  27
13  45   5  37  15  47   7  39
61  29  53  21  63  31  55  23
 4  36  12  44   2  34  10  42
52  20  60  28  50  18  58  26
16  48   8  40  14  46   6  38
64  32  56  24  62  30  54  22
```
The pattern continues like that for each square pixmap with a width and height of a power of two (16, 32, 64, …).

But the width and the height of the pixmap can be arbitrary positive numbers.  If the pixmap's width and/or height are not a power of two, the coordinates the algorithm  would produce outside of the pixmap are skipped:

3×3:
```
1 6 3
8 5 9
4 7 2
```
6×5:
```
 1 16  6 21  3 18
25 10 28 13 26 11
 8 23  5 20  9 24
29 14 27 12 30 15
 4 19  7 22  2 17
```
Write an algorithm which produces the coordinates of the dithering for a given width and height.

To pass the Python test cases, write a *generator* ```dithering()``` which yields coordinate tuples:
```python
g = dithering(6, 5)
for i in range(7):
  print g.next()
```
Will print:
```
(0, 0)
(4, 4)
(4, 0)
(0, 4)
(2, 2)
(2, 0)
(2, 4)
```

def dithering(width, height):
    size =  1
    while width > size or height > size:
        size *= 2
    if size == 1:
        yield (0,0)
    else:
        for (x, y) in  dithering(size/2, size/2):
            for t in ((x,y), (x+size/2, y+size/2), (x+size/2, y), (x, y+size/2)):
                if t[0] < width and t[1] < height:
                    yield t


Solve in Python:
A plot of land can be described by $M x N$ dots such that horizontal and vertical distance between any two dots is 10m.
Mr. Wolf would like to build a house in the land such that all four sides of the house are equal. Help Mr. Wolf to find the total number of unique positions where houses can be built. Two positions are different if and only if their sets of four dots are different.

-----Input:-----
The first line of the input gives the number of test cases, $T$. $T$ lines follow. Each line has two integers $M$ and $N$: the number of dots in each row and column of the plot, respectively.

-----Output:-----
For each test case, output one single integer containing the total number of different positions where the house can be built.

-----Constraints-----
- $1 \leq T \leq 100$
- $2 \leq M \leq 10^9$
- $2 \leq N \leq 10^9$

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

2 4

3 4

4 4

1000 500

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

10

20

624937395

-----EXPLANATION:-----
Map 1

Map 2

Map 3

# cook your dish here
from sys import stdin,stdout,setrecursionlimit
from math import ceil

mod = 1000000007
t = int(stdin.readline())
for _ in range(t):
    m,n = list(map(int,input().split()))
    if m < n:
        m,n = n,m

    y = n-1
    s1 = ((y*(y+1)) //2)%mod
    s2 = ((y*(y+1)*(2*y+1)) //6)%mod
    s3 = ((y*y*(y+1)*(y+1)) //4)%mod

    ans = (m*n*s1 - (m+n)*s2+s3)%mod
    # ans = (m*(m+1)*(2*m*n + 4*n + 2 - m*m - m)//12)

    print(ans)


Solve in Python:
A policeman wants to catch a thief. Both the policeman and the thief can only move on a line on integer coordinates between $0$ and $N$ (inclusive).
Initially, the policeman is at a coordinate $x$ and the thief is at a coordinate $y$. During each second, each of them must move to the left or right (not necessarily both in the same direction) by distance $\textbf{exactly}$ equal to $K$. No one may go to the left of the coordinate $0$ or to the right of $N$. Both the policeman and the thief move simultaneously and they cannot meet while moving, only at the end of each second.
Will the policeman be able to catch the thief if they both move optimally? The thief is caught as soon as the policeman and thief meet at the same position at the same time.

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

-----Output-----
For each test case, print a single line containing the string "Yes" if the thief can be caught or "No" if the thief cannot be caught (without quotes).

-----Constraints-----
- $1 \le T \le 1,000$
- $1 \le N \le 10^9$
- $1 \le K \le N$
- $0 \le x, y \le N$
- $x \neq y$

-----Example Input-----
5
0 1 1 1
1 4 1 5
4 2 1 7
3 7 2 10
8 2 3 15

-----Example Output-----
No
No
Yes
Yes
Yes

-----Explanation-----
Example case 1: The policeman is at $0$ and the thief is at $1$. After the $1$-st second, the policeman is at $1$ and the thief is at $0$. After the next second, the policeman is again at $0$ and the thief at $1$. They cannot end up at the same coordinate.

# cook your dish here

for TC in range(int(input())):
 x,y,k,n = list(map(int,input().split()))

 if abs(x-y)%(2*k)!=0:
  print('No')
 else:
  print('Yes')


Solve in Python:
A population of bears consists of black bears, brown bears, and white bears.

The input is an array of two elements.

Determine whether the offspring of the two bears will return `'black'`, `'brown'`, `'white'`, `'dark brown'`, `'grey'`, `'light brown'`, or `'unknown'`.

Elements in the the array will always be a string.

## Examples:

    bear_fur(['black', 'black'])  returns 'black'

    bear_fur(['brown', 'brown'])  returns 'brown'

    bear_fur(['white', 'white'])  returns 'white'

    bear_fur(['black', 'brown'])  returns 'dark brown'

    bear_fur(['black', 'white'])  returns 'grey'

    bear_fur(['brown', 'white'])  returns 'light brown'

    bear_fur(['yellow', 'magenta'])  returns 'unknown'

def bear_fur(bears):
    return  {('black', 'black') : 'black',
             ('black', 'white') : 'grey',
             ('black', 'brown') : 'dark brown',
             ('brown', 'brown') : 'brown',
             ('brown', 'white') : 'light brown',
             ('white', 'white') : 'white'
            }.get(tuple(sorted(bears)), 'unknown')


Solve in Python:
A positive integer is magical if it is divisible by either A or B.
Return the N-th magical number.  Since the answer may be very large, return it modulo 10^9 + 7.

Example 1:
Input: N = 1, A = 2, B = 3
Output: 2

Example 2:
Input: N = 4, A = 2, B = 3
Output: 6

Example 3:
Input: N = 5, A = 2, B = 4
Output: 10

Example 4:
Input: N = 3, A = 6, B = 4
Output: 8

Note:

1 <= N <= 10^9
2 <= A <= 40000
2 <= B <= 40000

class Solution:
    def _lcm(self, a, b):
        return a * b // math.gcd(a, b)

    def _nth_magical_number_slow(self, n: int, a: int, b: int) -> int:
        if n == 0:
            return 0
        else:
            i, j = a, b
            count = 1
            while count < n:
                if i <= j:
                    i = i + a
                else:
                    j = j + b

                if i == j:
                    if a < b:
                        i = i + a
                    else:
                        j = j + b

                count += 1

            return min(i, j) % 1000000007

    def nthMagicalNumber(self, n: int, a_orig: int, b_orig: int) -> int:
        a, b = min(a_orig, b_orig), max(a_orig, b_orig)
        if a == b:
            return a * n % 1000000007
        else:
            lcm = self._lcm(a, b)
            k = lcm // a + lcm // b - 1
            return ((n // k) * lcm + self._nth_magical_number_slow(n % k, a, b)) % 1000000007


Solve in Python:
A prime number is number x which has only divisors as 1 and x itself.
Harsh is playing a game with his friends, where his friends give him a few numbers claiming that they are divisors of some number x but divisor 1 and the number x itself are not being given as divisors.
You need to help harsh find which number's divisors are given here.
His friends can also give him wrong set of divisors as a trick question for which no number exists.
Simply, We are given the divisors of a number x ( divisors except 1 and x itself ) , you have to print the number if only it is possible.
You have to answer t queries.
(USE LONG LONG TO PREVENT OVERFLOW)

-----Input:-----
- First line is T queires.
- Next are T queries.
- First line is N ( No of divisors except 1 and the number itself )
- Next line has N integers or basically the divisors.

-----Output:-----
Print the minimum possible x which has such divisors and print -1 if not possible.

-----Constraints-----
- 1<= T <= 30
- 1<= N <= 350
- 2<= Di <=10^6

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

-----Sample Output:-----
6
8
-1

-----EXPLANATION:-----
Query 1 : Divisors of 6 are ( 1,2,3,6) Therefore, Divisors except 1 and the number 6 itself are ( 2 , 3). Thus, ans = 6.
Query 2 : Divisors of 8 are ( 1,2,4,8) Therefore, Divisors except 1 and the number 8 itself are ( 2 , 4). Thus, ans = 8.
Query 3 : There is no such number x with only ( 1,2,3,12,x ) as the divisors.

import math

def factorialToNum(N, n):
	N.sort()
	t = N[0]*N[n-1]
	L = []
	i = 2

	while(i * i <= t):
		if(t % i == 0):
			L.append(i)
			if ((t//i) != i):
				L.append(t//i)
		i += 1

	L.sort()

	if(len(L) != n):
		return -1
	else:
		j = 0
		for it in range(n):
			if(N[j] != L[it]):
				return -1
			else:
				j += 1
	return t

t = int(input())

for _ in range(t):
    n = int(input())
    N = list(map(int, input().strip().split(' ')))
    print(factorialToNum(N, n))


Solve in Python:
A printer – who still uses moveable type – is preparing to print a set of pages for a book. These pages are to be numbered, as usual. The printer needs to know how many instances of each decimal digit will be required to set up the page numbers in the section of the book to be printed.

For example, if pages 10, 11, 12, 13, 14 and 15 are to be printed, computing the number of digits is relatively simple: just look at the page numbers that will appear, and count the number of times each digit appears. The digit 0 appears only once, the digit 1 appears 7 times, the digits 2, 3, 4 and 5 each appear once, and 6, 7, 8 and 9 don’t appear at all.

Your task in this problem is to provide the printer with the appropriate counts of the digits. You will be given the numbers of the two pages that identify the section of the book to be printed. You may safely assume that all pages in that section are to be numbered, that no leading zeroes will be printed, that page numbers are positive, and that no page will have more than three digits in its page number.

-----Input-----

There will be multiple cases to consider. The input for each case has two integers, A and B, each of which is guaranteed to be positive. These identify the pages to be printed. That is, each integer P between A and B, including A and B, is to be printed. A single zero will follow the input for the last case.

-----Output-----

For each input case, display the case number (1, 2, …) and the number of occurrences of each decimal digit 0 through 9 in the specified range of page numbers. Display your results in the format shown in the examples below.

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

10 15
912 912
900 999
0

Output:

Case 1: 0:1 1:7 2:1 3:1 4:1 5:1 6:0 7:0 8:0 9:0
Case 2: 0:0 1:1 2:1 3:0 4:0 5:0 6:0 7:0 8:0 9:1
Case 3: 0:20 1:20 2:20 3:20 4:20 5:20 6:20 7:20 8:20 9:120

import sys
def main():
    case=1
    while True:
        try:
            m, n = list(map(int, sys.stdin.readline().split()))
            if m>n:
                m,n=n,m
            r=[str(num) for num in range(m, n+1)]
            s=''.join(r)
            d={}
            for number in s:
                if number not in d:
                    d[number]=1
                else: d[number]+=1
            for q in range(10):
                if str(q) not in d:
                        d[str(q)]=0
            print("Case "+str(case)+": "+"0:"+str(d['0'])+" "+"1:"+str(d['1'])+" "+"2:"+str(d['2'])+" "+"3:"+str(d['3'])+" "+"4:"+str(d['4'])+" "+"5:"+str(d['5'])+" "+"6:"+str(d['6'])+" "+"7:"+str(d['7'])+" "+"8:"+str(d['8'])+" "+"9:"+str(d['9']))
            case+=1
        except:
            break
def __starting_point():
    main()

__starting_point()


Solve in Python:
A product-sum number is a natural number N which can be expressed as both the product and the sum of the same set of numbers.

N = a1 × a2 × ... × ak = a1 + a2 + ... + ak

For example, 6 = 1 × 2 × 3 = 1 + 2 + 3.

For a given set of size, k, we shall call the smallest N with this property a minimal product-sum number. The minimal product-sum numbers for sets of size, k = 2, 3, 4, 5, and 6 are as follows.
```
k=2: 4 = 2 × 2 = 2 + 2
k=3: 6 = 1 × 2 × 3 = 1 + 2 + 3
k=4: 8 = 1 × 1 × 2 × 4 = 1 + 1 + 2 + 4
k=5: 8 = 1 × 1 × 2 × 2 × 2 = 1 + 1 + 2 + 2 + 2
k=6: 12 = 1 × 1 × 1 × 1 × 2 × 6 = 1 + 1 + 1 + 1 + 2 + 6
```

Hence for 2 ≤ k ≤ 6, the sum of all the minimal product-sum numbers is 4+6+8+12 = 30; note that 8 is only counted once in the sum.

Your task is to write an algorithm to compute the sum of all minimal product-sum numbers where 2 ≤ k ≤ n.

Courtesy of ProjectEuler.net

maxi = 12001
res = [2*maxi]*maxi
def rec(p, s, c, x):
    k = p - s + c
    if k >= maxi: return
    res[k] = min(p, res[k])
    [rec(p*i, s+i, c+1, i) for i in range(x, 2*maxi//p + 1)]
rec(1, 1, 1, 2)

def productsum(n):
    return sum(set(res[2:n+1]))


Solve in Python:
A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits and all we know is that all integers in the array were in the range [1, k] and there are no leading zeros in the array.
Given the string s and the integer k. There can be multiple ways to restore the array.
Return the number of possible array that can be printed as a string s using the mentioned program.
The number of ways could be very large so return it modulo 10^9 + 7

Example 1:
Input: s = "1000", k = 10000
Output: 1
Explanation: The only possible array is [1000]

Example 2:
Input: s = "1000", k = 10
Output: 0
Explanation: There cannot be an array that was printed this way and has all integer >= 1 and <= 10.

Example 3:
Input: s = "1317", k = 2000
Output: 8
Explanation: Possible arrays are [1317],[131,7],[13,17],[1,317],[13,1,7],[1,31,7],[1,3,17],[1,3,1,7]

Example 4:
Input: s = "2020", k = 30
Output: 1
Explanation: The only possible array is [20,20]. [2020] is invalid because 2020 > 30. [2,020] is ivalid because 020 contains leading zeros.

Example 5:
Input: s = "1234567890", k = 90
Output: 34

Constraints:

1 <= s.length <= 10^5.
s consists of only digits and doesn't contain leading zeros.
1 <= k <= 10^9.

class Solution:
    def numberOfArrays(self, s: str, k: int) -> int:
        dp = [-1] * len(s)
        return self.dfs(s, k, 0, dp)

    def dfs(self, s: str, k: int, start: int, dp: List[int]) -> int:
        if start == len(s):
            return 1
        if s[start] == '0':
            return 0
        if dp[start] != -1:
            return dp[start]

        res, num = 0, 0

        for i in range(start, len(s)):
            num = num * 10 + (ord(s[i]) - ord('0'))

            if num > k:
                break

            res += self.dfs(s, k, i + 1, dp)
            res %= 10**9 + 7

        dp[start] = res
        return res


Solve in Python:
A rectangle can be split up into a grid of 1x1 squares, the amount of which being equal to the product of the two dimensions of the rectangle. Depending on the size of the rectangle, that grid of 1x1 squares can also be split up into larger squares, for example a 3x2 rectangle has a total of 8 squares, as there are 6 distinct 1x1 squares, and two possible 2x2 squares. A 4x3 rectangle contains 20 squares.
Your task is to write a function `findSquares` that returns the total number of squares for any given rectangle, the dimensions of which being given as two integers with the first always being equal to or greater than the second.

def findSquares(x,y):
    squares = 0
    while y > 0:
        squares = squares + x*y
        x = x-1
        y = y-1
    return squares


Solve in Python:
A rectangle with sides $A$ and $B$ is cut into rectangles with cuts parallel to its sides. For example, if $p$ horizontal and $q$ vertical cuts were made, $(p + 1) \cdot (q + 1)$ rectangles were left after the cutting. After the cutting, rectangles were of $n$ different types. Two rectangles are different if at least one side of one rectangle isn't equal to the corresponding side of the other. Note that the rectangle can't be rotated, this means that rectangles $a \times b$ and $b \times a$ are considered different if $a \neq b$.

For each type of rectangles, lengths of the sides of rectangles are given along with the amount of the rectangles of this type that were left after cutting the initial rectangle.

Calculate the amount of pairs $(A; B)$ such as the given rectangles could be created by cutting the rectangle with sides of lengths $A$ and $B$. Note that pairs $(A; B)$ and $(B; A)$ are considered different when $A \neq B$.

-----Input-----

The first line consists of a single integer $n$ ($1 \leq n \leq 2 \cdot 10^{5}$) — amount of different types of rectangles left after cutting the initial rectangle.

The next $n$ lines each consist of three integers $w_{i}, h_{i}, c_{i}$ $(1 \leq w_{i}, h_{i}, c_{i} \leq 10^{12})$ — the lengths of the sides of the rectangles of this type and the amount of the rectangles of this type.

It is guaranteed that the rectangles of the different types are different.

-----Output-----

Output one integer — the answer to the problem.

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

Output
3

Input
2
2 3 20
2 4 40

Output
6

Input
2
1 2 5
2 3 5

Output
0

-----Note-----

In the first sample there are three suitable pairs: $(1; 9)$, $(3; 3)$ and $(9; 1)$.

In the second sample case there are 6 suitable pairs: $(2; 220)$, $(4; 110)$, $(8; 55)$, $(10; 44)$, $(20; 22)$ and $(40; 11)$.

Here the sample of cut for $(20; 22)$.

 [Image]

The third sample has no suitable pairs.

n =int(input())
w=[]
h=[]
c=[]
cntw={}
cnth={}
multMayotC=0
cntC=0

def insert1(a,b,c):
    if not a in b :
        b[a]=c
    else :
        b[a]=b[a]+c

def multMayot(a,b):
    if a % b == 0 :
        return b
    else :
        return multMayot(b,a%b)

for i in range(0, n):
    a,b,d = map(int,input().split())
    w.append(a)
    h.append(b)
    c.append(d)
    insert1(a,cntw,d)
    insert1(b,cnth,d)
    cntC += d

    if multMayotC == 0 :
        multMayotC = d
    else:
        multMayotC = multMayot(multMayotC, d)

for i in range(0, n):
    if cntw[w[i]] * cnth[h[i]] != cntC * c[i]:
        print (0)
        return

result = 0
i = 1
while (i * i <= multMayotC) :
    if multMayotC % i == 0 :
        result += 1
        if i * i != multMayotC :
            result += 1
    i += 1

print (result)


Solve in Python:
A repetition-free number is one in which each digit $\{1,2,3,…,9\}$ appears at most once and the digit $0$ does not appear. A repetition-free number can have at most nine digits, but may also have fewer than nine digits. Some examples of repetition-free numbers are $9, 32, 489, 98761$ and $983245$.
You will be given an integer $N$ with at most nine digits. Your task is to print out the smallest repetition-free number bigger than $N$. For example, for $99$ the answer is $123$, for $881$ the answer is $891$, and for $133$ the answer is $134$.

-----Input:-----
A single line with a single integer with at most $9$ digits.

-----Output:-----
A single line containing the smallest repetition-free number bigger than the given number. If there is no repetition-free number bigger than the given number, print $0$.

-----Constraints:-----
- $N$ consists of atmost $9$ digits

-----Sample input-----
99

-----Sample output-----
123

n=int(input())
if n>999999999 or n<-999999999:
	print(0)
else:
	n+=1
	f=False
	p=False
	while n<=987654321:
		k=str(n)
		if k.count('0')==0:
			for i in range(len(k)):
				if k.count(k[i])>1:
					p=True
					break
			if p:
				p=False
			else:
				f=True
				break

		n+=1
	if f:
		print(n)
	else:
		print(0)


Solve in Python:
A reversed arabic no is one whose digits have been written in the reversed order. However in this any trailing zeroes are omitted. The task at hand here is a simple one. You need to add two numbers which have been written in reversed arabic and return the output back in reversed arabic form, assuming no zeroes were lost while reversing.

-----Input-----
The input consists of N cases. The first line of the input contains only a positive integer N. Then follow the cases. Each case consists of exactly one line with two positive integers seperated by space. These are the reversednumbers you are to add.

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

-----Example-----
Input:
1
24 1

Output:
34

n = int(input())
for index in range(0, n):
 a, b = list(map(str, input().split()))
 a = int(a[::-1])
 b = int(b[::-1])
 a = str(a + b)
 a = int(a[::-1])
 print(a)


Solve in Python:
A robber has attempted to rob a bank but failed to complete his task. However, he had managed to open all the safes.

Oleg the bank client loves money (who doesn't), and decides to take advantage of this failed robbery and steal some money from the safes. There are many safes arranged in a line, where the i-th safe from the left is called safe i. There are n banknotes left in all the safes in total. The i-th banknote is in safe x_{i}. Oleg is now at safe a. There are two security guards, one of which guards the safe b such that b < a, i.e. the first guard is to the left of Oleg. The other guard guards the safe c so that c > a, i.e. he is to the right of Oleg.

The two guards are very lazy, so they do not move. In every second, Oleg can either take all the banknotes from the current safe or move to any of the neighboring safes. However, he cannot visit any safe that is guarded by security guards at any time, becaues he might be charged for stealing. Determine the maximum amount of banknotes Oleg can gather.

-----Input-----

The first line of input contains three space-separated integers, a, b and c (1 ≤ b < a < c ≤ 10^9), denoting the positions of Oleg, the first security guard and the second security guard, respectively.

The next line of input contains a single integer n (1 ≤ n ≤ 10^5), denoting the number of banknotes.

The next line of input contains n space-separated integers x_1, x_2, ..., x_{n} (1 ≤ x_{i} ≤ 10^9), denoting that the i-th banknote is located in the x_{i}-th safe. Note that x_{i} are not guaranteed to be distinct.

-----Output-----

Output a single integer: the maximum number of banknotes Oleg can take.

-----Examples-----
Input
5 3 7
8
4 7 5 5 3 6 2 8

Output
4

Input
6 5 7
5
1 5 7 92 3

Output
0

-----Note-----

In the first example Oleg can take the banknotes in positions 4, 5, 6 (note that there are 2 banknotes at position 5). Oleg can't take the banknotes in safes 7 and 8 because he can't run into the second security guard. Similarly, Oleg cannot take the banknotes at positions...

a,b,c = map(int, input().split())
n = int(input())
p = list(map(int, input().split()))
sm = 0
for i in range(len(p)):
    if p[i] > b and p[i] < c:
        sm += 1
print(sm)


Solve in Python:
A robot is initially at $(0,0)$ on the cartesian plane. It can move in 4 directions - up, down, left, right denoted by letter u, d, l, r respectively. More formally:
- if the position of robot is $(x,y)$ then u makes it $(x,y+1)$
- if the position of robot is $(x,y)$ then l makes it $(x-1,y)$
- if the position of robot is $(x,y)$ then d makes it $(x,y-1)$
- if the position of robot is $(x,y)$ then r makes it $(x+1,y)$
The robot is performing a counter-clockwise spiral movement such that his movement can be represented by the following sequence of moves -
ulddrruuulllddddrrrruuuuu… and so on.
A single move takes 1 sec. You have to find out the position of the robot on the cartesian plane at $t$ second.

-----Input:-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $t$.

-----Output:-----
For each test case, print two space-separated integers, $(x,y)$ — the position of the robot.

-----Constraints-----
- $1 \leq T \leq 10^6$
- $1 \leq t \leq 10^{18}$

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

-----Sample Output:-----
0 1
-1 1
-1 0
2 4
-1749 812

z = int(input())
i = 0
while i < z:
  n = int(input())
  p = int(n**(0.5))
  if p*(p+1) < n:
    p += 1
  # print("P", p)
  x, y = 0, 0
  q = 0
  flag = True
  if p*(p+1) == n:
    # print("Even steps, nice")
    q = p
  else:
    # remaining steps
    q = p-1
    flag = False
  if q%2 :
    # odd
    x -= ((q+1)//2)
    y += ((q+1)//2)
  else :
    x += (q//2)
    y -= (q//2)
  if flag:
    print(x, y)
  else:
    # remaining steps
    l = q*(q+1)
    t = p*(p+1)
    diff = t-l

    # print(x, y)
    if x < 0:
      # left
      if n-l >= diff//2:
        y *= (-1)
        l += (diff//2)
        x += (n-l)
      else :
        y -= (n-l)

    else:
      # right
      if n-l >= diff//2:
        y *= (-1)
        y += 1
        l += (diff//2)
        x -= (n-l)
      else :
        y += (n-l)
    # print("Remaining steps: ", n-l)
    print(x, y)
  i+=1


Solve in Python:
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

How many possible unique paths are there?

Above is a 7 x 3 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

Example 1:

Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right

Example 2:

Input: m = 7, n = 3
Output: 28

class Solution:
     def uniquePaths(self, m, n):
         """
         :type m: int
         :type n: int
         :rtype: int
         """
         a = m - 1
         b = n - 1
         ret = 1
         for i in range(b):
             ret = ret * (a+b-i) / (b-i)
         return round(ret)


Solve in Python:
A robot on an infinite grid starts at point (0, 0) and faces north.  The robot can receive one of three possible types of commands:

-2: turn left 90 degrees
-1: turn right 90 degrees
1 <= x <= 9: move forward x units

Some of the grid squares are obstacles.
The i-th obstacle is at grid point (obstacles[i][0], obstacles[i][1])
If the robot would try to move onto them, the robot stays on the previous grid square instead (but still continues following the rest of the route.)
Return the square of the maximum Euclidean distance that the robot will be from the origin.

Example 1:
Input: commands = [4,-1,3], obstacles = []
Output: 25
Explanation: robot will go to (3, 4)

Example 2:
Input: commands = [4,-1,4,-2,4], obstacles = [[2,4]]
Output: 65
Explanation: robot will be stuck at (1, 4) before turning left and going to (1, 8)

Note:

0 <= commands.length <= 10000
0 <= obstacles.length <= 10000
-30000 <= obstacle[i][0] <= 30000
-30000 <= obstacle[i][1] <= 30000
The answer is guaranteed to be less than 2 ^ 31.

class Solution:
    def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:
        arrow = [(-1,0), (0,1), (1,0), (0,-1)]
        arrowNow = 1
        curPoint = [0,0]
        obstacles = [tuple(e) for e in obstacles]
        setObs = set(obstacles)
        ans = 0
        for e in commands:
            if e==-1:
                arrowNow= (arrowNow+1)%4
            elif e==-2:
                arrowNow= (arrowNow-1)%4
            else:
                for i in range(e):
                    rowNow = curPoint[0] + arrow[arrowNow][0]
                    colomNow = curPoint[1] + arrow[arrowNow][1]
                    if (rowNow, colomNow) not in setObs:
                        ans = max(ans, rowNow**2 + colomNow**2)
                        curPoint[0], curPoint[1] = rowNow, colomNow
        return ans


Solve in Python:
A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practice.

Applying the simplest variant of median smoothing to the sequence of numbers a_1, a_2, ..., a_{n} will result a new sequence b_1, b_2, ..., b_{n} obtained by the following algorithm:  b_1 = a_1, b_{n} = a_{n}, that is, the first and the last number of the new sequence match the corresponding numbers of the original sequence.  For i = 2, ..., n - 1 value b_{i} is equal to the median of three values a_{i} - 1, a_{i} and a_{i} + 1.

The median of a set of three numbers is the number that goes on the second place, when these three numbers are written in the non-decreasing order. For example, the median of the set 5, 1, 2 is number 2, and the median of set 1, 0, 1 is equal to 1.

In order to make the task easier, Vasya decided to apply the method to sequences consisting of zeros and ones only.

Having made the procedure once, Vasya looked at the resulting sequence and thought: what if I apply the algorithm to it once again, and then apply it to the next result, and so on? Vasya tried a couple of examples and found out that after some number of median smoothing algorithm applications the sequence can stop changing. We say that the sequence is stable, if it does not change when the median smoothing is applied to it.

Now Vasya wonders, whether the sequence always eventually becomes stable. He asks you to write a program that, given a sequence of zeros and ones, will determine whether it ever becomes stable. Moreover, if it ever becomes stable, then you should determine what will it look like and how many times one needs to apply the median smoothing algorithm to initial sequence in order to obtain a stable one.

-----Input-----

The first input line of the input contains a single integer n (3 ≤...

from math import ceil

def __starting_point():
    n = int(input())
    arr = list(map(int, input().split()))

    narr = [True]

    for i in range(1, n - 1):
        x = arr[i]
        narr.append(x == arr[i - 1] or x == arr[i + 1])

    narr.append(True)

    cnt = 0
    mc = 0

    for x in narr:
        if not x:
            cnt += 1
        if x and cnt:
            mc = max(mc, cnt)
            cnt = 0

    if cnt:
        mc = max(mc, cnt)

    print(ceil(mc / 2))

    ss = None

    for i, x in enumerate(arr):
        if not narr[i]:
            if ss is None:
                ss = i
        elif ss is not None:
            if arr[ss - 1] == x:
                for j in range(ss, i):
                    arr[j] = x
            else:
                for j in range(ss, i):
                    arr[j] = arr[ss - 1] if j < (i + ss) / 2 else x
            ss = None

    print(*arr)

__starting_point()


Solve in Python:
A sentence S is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only.
We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.)
The rules of Goat Latin are as follows:

If a word begins with a vowel (a, e, i, o, or u), append "ma" to the end of the word.
        For example, the word 'apple' becomes 'applema'.

If a word begins with a consonant (i.e. not a vowel), remove the first letter and append it to the end, then add "ma".
        For example, the word "goat" becomes "oatgma".

Add one letter 'a' to the end of each word per its word index in the sentence, starting with 1.
        For example, the first word gets "a" added to the end, the second word gets "aa" added to the end and so on.

Return the final sentence representing the conversion from S to Goat Latin.

Example 1:
Input: "I speak Goat Latin"
Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"

Example 2:
Input: "The quick brown fox jumped over the lazy dog"
Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"

Notes:

S contains only uppercase, lowercase and spaces. Exactly one space between each word.
1 <= S.length <= 150.

class Solution:
    def toGoatLatin(self, S: str) -> str:

        vowels = set(['a','e','i','o','u'])
        s = ''
        for i,item in enumerate(S.strip().split()):
            if item[0].lower() in vowels:
                s+=item
            else:
                s+=item[1:]+item[0]

            s+='ma'+'a'*(i+1)+' '

        return s[:-1]


Solve in Python:
A sequence X_1, X_2, ..., X_n is fibonacci-like if:

n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n

Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A.  If one does not exist, return 0.
(Recall that a subsequence is derived from another sequence A by deleting any number of elements (including none) from A, without changing the order of the remaining elements.  For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].)

Example 1:
Input: [1,2,3,4,5,6,7,8]
Output: 5
Explanation:
The longest subsequence that is fibonacci-like: [1,2,3,5,8].

Example 2:
Input: [1,3,7,11,12,14,18]
Output: 3
Explanation:
The longest subsequence that is fibonacci-like:
[1,11,12], [3,11,14] or [7,11,18].

Note:

3 <= A.length <= 1000
1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9
(The time limit has been reduced by 50% for submissions in Java, C, and C++.)

class Solution:
    def lenLongestFibSubseq(self, A: List[int]) -> int:
        dp = dict()
        res = 2
        for i in range(len(A)):
            for j in range(i):
                if (A[j], A[i]-A[j]) in dp:
                    dp[A[i], A[j]] = dp[A[j], A[i]-A[j]] + 1
                else:
                    dp[A[i], A[j]] = 2

                res = max(res, dp[A[i], A[j]])

        return res if res > 2 else 0


Solve in Python:
A sequence is usually a set or an array of numbers that has a strict way for moving from the nth term to the (n+1)th term.
If ``f(n) = f(n-1) + c`` where ``c`` is a constant value, then ``f`` is an arithmetic sequence.
An example would be (where the first term is 0 and the constant is 1) is [0, 1, 2, 3, 4, 5, ... and so on] )
Else if (pun) ``f(n) = f(n-1) * c`` where ``c`` is a constant value, then ``f`` is a geometric sequence.
Example where the first term is 2 and  the constant is 2 will be [2, 4, 8, 16, 32, 64, ... to infinity ... ]
There are some sequences that aren't arithmetic nor are they geometric.
Here is a link to feed your brain : Sequence !

You're going to write a function that's going to return the value in the nth index of an arithmetic sequence.(That is, adding a constant to move to the next element in the "set").

The function's name is `nthterm`/`Nthterm`, it takes three inputs `first`,`n`,`c` where:

  - ``first`` is the first value in the 0 INDEX.
  - ``n`` is the index of the value we want.
  - ``c`` is the constant added between the terms.

Remember that `first` is in the index ``0`` .. just saying ...

def nthterm(f, n, c):
    return n * c + f


Solve in Python:
A sequence of integers ($a_1, a_2, \ldots, a_k$) is said to be UpDown, if these inequalities hold true:
- $a_1 \le a_2$
- $a_2 \ge a_3$
- $a_3 \le a_4$
and so on.
That is, every even-indexed element should be at least as large as its adjacent elements. And every odd-indexed element should be at most as large as its adjacent elements. Formally, $a_{2i} \ge a_{2i+1}$ and $a_{2i+1} \le a_{2i+2}$, for all valid positions.
A subsegment is a consecutive portion of a sequence. That is, a subsegment of ($b_1, b_2, \ldots, b_k$)  will be of the form ($b_i, b_{i+1}, \ldots, b_j$), for some $i$ and $j$.
You are given a sequence ($s_1, s_2, \ldots, s_n$). You can insert at most one integer anywhere in this sequence. It could be any integer. After inserting an integer (or choosing not to), suppose you have the new sequence ($t_1, t_2, \ldots, t_m$). Note that $m$ will either be $n$+1 or $n$. You want to maximize the length of the longest subsegment of ($t_1, t_2, \ldots, t_m$) which is UpDown, and output the length of that.

-----Input-----
- The first line contains a single integer, $T$, which is the number of testcases. The description of each testcase follows.
- The first line of every testcase contains a single integer, $n$, which is the number of integers in the original sequence.
- The second line contains $n$ integers: $s_1, s_2, \ldots, s_n$, which forms the original sequence.

-----Output-----
For each testcase output a single line containing one integer, which should be the length of the longest UpDown subsegment that you can get after inserting at most one integer.

-----Constraints-----
- $1 \le T \le 2$
- $1 \le n \le 10^6$
- $1 \le s_i \le 10^9$

-----Subtasks-----
Subtask #1 (20 points): $1 \le n \le 100$
Subtask #2 (10 points): $1 \le n \le 10000$
Subtask #3 (70 points): Original constraints

-----Sample Input-----
2
7
100 1 10 3 20 25 24
5
3 3 2 4 1

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

-----Explanation-----
Testcase 1: The original sequence is (100, 1, 10, 3, 20, 25, 24). Suppose you insert the element 5 between...

for i in range(int(input())):
	n = int(input())
	dp = [[1 for k in range(n)] for k in range(2)] # row 1: longest UD, row 2: longest DU
	nums = [int(i) for i in input().split()]
	answer = 0
	for k in range(n - 2, -1, -1):
		if nums[k + 1] >= nums[k]:
			dp[0][k] = 1 + dp[1][k + 1]
			if dp[0][k] > answer:
				answer = dp[0][k]
		if nums[k + 1] <= nums[k]:
			dp[1][k] = 1 + dp[0][k + 1]

	answer += 1
	for k in range(n - 1):
		if k + dp[0][k] >= n:
			continue
		possible = 0
		if dp[0][k] % 2 == 0:
			possible = dp[0][k] + dp[1][k + dp[0][k]] + 1
		else:
			possible = dp[0][k] + dp[0][k + dp[0][k]] + 1
		if possible > answer:
			answer = possible

	print(answer)


Solve in Python:
A sequence of number is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.

For example, these are arithmetic sequence:
1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9

The following sequence is not arithmetic. 1, 1, 2, 5, 7

A zero-indexed array A consisting of N numbers is given. A slice of that array is any pair of integers (P, Q) such that 0

A slice (P, Q) of array A is called arithmetic if the sequence:
    A[P], A[p + 1], ..., A[Q - 1], A[Q] is arithmetic. In particular, this means that P + 1 < Q.

The function should return the number of arithmetic slices in the array A.

Example:

A = [1, 2, 3, 4]

return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself.

class Solution:
     def numberOfArithmeticSlices(self, A):
         curr, sum = 0, 0
         for i in range(2,len(A)):
             if A[i]-A[i-1] == A[i-1]-A[i-2]:
                 curr += 1
                 sum += curr
             else:
                 curr = 0
         return sum
 #         solution = 0
 #         connected = 1
 #         old_diff = None
 #         sequences = []
 #         if len(A) < 3:
 #             return 0

 #         for index,num in enumerate(A):
 #             if index < len(A) - 1:
 #                 new_diff = num - A[index + 1]
 #             else:
 #                 new_diff = A[index - 1] - num
 #             if old_diff == new_diff:
 #                 if index == len(A) - 1 and connected >= 3:
 #                     connected += 1
 #                     sequences.append(connected)
 #                 connected += 1
 #             else:
 #                 old_diff = new_diff
 #                 if connected > 2:
 #                     sequences.append(connected)
 #                 connected = 1
 #         for sequence in sequences:
 #             prev = 0
 #             while sequence >= 2:
 #                 prev += 1
 #                 solution += prev
 #                 sequence -= 1
 #         return solution


Solve in Python:
A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.

For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.

Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.

Examples:

Input: [1,7,4,9,2,5]
Output: 6
The entire sequence is a wiggle sequence.

Input: [1,17,5,10,13,15,10,5,16,8]
Output: 7
There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8].

Input: [1,2,3,4,5,6,7,8,9]
Output: 2

Follow up:
Can you do it in O(n) time?

Credits:Special thanks to @agave and @StefanPochmann for adding this problem and creating all test cases.

class Solution:
     def wiggleMaxLength(self, nums):
         """
         :type nums: List[int]
         :rtype: int
         """
         l = len(nums)
         if l == 0:
             return 0
         elif l == 1:
             return 1
         st = 1
         while nums[0] == nums[st]:
             st += 1
             if st == l:
                 return 1
         seq = [nums[0], nums[st]]
         for i in range(st+1, l):
             if nums[i] == seq[-1]:
                 continue
             if seq[-1] < seq[-2]:
                 if nums[i] < seq[-1]:
                     seq[-1] = nums[i]
                 else:
                     seq.append(nums[i])
             else:
                 if nums[i]>seq[-1]:
                     seq[-1] = nums[i]
                 else:
                     seq.append(nums[i])
         return len(seq)


Solve in Python:
A series or sequence of numbers is usually the product of a function and can either be infinite or finite.

In this kata we will only consider finite series and you are required to return a code according to the type of sequence:

|Code|Type|Example|
|-|-|-|
|`0`|`unordered`|`[3,5,8,1,14,3]`|
|`1`|`strictly increasing`|`[3,5,8,9,14,23]`|
|`2`|`not decreasing`|`[3,5,8,8,14,14]`|
|`3`|`strictly decreasing`|`[14,9,8,5,3,1]`|
|`4`|`not increasing`|`[14,14,8,8,5,3]`|
|`5`|`constant`|`[8,8,8,8,8,8]`|

You can expect all the inputs to be non-empty and completely numerical arrays/lists - no need to validate the data; do not go for sloppy code, as rather large inputs might be tested.

Try to achieve a good solution that runs in linear time; also, do it functionally, meaning you need to build a *pure* function or, in even poorer words, do NOT modify the initial input!

def sequence_classifier(arr):
    if all(arr[i] == arr[i+1] for i in range(len(arr)-1)): return 5
    if all(arr[i] <  arr[i+1] for i in range(len(arr)-1)): return 1
    if all(arr[i] <= arr[i+1] for i in range(len(arr)-1)): return 2
    if all(arr[i] >  arr[i+1] for i in range(len(arr)-1)): return 3
    if all(arr[i] >= arr[i+1] for i in range(len(arr)-1)): return 4
    return 0


Solve in Python:
A simple string contains a large repetition of letters within it. This problem is related to string handling and manipulation.  An original message is sent from planet Earth to planet Cybertron in form of a string. However, the letter position and string size is not important. The number of time each letter has occurred in the string is important. So the original string which is sent to Cybertron is encrypted in the new string which comprises the letters followed by each time it has occurred in the original string. Eg- original message is- abcdabf. Then the encrypted string is- a2b2c1d1f1

-----Input-----
The input consists of a single line string without any space or numeric or special characters.

-----Output-----
It will consist of in the encrypted string which comprises the letters followed by each time it has occurred in the original string in order.

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

Output:
i2n2f1o2r1m1a1t1

import sys,math

def main(filename):
 inputfile = open(filename,'rU')
 data = inputfile.readlines()
 T=data.pop(0)
 ans=[]
 ansstring=str()
 explored=[]
 for i in T:
  if i in explored:
   #print explored
   for j in range(len(ans)):
    if ans[j][0]==i:
     ans[j][1] += 1
  else:
   ans.append([i,1])
   explored.append(i)
 for i in ans:
  ansstring += i[0]+str(i[1])
 print(ansstring)

 inputfile.close()

def __starting_point():
 main(sys.argv[1])
__starting_point()


Solve in Python:
A sophomore Computer Science student is frustrated with boring college lectures. Professor X agreed to give him some questions; if the student answers all questions correctly, then minimum attendance criteria will not apply to him.
Professor X chooses a sequence $A_1, A_2, \ldots, A_N$ and asks $Q$ queries. In each query, the student is given an integer $P$; he has to construct a sequence $B_1, B_2, \ldots, B_N$, where $P \oplus A_i = B_i$ for each valid $i$ ($\oplus$ denotes bitwise XOR), and then he has to find the number of elements of this sequence which have an even number of $1$-s in the binary representation and the number of elements with an odd number of $1$-s in the binary representation. Help him answer the queries.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains two space-separated integers $N$ and $Q$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.
- $Q$ lines follow. Each of these lines contains a single integer $P$ describing a query.

-----Output-----
For each query, print a single line containing two space-separated integers ― the number of elements with an even number of $1$-s and the number of elements with an odd number of $1$-s in the binary representation.

-----Constraints-----
- $1 \le T \le 100$
- $1 \le N, Q \le 10^5$
- $ T \cdot (N+Q) \leq 4 \cdot 10^6 $
- $1 \le A_i \le 10^8$ for each valid $i$
- $1 \le P \le 10^5$
The input/output is quite large, please use fast reading and writing methods.

-----Subtasks-----
Subtask #1 (30 points): $N, Q \le 1,000$
Subtask #2 (70 points): original constraints

-----Example Input-----
1
6 1
4 2 15 9 8 8
3

-----Example Output-----
2 4

-----Explanation-----
Example case 1: The elements of the sequence $B$ are $P \oplus 4 = 7$, $P \oplus 2 = 1$, $P \oplus 15 = 12$, $P \oplus 9 = 10$, $P \oplus 8 = 11$ and $P \oplus 8 = 11$. The elements which have an even number of...

# cook your dish here
from sys import stdin, stdout
t=int(input())
for i in range(t):
 n,q=list(map(int,stdin.readline().split()))
 a=list(map(int,stdin.readline().split()))
 even,odd=0,0
 for j in range(n):
  count=(bin(a[j]).count("1"))
  if count%2==0:
   even+=1
  else:
   odd+=1

 for j in range(q):
  m=int(stdin.readline())
  temp=bin(m).count("1")
  temp1,temp2=even,odd
  if temp%2==0:
   temp1,temp2=even,odd
  else:
   temp1,temp2=odd,even
  stdout.write(str(temp1)+" "+str(temp2))
  stdout.write("\n")


Solve in Python:
A special type of prime is generated by the formula `p = 2^m * 3^n + 1` where `m` and `n` can be any non-negative integer.

The first `5` of these primes are `2, 3, 5, 7, 13`, and are generated as follows:
```Haskell
2 = 2^0 * 3^0 + 1
3 = 2^1 * 3^0 + 1
5 = 2^2 * 3^0 + 1
7 = 2^1 * 3^1 + 1
13 = 2^2 * 3^1 + 1
..and so on
```
You will be given a range and your task is to return the number of primes that have this property. For example, `solve(0,15) = 5`, because there are only `5` such primes `>= 0 and < 15`; they are `2,3,5,7,13`. The upper limit of the tests will not exceed `1,500,000`.

More examples in the test cases.

Good luck!

If you like Prime Katas, you will enjoy this Kata: [Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3)


Solve in Python:
A spoonerism is a spoken phrase in which the first letters of two of the words are swapped around, often with amusing results.

In its most basic form a spoonerism is a two word phrase in which only the first letters of each word are swapped:

```"not picking" --> "pot nicking"```

Your task is to create a function that takes a string of two words, separated by a space: ```words``` and returns a spoonerism of those words in a string, as in the above example.

NOTE: All input strings will contain only two words.  Spoonerisms can be more complex.  For example, three-word phrases in which the first letters of the first and last words are swapped: ```"pack of lies" --> "lack of pies"``` or more than one letter from a word is swapped: ```"flat battery --> "bat flattery"```
You are NOT expected to account for these, or any other nuances involved in spoonerisms.

Once you have completed this kata, a slightly more challenging take on the idea can be found here: http://www.codewars.com/kata/56dbed3a13c2f61ae3000bcd

def spoonerize(words):
    a, b = words.split(' ')
    return b[0] + a[1:] + ' ' + a[0] + b[1:]


Solve in Python:
A spy needs your help to encrypt a 5 letter message.
To encrypt the message the following steps are need to be done:
1)Each letter of the message will be converted to it's equivalent number (i.e A=0, B=1,..Z=25)
2)98, 57, 31, 45, 46 are the 5 numbers in the key.
3)Add the equivalent number of the first letter of the message to the first number of the key, then the equivalent number of the second letter of the message to the second number of the key and so on.
4)Take modulo 26 of the sum of each expression.
5)Convert the newly obtained numbers into it's equivalent letters (i.e 0=A, 1=B,…25=Z)
Print the final encrypted string.
Note: It is guaranteed that the given string only contains Only Upper-case Latin Letters.

-----Input:-----
- The first line of the input contains a single Integer $T$. $T$ denoting the number of testcases, description of each testcases contains.
- The first line of the each testcase contains a single string $S$. $S$ denoting the string which you need to encrypt

-----Output:-----
- For each test case, print encypted string i.e result of above operation.
Note: Each testcase output must be printed on new line

-----Constraints:-----
- $1 \leq T \leq 100$
- $1 \leq S \leq 5$

-----Sample Input:-----
2
HELLO
HELL

-----Sample Output:-----
BJQEI
BJQE

-----Explanation:-----
- For 1st Testcase : The conversion of "HELLO" to its equivalent number will be 7, 4, 11, 11, 14 respectively.
Then we add each equivalent number of the message with corresponding number in the key:
7 + 98 = 105
4 + 57 = 61
11 + 31 = 42
11 + 45 = 56
14 + 46 = 60
Further we take the sum:
105 modulo 26 = 1
61 modulo 26 = 9
42 modulo 26 = 16
56 modulo 26 = 4
60 modulo 26 = 8
Finally, convert the newly obtained numbers into it's equivalent letters:
B
J
Q
E
I
Print the final string:
BJQEI

n=int(input())
l=[98,57,31,45,46]
f=''
for i in range(0,n):
    s=input().strip()
    for z in range(0,len(s)):
        k=ord(s[z])-65
        k=k+l[z]
        req=k%(26)
        req=req+65
        f=f+chr(req)
    print(f)
    f=''


Solve in Python:
A squarer is a simple and convenient device. You give it some positive integer X and it calculates its square.
Leha is implementing a module of this device which is responsible for squaring the numbers consisting of multiple repetitions of one digit. But it turned out that it's not as simple as he thought.
Please help him now!

-----Input-----
The first line contains one integer T denoting the number of testcases. The descriptions of T test cases follow.
Each of the following T lines contain 2 space-separated integers - N and D, respectively. It means that the number X in the corresponding testcase consists of the digit D repeated N times (in decimal representation).

-----Output-----
As the answer can be very large, we ask you to output its hash which is computed in the following way:
Let's consider the integer answer Y as a 0-indexed array starting from its leftmost digit. The hash function is calculated as:
p0*Y[0] + p1*Y[1] + ... + pM-1*Y[M-1] modulo 109 + 7
where M is the length of the array representation of Y and p equals 23.

-----Constraints-----
- 1 ≤ T ≤ 20
- 1 ≤ D ≤ 9
- Subtask 1 (16 points): 1 ≤ N ≤ 9
- Subtask 2 (25 points): 1 ≤ N ≤ 100
- Subtask 3 (27 points): 1 ≤ N ≤ 2 × 104
- Subtask 4 (32 points): 1 ≤ N ≤ 106

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

Output:139
40079781
32745632

-----Explanation-----
In the first test case, X = 4 and Y = 16. Its hash equals 1*1 + 23*6 = 139.

mod=1000000007
dp =[]
dp.append(1)
tens=[]
tens.append(10)
tws=[]
tws.append(1)
for i in range(1, 21):
 tens.append(tens[i-1]*tens[i-1])
 dp.append(dp[i-1]*tens[i-1]+dp[i-1])
 tws.append(tws[i-1]*2)

t=eval(input())
t=int(t)
for i in range(0, t):
 now=0
 b, a = input().split()
 a=int(a)
 b=int(b)
 j=20
 val=0
 while(j>=0):
  if(b>=tws[j]):
   val*=tens[j]
   val+=dp[j]
   b-=tws[j]
  j-=1
 val*=a
 act=val*val
 now=str(act)
 # print(now)
 dow=1
 ans=0
 for c in now:
  x=int(c)
  # print(x)
  # print(dow)
  ans+=(dow*x)
  dow*=23
  dow%=mod
  ans%=mod
 print(ans)
 # digs=[]
 # while(act >0):
 #   d=act%10
 #   digs.append(d)
 #   act=act/10
 # now=0
 # while (act > 0):
 #   d=act%10
 #   now*=10
 #   now+=d
 #   act=act/10
 # count=0
 # ans=0
 # mul=1
 # while (now > 0):
 #   d=now%10
 #   ans+=(mul*d)
 #   ans%=mod
 #   now/=10
 #   count+=1
 #   mul*=23
 #   mul%=mod
 # print(ans)


Solve in Python:
A startup office has an ongoing problem with its bin. Due to low budgets, they don't hire cleaners. As a result, the staff are left to voluntarily empty the bin. It has emerged that a voluntary system is not working and the bin is often overflowing. One staff member has suggested creating a rota system based upon the staff seating plan.

Create a function `binRota` that accepts a 2D array of names. The function will return a single array containing staff names in the order that they should empty the bin.

Adding to the problem, the office has some temporary staff. This means that the seating plan changes every month. Both staff members' names and the number of rows of seats may change. Ensure that the function `binRota` works when tested with these changes.

**Notes:**
- All the rows will always be the same length as each other.
- There will be no empty spaces in the seating plan.
- There will be no empty arrays.
- Each row will be at least one seat long.

An example seating plan is as follows:

![](http://i.imgur.com/aka6lh0l.png)

Or as an array:
```
[ ["Stefan", "Raj",    "Marie"],
  ["Alexa",  "Amy",    "Edward"],
  ["Liz",    "Claire", "Juan"],
  ["Dee",    "Luke",   "Katie"] ]
```

The rota should start with Stefan and end with Dee, taking the left-right zigzag path as illustrated by the red line:

As an output you would expect in this case:

```
["Stefan", "Raj", "Marie", "Edward", "Amy", "Alexa", "Liz", "Claire", "Juan", "Katie", "Luke", "Dee"])
```

def binRota(arr):
    return [seat for row, seats in enumerate(arr) for seat in seats[::(-1)**row]]


Solve in Python:
A stick is balanced horizontally on a support. Will it topple over or stay balanced? (This is a physics problem: imagine a real wooden stick balanced horizontally on someone's finger or on a narrow table, for example).

The stick is represented as a list, where each entry shows the mass in that part of the stick.

The stick is balanced on a support. The "terrain" is represented by a list of 1s and 0s, where the 1s represent the support and the 0s represent empty space. Each index is a coordinate on the x-axis, so e.g. the physical interpretations of some terrains are as follows:

![](https://i.imgur.com/P4MpHZV.png)

The stick will only balance if its centre of mass is directly above some part of its support. Return `True` if the stick will balance and `False` if it will topple.

Both lists will be of equal length (that is, the stick and the terrain have equal width so that each index of the stick is directly above the corresponding index of the terrain). Every terrain will contain one, and only one, support.

## Examples:

![](https://i.imgur.com/PyMBsAl.png)

```
[2,3,2]
[0,1,0] ---> Perfectly balanced, return True

[5,1,1]
[0,1,0] ---> will topple to the left, return False

[3,3,4]
[0,1,0] ---> will topple to the right (but only just)

[7,1,1,1,1,1,1,1]
[0,1,1,0,0,0,0,0] ---> will balance, perfectly, without a doubt

[5, 3, 2, 8, 6]
[0, 0, 0, 1, 1] ---> will topple to the left

```

will_it_balance=lambda a,s:s.index(1)<=sum(i*a[i]for i in range(len(a)))/sum(a)<=len(s)-s[::-1].index(1)-1


Solve in Python:
A string S of lowercase letters is given.  Then, we may make any number of moves.
In each move, we choose one of the first K letters (starting from the left), remove it, and place it at the end of the string.
Return the lexicographically smallest string we could have after any number of moves.

Example 1:
Input: S = "cba", K = 1
Output: "acb"
Explanation:
In the first move, we move the 1st character ("c") to the end, obtaining the string "bac".
In the second move, we move the 1st character ("b") to the end, obtaining the final result "acb".

Example 2:
Input: S = "baaca", K = 3
Output: "aaabc"
Explanation:
In the first move, we move the 1st character ("b") to the end, obtaining the string "aacab".
In the second move, we move the 3rd character ("c") to the end, obtaining the final result "aaabc".

Note:

1 <= K <= S.length <= 1000
S consists of lowercase letters only.

class Solution:
    def orderlyQueue(self, S: str, K: int) -> str:
        if K==1:
            tmp = S
            for i in range(len(S)):
                S = S[1:] + str(S[0])
                if S<tmp:
                    tmp = S
            return tmp
        else:
            return ''.join(sorted(S))


Solve in Python:
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.

Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".

Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.

Example 3:
Input: s = "leetcodeleet"
Output: "leet"

Example 4:
Input: s = "a"
Output: ""

Constraints:

1 <= s.length <= 10^5
s contains only lowercase English letters.

class Solution:
    def longestPrefix(self, s: str) -> str:
        res, l, r , mod = 0,0,0, 10**9+7
        for i in range(len(s)-1):
            l = (l*128 + ord(s[i]))%mod
            r = (ord(s[~i])*(pow(128,i,mod)) + r)%mod
            if l==r: res = i+1
        return s[:res ]

    def longestPrefix_bychance_Brute(self, s: str) -> str:
        res = ''
        for i in range(1, len(s)):
            if s[:i]==s[-i:]:
                res =s[:i]
        return res


Solve in Python:
A string is called happy if it does not have any of the strings 'aaa', 'bbb' or 'ccc' as a substring.
Given three integers a, b and c, return any string s, which satisfies following conditions:

s is happy and longest possible.
s contains at most a occurrences of the letter 'a', at most b occurrences of the letter 'b' and at most c occurrences of the letter 'c'.
s will only contain 'a', 'b' and 'c' letters.

If there is no such string s return the empty string "".

Example 1:
Input: a = 1, b = 1, c = 7
Output: "ccaccbcc"
Explanation: "ccbccacc" would also be a correct answer.

Example 2:
Input: a = 2, b = 2, c = 1
Output: "aabbc"

Example 3:
Input: a = 7, b = 1, c = 0
Output: "aabaa"
Explanation: It's the only correct answer in this case.

Constraints:

0 <= a, b, c <= 100
a + b + c > 0

class Solution:
    def longestDiverseString(self, a: int, b: int, c: int) -> str:
        # 更新初始存量，根据插空规则修正单个字符最大可能的数量
        d = {'a':min(a,2*(b+c+1)),'b':min(b,2*(a+c+1)),'c':min(c,2*(b+a+1))}
        # 修正后的数量确保可以全部用在结果中，求和计算字符串总长
        n = sum(d.values())
        # 维护结果列表
        res = []
        # 单次插入一个字符，根据长度循环
        for _ in range(n):
            # 候选的字母
            cand = set(['a','b','c'])
            # 如果列表最后两个字符相同，根据规则不能插入连续三个，故将该字符从候选中删除
            if len(res)>1 and res[-1]==res[-2]:
                cand.remove(res[-1])
            # 贪心，在候选中选择存量最大的字符
            tmp = max(cand,key=lambda x:d[x])
            # 将它加到结果里
            res.append(tmp)
            # 把它的剩余计数减去1. 开始下一轮
            d[tmp] -= 1
        return ''.join(res)


Solve in Python:
A string of '0's and '1's is monotone increasing if it consists of some number of '0's (possibly 0), followed by some number of '1's (also possibly 0.)
We are given a string S of '0's and '1's, and we may flip any '0' to a '1' or a '1' to a '0'.
Return the minimum number of flips to make S monotone increasing.

Example 1:
Input: "00110"
Output: 1
Explanation: We flip the last digit to get 00111.

Example 2:
Input: "010110"
Output: 2
Explanation: We flip to get 011111, or alternatively 000111.

Example 3:
Input: "00011000"
Output: 2
Explanation: We flip to get 00000000.

Note:

1 <= S.length <= 20000
S only consists of '0' and '1' characters.

class Solution:
    def minFlipsMonoIncr(self, S: str) -> int:
        str_len = len(S)
        count_arr = [[0,0] for x in range(str_len)]
        one_start_idx = -1
        for i in range(len(S)):
            if S[i]=='0':
                if i==0:
                    count_arr[i][0] +=1
                    count_arr[i][1] = 0
                else:
                    count_arr[i][0] = count_arr[i-1][0]+1
                    count_arr[i][1] = count_arr[i-1][1]
            else:
                if i==0:
                    count_arr[i][1] +=1
                else:
                    count_arr[i][1] = count_arr[i-1][1]+1
                    count_arr[i][0] = count_arr[i-1][0]

                if one_start_idx == -1:
                    one_start_idx = i

        total_flips = []
        total_flips.append(min(count_arr[str_len-1][0], count_arr[str_len-1][1]))

        for i in range(one_start_idx, str_len):
            if i==0:
                total_flips.append(count_arr[str_len-1][0]-count_arr[i][0])
            elif i==str_len-1:
                total_flips.append(count_arr[str_len-1][0])

            else:
                total_flips.append(count_arr[i-1][1]+count_arr[str_len-1][0]-count_arr[i][0])

        return min(total_flips)


Solve in Python:
A string with length $L$ is called rich if $L \ge 3$ and there is a character which occurs in this string strictly more than $L/2$ times.
You are given a string $S$ and you should answer $Q$ queries on this string. In each query, you are given a substring $S_L, S_{L+1}, \ldots, S_R$. Consider all substrings of this substring. You have to determine whether at least one of them is rich.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains two space-separated integers $N$ and $Q$.
- The second line contains a single string $S$ with length $N$.
- Each of the next $Q$ lines contains two space-separated integers $L$ and $R$ describing a query.

-----Output-----
For each query, print a single line containing the string "YES" if the given substring contains a rich substring or "NO" if it does not contain any rich substring.

-----Constraints-----
- $1 \le T \le 10$
- $1 \le N, Q \le 10^5$
- $1 \le L \le R \le N$
- $S$ contains only lowercase English letters

-----Example Input-----
1
10 2
helloworld
1 3
1 10

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

t=int(input())
for _ in range(t):
 n,m=list(map(int,input().split()))
 s=input()
 if n<3:
  for i in range(m):
   a,b=list(map(int,input().split()))
   print('NO')
 else:
  k=[s[0],s[1],s[2]]
  if k[0]==k[1] or k[1]==k[2] or k[0]==k[2]:
   c=1
  else:
   c=0
  ans=[0,c]
  for i in range(3,n):
   del(k[0])
   k.append(s[i])
   if k[0]==k[1] or k[1]==k[2] or k[0]==k[2]:
    c+=1
   ans.append(c)
  for i in range(m):
   a,b=list(map(int,input().split()))
   if b-a<2:
    print('NO')
    continue
   b-=2
   a-=1
   if ans[b]-ans[a]==0:
    print('NO')
   else:
    print('YES')


Solve in Python:
A strongness of an even number is the number of times we can successively divide by 2 until we reach an odd number starting with an even number n.

For example, if n = 12, then
* 12 / 2 = 6
* 6 / 2 = 3

So we divided successively 2 times and we reached 3, so the strongness of 12 is `2`.

If n = 16 then
* 16 / 2 = 8
* 8 / 2 = 4
* 4 / 2 = 2
* 2 / 2 = 1

we divided successively 4 times and we reached 1, so the strongness of 16 is `4`

# Task

Given a closed interval `[n, m]`, return the even number that is the strongest in the interval. If multiple solutions exist return the smallest strongest even number.

Note that programs must run within the allotted server time; a naive solution will probably time out.

# Constraints
```if-not:ruby
1 <= n < m <= INT_MAX
```
```if:ruby
1 <= n < m <= 2^64
```

# Examples
```
[1, 2]    -->   2  # 1 has strongness 0, 2 has strongness 1
[5, 10]   -->   8  # 5, 7, 9 have strongness 0; 6, 10 have strongness 1; 8 has strongness 3
[48, 56]  -->  48

from math import log
from math import floor

def strongest_even(n,m):
    a=2**floor(log(m)/log(2));b=1;
    while a*b<n or a*b>m:
        a /= 2;
        b += 2;
        while a*b<=m:
            if a*b>=n:
                return a*b
            b +=2

    return a*b
#strongest_even(33,47)


Solve in Python:
A subarray A[i], A[i+1], ..., A[j] of A is said to be turbulent if and only if:

For i <= k < j, A[k] > A[k+1] when k is odd, and A[k] < A[k+1] when k is even;
OR, for i <= k < j, A[k] > A[k+1] when k is even, and A[k] < A[k+1] when k is odd.

That is, the subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray.
Return the length of a maximum size turbulent subarray of A.

Example 1:
Input: [9,4,2,10,7,8,8,1,9]
Output: 5
Explanation: (A[1] > A[2] < A[3] > A[4] < A[5])

Example 2:
Input: [4,8,12,16]
Output: 2

Example 3:
Input: [100]
Output: 1

Note:

1 <= A.length <= 40000
0 <= A[i] <= 10^9

class Solution:
    def maxTurbulenceSize(self, A: List[int]) -> int:
        if len(A) < 2:
            return len(A)
        if len(A) == 2:
            return 2 if A[0] != A[1] else 1

        DP = [0 for _ in A]
        for i in range(1, len(A)):
            if DP[i-1] > 1:
                if A[i] > A[i-1]:
                    DP[i] = -DP[i-1] - 1
                elif A[i] < A[i-1]:
                    DP[i] = 2
                else:
                    DP[i] = 1
            elif DP[i-1] < -1:
                if A[i] < A[i-1]:
                    DP[i] = -DP[i-1] + 1
                elif A[i] > A[i-1]:
                    DP[i] = -2
                else:
                    DP[i] = -1
            else:
                if A[i] == A[i-1]:
                    DP[i] = 1
                else:
                    DP[i] = 2*(-1 if A[i] > A[i-1] else 1)

        return abs(max(DP, key = abs))


Solve in Python:
A subsequence of a string S is a string that can be obtained by deleting zero or more characters from S without changing the order of the remaining characters.
For example, arc, artistic and (an empty string) are all subsequences of artistic; abc and ci are not.
You are given a string A consisting of lowercase English letters.
Find the shortest string among the strings consisting of lowercase English letters that are not subsequences of A.
If there are more than one such string, find the lexicographically smallest one among them.

-----Constraints-----
 - 1 \leq |A| \leq 2 \times 10^5
 - A consists of lowercase English letters.

-----Input-----
Input is given from Standard Input in the following format:
A

-----Output-----
Print the lexicographically smallest string among the shortest strings consisting of lowercase English letters that are not subsequences of A.

-----Sample Input-----
atcoderregularcontest

-----Sample Output-----
b

The string atcoderregularcontest contains a as a subsequence, but not b.

n2a=lambda x:chr(x+ord('a'))
a2n=lambda x:ord(x)-ord('a')

def main(a):
  nc=26
  n=len(a)
  ary=[]
  tmp=[0]*nc
  mi=set(range(nc))
  for i in range(n-1,-1,-1):
    x=a2n(a[i])
    mi.discard(x)
    tmp[x]+=1
    if len(mi)==0:
      ary.append(tmp.copy())
      tmp=[0]*nc
      mi=set(range(nc))
  if any(tmp):ary.append(tmp)
  #for x in ary:print(x)
  ans=[]
  now=0
  tmp=ary.pop()
  if all(tmp):
    ans.append('a')
    while a[now]!='a':
      tmp[a2n(a[now])]-=1
      now+=1
    tmp[a2n(a[now])]-=1
    now+=1
  else:
    for i in range(nc):
      if tmp[i]==0:
        ans.append(n2a(i))
        break
    if not ary:return ans
    ntmp=ary.pop()
    for j in range(nc):tmp[j]+=ntmp[j]
    while a2n(a[now])!=i:
      tmp[a2n(a[now])]-=1
      now+=1
    tmp[a2n(a[now])]-=1
    now+=1
  while True:
    #print(ary,tmp,ans)
    for i in range(nc):
      if tmp[i]==0:
        ans.append(n2a(i))
        break
    if not ary:return ans
    ntmp=ary.pop()
    for j in range(nc):tmp[j]+=ntmp[j]
    while a2n(a[now])!=i:
      tmp[a2n(a[now])]-=1
      now+=1
    tmp[a2n(a[now])]-=1
    now+=1

a=input()
print(*main(a),sep='')
"""
bcdefghijklmnopqrstuvwxyza

aabbccaabca
aab / bccaa / bca

"""


Solve in Python:
A system is transmitting messages in binary, however it is not a perfect transmission, and sometimes errors will occur which result in a single bit flipping from 0 to 1, or from 1 to 0.

To resolve this, A 2-dimensional Parity Bit Code is used: https://en.wikipedia.org/wiki/Multidimensional_parity-check_code

In this system, a message is arrayed out on a M x N grid. A 24-bit message could be put on a 4x6 grid like so:

>1 0 1 0 0 1
>1 0 0 1 0 0
>0 1 1 1 0 1
>1 0 0 0 0 1

Then, Parity bits are computed for each row and for each column, equal to 1 if there is an odd number of 1s in the row of column, and 0 if it is an even number. The result for the above message looks like:

>1 0 1 0 0 1 1
>1 0 0 1 0 0 0
>0 1 1 1 0 1 0
>1 0 0 0 0 1 0
>1 1 0 0 0 1

Since the 1st row, and 1st, 2nd and 6th column each have an odd number of 1s in them, and the others all do not.

Then the whole message is sent, including the parity bits. This is arranged as:

> message + row_parities + column_parities
> 101001100100011101100001 + 1000 + 110001
> 1010011001000111011000011000110001

If an error occurs in transmission, the parity bit for a column and row will be incorrect, which can be used to identify and correct the error. If a row parity bit is incorrect, but all column bits are correct, then we can assume the row parity bit was the one flipped, and likewise if a column is wrong but all rows are correct.

 Your Task:

Create a function correct, which takes in integers M and N, and a string of bits where the first M\*N represent the content of the message, the next M represent the parity bits for the rows, and the final N represent the parity bits for the columns. A single-bit error may or may not have appeared in the bit array.

The function should check to see if there is a single-bit error in the coded message, correct it if it exists, and return the corrected string of bits.

import pandas as pd

def correct(m,n,s):
    s,r,c = s[:m*n], s[m*n:m*n+m], s[-n:]
    arr = pd.np.array(list(s)).reshape(m,n)
    df = pd.DataFrame(arr)
    row = ''.join(df.eq('1').sum(1).mod(2).astype(str))
    col = ''.join(df.eq('1').sum(0).mod(2).astype(str))
    if r != row and c != col:
        for idx, (i,j) in enumerate(zip(row,r)):
            if i != j:
                x = idx
        for idx, (i,j) in enumerate(zip(col,c)):
            if i!= j:
                y = idx

        df = df.astype(int)
        df.loc[x,y] ^= 1
        return ''.join(df.astype(str).values.ravel()) + r + c

    else:
        return ''.join(df.values.ravel()) + row + col


Solve in Python:
A tennis tournament is about to take place with $N$ players participating in it.
Every player plays with every other player exactly once and there are no ties. That is, every match has a winner and a loser.
With Naman's birthday approaching, he wants to make sure that each player wins the same number of matches so that nobody gets disheartened.
Your task is to determine if such a scenario can take place and if yes find one such scenario.

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

-----Output:-----
- If it's impossible for everyone to win the same number of matches, print "NO" (without quotes).
- Otherwise print "YES" (without quotes) and then print $N$ lines , each line should consist of a string containing only 0s and 1s and should be of size $N$.
- If the jth character in the ith line is 1 then it means in the match between $i$ and $j$ , $i$ wins.
- You will get a WA if the output does not correspond to a valid tournament, or if the constraints are not satisfied.
- You will get also WA verdict if any 2 lines have contradicting results or if a player beats himself.

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

-----Subtasks-----
- 10 points : $2 \leq N \leq 6$
- 90 points :  Original Constraints.

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

-----Sample Output:-----
YES
010
001
100
NO

-----Explanation:-----
One such scenario for $N$ = $3$ is when player $1$ beats player $2$, player $2$ to beats player $3$ and player $3$ beats player $1$. Here all players win exactly $1$ match.

# cook your dish here

def calc(n) :
 a = n * (n-1)
 a = int(a/2)
 return a

t = int(input())
tt = 0
while tt < t :
 tt = tt + 1
 n = int(input())
 num = calc(n)
 if num%n != 0 :
  print("NO")
 else :
  win = int(num/n)
  print("YES")
  i = 0
  while i < n :
   i = i + 1
   j = i
   str = ""
   k = 0
   while k < n :
    str = str + "0"
    k = k + 1
   k = 0
   while k < win :
    if (j+k)%n==0 :
     str = '1' + str[1:n]
    elif (j+k)%n==(n-1) :
     str = str[:n-1] + "1"
    else :
     kkk = (j+k)%n
     str = str[0:kkk] + "1" + str[kkk+1:]
    k = k + 1
   print(str)


Solve in Python:
A tourist is visiting Byteland. The tourist knows English very well. The language of Byteland is rather different from English. To be exact it differs in following points:

- Bytelandian alphabet has the same letters as English one, but possibly different in meaning. Like 'A' in Bytelandian may be 'M' in English. However this does not mean that 'M' in Bytelandian must be 'A' in English. More formally, Bytelindian alphabet is a permutation of English alphabet. It will be given to you and could be any possible permutation. Don't assume any other condition.
- People of Byteland don't like to use invisible character for separating words. Hence instead of space (' ') they use underscore ('_'). Other punctuation symbols, like '?', '!' remain the same as in English.

The tourist is carrying "The dummies guide to Bytelandian", for translation. The book is serving his purpose nicely. But he is addicted to sharing on BaceFook, and shares his numerous conversations in Byteland on it. The conversations are rather long, and it is quite tedious to translate for his English friends, so he asks you to help him by writing a program to do the same.

-----Input-----
The first line of the input contains an integer T, denoting the length of the conversation, and the string M, denoting the English translation of Bytelandian string "abcdefghijklmnopqrstuvwxyz". T and M are separated by exactly one space. Then T lines follow, each containing a Bytelandian sentence S which you should translate into English. See constraints for details.

-----Output-----
For each of the sentence in the input, output its English translation on a separate line. Replace each underscores ('_') with a space (' ') in the output. Each punctuation symbol (see below) should remain the same. Note that the uppercase letters in Bytelandian remain uppercase in English, and lowercase letters remain lowercase. See the example and its explanation for clarity.

-----Constraints-----

- 1 ≤ T ≤ 100
- M is a permutation of "abcdefghijklmnopqrstuvwxyz"
- Each sentence is...

# cook your dish here
try:
 t,s=input().split()
 for i in range(int(t)):
  s1=eval(input())
  s1=s1.replace("_"," ")

  aa=""
  for i in s1:
   if(i.isalpha()==True):
    if(i.isupper()==True):
     i=i.lower()
     g=ord(i)%97
     ss1=s[g].upper()
     aa+=ss1
    else:

     g=ord(i)%97
     aa+=s[g]
   else:
    aa+=i
  print(aa)
except:pass


Solve in Python:
A transaction is possibly invalid if:

the amount exceeds $1000, or;
if it occurs within (and including) 60 minutes of another transaction with the same name in a different city.

Each transaction string transactions[i] consists of comma separated values representing the name, time (in minutes), amount, and city of the transaction.
Given a list of transactions, return a list of transactions that are possibly invalid.  You may return the answer in any order.

Example 1:
Input: transactions = ["alice,20,800,mtv","alice,50,100,beijing"]
Output: ["alice,20,800,mtv","alice,50,100,beijing"]
Explanation: The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too.
Example 2:
Input: transactions = ["alice,20,800,mtv","alice,50,1200,mtv"]
Output: ["alice,50,1200,mtv"]

Example 3:
Input: transactions = ["alice,20,800,mtv","bob,50,1200,mtv"]
Output: ["bob,50,1200,mtv"]

Constraints:

transactions.length <= 1000
Each transactions[i] takes the form "{name},{time},{amount},{city}"
Each {name} and {city} consist of lowercase English letters, and have lengths between 1 and 10.
Each {time} consist of digits, and represent an integer between 0 and 1000.
Each {amount} consist of digits, and represent an integer between 0 and 2000.

from collections import defaultdict
class Transaction:
    def __init__(self, name, time, amount, city):
        self.name = name
        self.time = int(time)
        self.amount = int(amount)
        self.city = city

class Solution:
    def invalidTransactions(self, transactions: List[str]) -> List[str]:
        invalid = []
        trans_index = defaultdict(list)
        trans = []
        for t in transactions:
            name, time, amount, city = t.split(',')
            trans.append(Transaction(name, time, amount, city))
        trans.sort(key = lambda x: x.time)

        s = set()
        for i in range(len(trans)):
            t1 = trans[i]
            if t1.amount > 1000:
                s.add(\"{},{},{},{}\".format(t1.name, t1.time, t1.amount, t1.city))
            for j in range(i + 1, len(trans)):
                t2 = trans[j]
                if t2.time - t2.time > 60:
                    break
                if t2.name == t1.name and t2.time - t1.time <= 60 and t1.city != t2.city:
                    s.add(\"{},{},{},{}\".format(t1.name, t1.time, t1.amount, t1.city))
                    s.add(\"{},{},{},{}\".format(t2.name, t2.time, t2.amount, t2.city))
        return list(s)


Solve in Python:
A traveling salesman has to visit clients. He got each client's address e.g. `"432 Main Long Road St. Louisville OH 43071"` as a list.

The basic zipcode format usually consists of two capital letters followed by a white space and five digits.
The list of clients to visit was given as a string of all addresses, each separated from the others by a comma, e.g. :

`"123 Main Street St. Louisville OH 43071,432 Main Long Road St. Louisville OH 43071,786 High Street Pollocksville NY 56432"`.

To ease his travel he wants to group the list by zipcode.
# Task
The function `travel` will take two parameters `r` (addresses' list of all clients' as a string) and `zipcode` and returns a string in the following format:

`zipcode:street and town,street and town,.../house number,house number,...`

The street numbers must be in the same order as the streets where they belong.

If a given zipcode doesn't exist in the list of clients' addresses return `"zipcode:/"`

# Examples
```
r = "123 Main Street St. Louisville OH 43071,432 Main Long Road St. Louisville OH 43071,786 High Street Pollocksville NY 56432"

travel(r, "OH 43071") --> "OH 43071:Main Street St. Louisville,Main Long Road St. Louisville/123,432"

travel(r, "NY 56432") --> "NY 56432:High Street Pollocksville/786"

travel(r, "NY 5643") --> "NY 5643:/"
```

# Note for Elixir:
In Elixir the empty addresses' input is an empty *list*, not an empty string.

# Note:
You can see a few addresses and zipcodes in the test cases.

def travel(r, zipcode):
    streets = []
    nums = []
    addresses = r.split(',')
    for address in addresses:
        if ' '.join(address.split()[-2:]) == zipcode:
            streets.append(' '.join(address.split()[1:-2]))
            nums += address.split()[:1]
    return '{}:{}/{}'.format(zipcode, ','.join(streets), ','.join(nums))


Solve in Python:
A tree is a graph with n vertices and exactly n - 1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.

A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.

You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to v_{i}. In one move you can apply the following operation:  Select the subtree of the given tree that includes the vertex with number 1.  Increase (or decrease) by one all the integers which are written on the vertices of that subtree.

Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero.

-----Input-----

The first line of the input contains n (1 ≤ n ≤ 10^5). Each of the next n - 1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ n; a_{i} ≠ b_{i}) indicating there's an edge between vertices a_{i} and b_{i}. It's guaranteed that the input graph is a tree.

The last line of the input contains a list of n space-separated integers v_1, v_2, ..., v_{n} (|v_{i}| ≤ 10^9).

-----Output-----

Print the minimum number of operations needed to solve the task.

Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

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

Output
3

n = int(input())
r = [[] for i in range(n + 1)]
r[1] = [0]
for i in range(n - 1):
    a, b = map(int, input().split())
    r[a].append(b)
    r[b].append(a)
t = list(map(int, input().split()))
u, v = [0] * (n + 1), [0] * (n + 1)
for i, j in enumerate(t, 1):
    if j < 0: u[i] = - j
    else: v[i] = j
t, p = [1], [0] * (n + 1)
while t:
    a = t.pop()
    for b in r[a]:
        if p[b]: continue
        p[b] = a
        t.append(b)
k = [len(t) for t in r]
t = [a for a in range(2, n + 1) if k[a] == 1]
x, y = [0] * (n + 1), [0] * (n + 1)
while t:
    a = t.pop()
    b = p[a]
    x[b] = max(x[b], u[a])
    y[b] = max(y[b], v[a])
    k[b] -= 1
    if k[b] == 1:
        t.append(b)
        if u[b] > 0:
            if x[b] - y[b] > u[b]:
                u[b], v[b] = x[b], x[b] - u[b]
            else: u[b], v[b] = y[b] + u[b], y[b]
        else:
            if y[b] - x[b] > v[b]:
                u[b], v[b] = y[b] - v[b], y[b]
            else: u[b], v[b] = x[b], x[b] + v[b]
print(u[1] + v[1])


Solve in Python:
A tree is an undirected connected graph without cycles.

Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p_1, p_2, ..., p_{n}, where p_{i} denotes a parent of vertex i (here, for convenience a root is considered its own parent). [Image] For this rooted tree the array p is [2, 3, 3, 2].

Given a sequence p_1, p_2, ..., p_{n}, one is able to restore a tree:  There must be exactly one index r that p_{r} = r. A vertex r is a root of the tree.  For all other n - 1 vertices i, there is an edge between vertex i and vertex p_{i}.

A sequence p_1, p_2, ..., p_{n} is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.

You are given a sequence a_1, a_2, ..., a_{n}, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.

-----Input-----

The first line of the input contains an integer n (2 ≤ n ≤ 200 000) — the number of vertices in the tree.

The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ n).

-----Output-----

In the first line print the minimum number of elements to change, in order to get a valid sequence.

In the second line, print any valid sequence possible to get from (a_1, a_2, ..., a_{n}) in the minimum number of changes. If there are many such sequences, any of them will be accepted.

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

Output
1
2 3 4 4

Input
5
3 2 2 5 3

Output
0
3 2 2 5 3

Input
8
2 3 5 4 1 6 6 7

Output
2
2 3 7 8 1 6 6 7

-----Note-----

In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p_4 = 4), which you can see on...

n = int(input())
arr = list(map(int, input().split(' ')))
root=-1
for i,a in enumerate(arr) :
    if i == a-1 :
        root = i
        break
v = [False]*len(arr)
if root>-1 :
    v[root]=True
ans = 0
for i,a in enumerate(arr) :
    if v[i] :
        continue
    v[i]= True
    l=[i]
    a-=1
    while not v[a] :
        l.append(a)
        v[a]=True
        a=arr[a]-1
    if a in l: #new cycle
        if root==-1:
            arr[a]=a+1
            root=a
            ans+=1
        else :
            arr[a]=root+1
            ans+=1
print(ans)
print(' '.join(map(str,arr)))


Solve in Python:
A triangle is called an equable triangle if its area equals its perimeter. Return `true`, if it is an equable triangle, else return `false`. You will be provided with the length of sides of the triangle. Happy Coding!

def equable_triangle(a, b, c):
    p = a + b + c
    ph = p / 2
    return p * p == ph * (ph - a) * (ph - b) * (ph - c)


Solve in Python:
A trick I learned in elementary school to determine whether or not a number was divisible by three is to add all of the integers in the number together and to divide the resulting sum by three. If there is no remainder from dividing the sum by three, then the original number is divisible by three as well.

Given a series of numbers as a string, determine if the number represented by the string is divisible by three.

You can expect all test case arguments to be strings representing values greater than 0.

Example:

```
"123"      -> true
"8409"     -> true
"100853"   -> false
"33333333" -> true
"7"        -> false
```

def divisible_by_three(st):
    return (sum([int(i) for i in st]) % 3) == 0