Muennighoff/xP3x-sample huggingface dataset:
inputs: Solve in Python:
This kata is the second part of a series: [Neighbourhood kata collection](https://www.codewars.com/collections/5b2f4db591c746349d0000ce). If this one is to easy you can try out the harder Katas.;)

___
The neighbourhood of a cell (in a matrix) are cells that are near to it. There are two popular types:
- The [Moore neighborhood](https://en.wikipedia.org/wiki/Moore_neighborhood) are eight cells which surround a given cell.
- The [Von Neumann neighborhood](https://en.wikipedia.org/wiki/Von_Neumann_neighborhood) are four cells which share a border with the given cell.

___

# Task
Given a neighbourhood type (`"moore"` or `"von_neumann"`), a 2D matrix (a list of lists) and a pair of coordinates, return the list of neighbours of the given cell.

Notes:
- The order of the elements in the output list is not important. 
- If the input indexes are outside the matrix, return an empty list.
- If the the matrix is empty, return an empty list.
- Order of the indices: The first index should be applied for the outer/first matrix layer. The last index for the most inner/last layer. `coordinates = (m, n)` should be apllied like `mat[m][n]`

___

## Examples
```
\ n   0    1    2    3    4
m  --------------------------
0  |  0 |  1 |  2 |  3 |  4 |
1  |  5 |  6 |  7 |  8 |  9 |
2  | 10 | 11 | 12 | 13 | 14 |
3  | 15 | 16 | 17 | 18 | 19 |
4  | 20 | 21 | 22 | 23 | 24 |
   --------------------------

get_neighborhood("moore", mat, (1,1)) == [0, 1, 2, 5, 7, 10, 11, 12]
get_neighborhood("moore", mat, (0,0)) == [1, 6, 5]
get_neighborhood("moore", mat, (4,2)) == [21, 16, 17, 18, 23]
get_neighborhood("von_neumann", mat, (1,1)) == [1, 5, 7, 11]
get_neighborhood("von_neumann", mat, (0,0)) == [1, 5]
get_neighborhood("von_neumann", mat, (4,2)) == [21, 17, 23]
```
___

Translations are appreciated.^^

If you like chess take a look at [Chess Aesthetics](https://www.codewars.com/kata/5b574980578c6a6bac0000dc)

If you like puzzles and take a look at [Rubik's cube](https://www.codewars.com/kata/5b3bec086be5d8893000002e)
targets: def get_neighbourhood(typ, arr, coordinates):
    
    def isInside(x,y): return 0 <= x < len(arr) and 0 <= y < len(arr[0])
    
    x,y = coordinates
    if not isInside(x,y): return []
    
    neigh = ( [(dx, dy) for dx in range(-1,2) for dy in range(-1,2) if (dx,dy) != (0,0)]
                  if typ == 'moore' else [(0,1), (0,-1), (1,0), (-1,0)] )
    
    return [ arr[a][b] for a,b in ((x+dx,y+dy) for dx,dy in neigh) if isInside(a,b) ]
inputs: Solve in Python:
Write a comparator for a list of phonetic words for the letters of the [greek alphabet](https://en.wikipedia.org/wiki/Greek_alphabet).

A comparator is:
> *a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument*

*(source: https://docs.python.org/2/library/functions.html#sorted)*

The greek alphabet is preloded for you as `greek_alphabet`:

```python
greek_alphabet = (
    'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', 
    'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', 
    'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma',
    'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega')
```

## Examples

```python
greek_comparator('alpha', 'beta')   <  0
greek_comparator('psi', 'psi')      == 0
greek_comparator('upsilon', 'rho')  >  0
```
targets: greek_alphabet = (
    'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta',
    'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu',
    'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma',
    'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega')


def greek_comparator(lhs, rhs):
    # the tuple greek_alphabet is defined in the nonlocal namespace
    if greek_alphabet.index(lhs) < greek_alphabet.index(rhs):
        return -(greek_alphabet.index(rhs) - greek_alphabet.index(lhs))
    elif greek_alphabet.index(lhs) == greek_alphabet.index(rhs):
        return 0
    else:
        return greek_alphabet.index(lhs) - greek_alphabet.index(rhs)
inputs: I found an interesting problem on https://atcoder.jp/contests/abc137/tasks/abc137_d:
There are N one-off jobs available. If you take the i-th job and complete it, you will earn the reward of B_i after A_i days from the day you do it.
You can take and complete at most one of these jobs in a day.
However, you cannot retake a job that you have already done.
Find the maximum total reward that you can earn no later than M days from today.
You can already start working today.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq N \leq 10^5
 - 1 \leq M \leq 10^5
 - 1 \leq A_i \leq 10^5
 - 1 \leq B_i \leq 10^4

-----Input-----
Input is given from Standard Input in the following format:
N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

-----Output-----
Print the maximum total reward that you can earn no later than M days from today.

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

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

You can earn the total reward of 5 by taking the jobs as follows:
 - Take and complete the first job today. You will earn the reward of 3 after four days from today.
 - Take and complete the third job tomorrow. You will earn the reward of 2 after two days from tomorrow, that is, after three days from today.

I tried it in Python, but could not do it. Can you solve it?
targets: import sys, math
from functools import lru_cache
import numpy as np
import heapq
from collections import defaultdict
sys.setrecursionlimit(10**9)
MOD = 10**9+7

def input():
    return sys.stdin.readline()[:-1]

def mi():
    return list(map(int, input().split()))

def ii():
    return int(input())

def i2(n):
    tmp = [list(mi()) for i in range(n)]
    return [list(i) for i in zip(*tmp)]


def lcm(a, b):
    return a*b//math.gcd(a, b)


def main():
    N, M = mi()
    A, B = i2(N)
    ans = 0

    d = defaultdict(list)
    for i in range(N):
        d[A[i]].append(B[i])

    h = []
    heapq.heapify(h)

    for i in range(1, M+1):
        for v in d[i]:
            heapq.heappush(h, -v)
        if h:
            ans -= heapq.heappop(h)
        else:
            continue

    print(ans)



def __starting_point():
    main()

__starting_point()
inputs: Solve in Python:
This is a simplified version of the task Toy Train. These two versions differ only in the constraints. Hacks for this version are disabled.

Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of $n$ stations, enumerated from $1$ through $n$. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station $i$ is station $i+1$ if $1 \leq i < n$ or station $1$ if $i = n$. It takes the train $1$ second to travel to its next station as described.

Bob gave Alice a fun task before he left: to deliver $m$ candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from $1$ through $m$. Candy $i$ ($1 \leq i \leq m$), now at station $a_i$, should be delivered to station $b_i$ ($a_i \neq b_i$). [Image] The blue numbers on the candies correspond to $b_i$ values. The image corresponds to the $1$-st example. 

The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.

Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.


-----Input-----

The first line contains two space-separated integers $n$ and $m$ ($2 \leq n \leq 100$; $1 \leq m \leq 200$) — the number of stations and the number of candies, respectively.

The $i$-th of the following $m$ lines contains two space-separated integers $a_i$ and $b_i$ ($1 \leq a_i, b_i \leq n$; $a_i \neq b_i$) — the station that initially contains candy $i$ and the destination station of the candy, respectively.


-----Output-----

In the first and only line,...
targets: def __starting_point():
	from sys import stdin
	n, m = list(map(int, stdin.readline().split()))
	c = {}
	for _ in range(m):
		a, b = list(map(int, stdin.readline().split()))
		if (a-1) not in c.keys():
			c[a-1] = []
		x = b-a + (n if b<a else 0)
		c[a-1].append(x)

	for k, l in c.items():
		c[k] = min(l) + ((len(l)-1)*n)

	out_ = []
	for x in range(n):
		res = 0
		for y, v in c.items():
			s = y-x + (n if y<x else 0)
			res = max(res, v+s)
		out_.append(res)

	print(*out_)
__starting_point()
inputs: I found an interesting problem on https://www.codewars.com/kata/565f5825379664a26b00007c:
```if-not:julia,racket
Write a function that returns the total surface area and volume of a box as an array: `[area, volume]`
```
```if:julia
Write a function that returns the total surface area and volume of a box as a tuple: `(area, volume)`
```
```if:racket
Write a function that returns the total surface area and volume of a box as a list: `'(area, volume)`
```

I tried it in Python, but could not do it. Can you solve it?
targets: def get_size(w,h,d):
    volume=w*h*d
    total_surface_area= 2*(w*h+h*d+w*d)
    return [total_surface_area,volume]
inputs: I found an interesting problem on https://www.codewars.com/kata/5254ca2719453dcc0b00027d:
In this kata you have to create all permutations of an input string and remove duplicates, if present. This means, you have to shuffle all letters from the input in all possible orders.

Examples:

```python
permutations('a'); # ['a']
permutations('ab'); # ['ab', 'ba']
permutations('aabb'); # ['aabb', 'abab', 'abba', 'baab', 'baba', 'bbaa']
```

The order of the permutations doesn't matter.

I tried it in Python, but could not do it. Can you solve it?
targets: import itertools

def permutations(string):
    return list("".join(p) for p in set(itertools.permutations(string)))
inputs: I found an interesting problem on https://www.codewars.com/kata/583601518d3b9b8d3b0000c9:
Your task in this Kata is to emulate text justify right in monospace font. You will be given a single-lined text and the expected justification width. The longest word will never be greater than this width.

Here are the rules:

- Use spaces to fill in the gaps on the left side of the words.
- Each line should contain as many words as possible.
- Use '\n' to separate lines.
- Gap between words can't differ by more than one space.
- Lines should end with a word not a space.
- '\n' is not included in the length of a line.
- Last line should not contain '\n'

Example with width=30:

```
        Bacon ipsum dolor amet
excepteur ut kevin burgdoggen,
   shankle cupim dolor officia
       ground round id ullamco
   deserunt nisi. Commodo tail
    qui salami, brisket boudin 
tri-tip. Labore flank laboris,
  cow enim proident aliqua sed
      hamburger consequat. Sed
     consequat ut non bresaola
   capicola shoulder excepteur
 veniam, bacon kevin. Pastrami
   shank laborum est excepteur
 non eiusmod bresaola flank in
nostrud. Corned beef ex pig do
   kevin filet mignon in irure
 deserunt ipsum qui duis short
        loin. Beef ribs dolore
  meatball officia rump fugiat
  in enim corned beef non est.
```

If you enjoyed this one and want more of a challenge try https://www.codewars.com/kata/text-align-justify/python

If you like bacon ipsum https://baconipsum.com

I tried it in Python, but could not do it. Can you solve it?
targets: def align_right(text,width):
    k = text.split()
    
    out = ''
    last = []
    for x in k:
        if len(x + out) <= width:
            out += x + ' '
        else:
            last.append(out)
            out = x+' '
    
    last.append(out)
    return '\n'.join(' ' * (width - len(x.rstrip())) + x.rstrip() for x in last)
inputs: I found an interesting problem on https://codeforces.com/problemset/problem/1185/A:
Polycarp decided to relax on his weekend and visited to the performance of famous ropewalkers: Agafon, Boniface and Konrad.

The rope is straight and infinite in both directions. At the beginning of the performance, Agafon, Boniface and Konrad are located in positions $a$, $b$ and $c$ respectively. At the end of the performance, the distance between each pair of ropewalkers was at least $d$.

Ropewalkers can walk on the rope. In one second, only one ropewalker can change his position. Every ropewalker can change his position exactly by $1$ (i. e. shift by $1$ to the left or right direction on the rope). Agafon, Boniface and Konrad can not move at the same time (Only one of them can move at each moment). Ropewalkers can be at the same positions at the same time and can "walk past each other".

You should find the minimum duration (in seconds) of the performance. In other words, find the minimum number of seconds needed so that the distance between each pair of ropewalkers can be greater or equal to $d$.

Ropewalkers can walk to negative coordinates, due to the rope is infinite to both sides.


-----Input-----

The only line of the input contains four integers $a$, $b$, $c$, $d$ ($1 \le a, b, c, d \le 10^9$). It is possible that any two (or all three) ropewalkers are in the same position at the beginning of the performance.


-----Output-----

Output one integer — the minimum duration (in seconds) of the performance.


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

Output
2

Input
3 1 5 6

Output
8

Input
8 3 3 2

Output
2

Input
2 3 10 4

Output
3



-----Note-----

In the first example: in the first two seconds Konrad moves for 2 positions to the right (to the position $8$), while Agafon and Boniface stay at their positions. Thus, the distance between Agafon and Boniface will be $|5 - 2| = 3$, the distance between Boniface and Konrad will be $|2 - 8| = 6$ and the distance between Agafon and Konrad will be $|5 - 8| = 3$. Therefore, all three pairwise distances will be at least $d=3$, so the performance could be finished...

I tried it in Python, but could not do it. Can you solve it?
targets: a, b, c, d = list(map(int, input().split()))
s = [a, b, c]
s.sort()
a, b, c = s
print(max(0, a - b + d) + max(0, b - c + d))
inputs: Solve in Python:
The math faculty of Berland State University has suffered the sudden drop in the math skills of enrolling students. This year the highest grade on the entrance math test was 8. Out of 100! Thus, the decision was made to make the test easier.

Future students will be asked just a single question. They are given a sequence of integer numbers $a_1, a_2, \dots, a_n$, each number is from $1$ to $3$ and $a_i \ne a_{i + 1}$ for each valid $i$. The $i$-th number represents a type of the $i$-th figure:

  circle;  isosceles triangle with the length of height equal to the length of base;  square. 

The figures of the given sequence are placed somewhere on a Cartesian plane in such a way that:

  $(i + 1)$-th figure is inscribed into the $i$-th one;  each triangle base is parallel to OX;  the triangle is oriented in such a way that the vertex opposite to its base is at the top;  each square sides are parallel to the axes;  for each $i$ from $2$ to $n$ figure $i$ has the maximum possible length of side for triangle and square and maximum radius for circle. 

Note that the construction is unique for some fixed position and size of just the first figure.

The task is to calculate the number of distinct points (not necessarily with integer coordinates) where figures touch. The trick is, however, that the number is sometimes infinite. But that won't make the task difficult for you, will it?

So can you pass the math test and enroll into Berland State University?


-----Input-----

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

The second line contains $n$ integer numbers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 3$, $a_i \ne a_{i + 1}$) — types of the figures.


-----Output-----

The first line should contain either the word "Infinite" if the number of distinct points where figures touch is infinite or "Finite" otherwise.

If the number is finite than print it in the second line. It's guaranteed that the number fits into 32-bit integer type.


-----Examples-----
Input
3
2 1...
targets: CIRCLE = 1
RECTANGLE = 2
SQUARE = 3


def main():
    n = int(input())
    a = list(map(int, input().split()))
    answer = 0

    for i in range(1, n):
        if a[i - 1] == CIRCLE:
            if a[i] == RECTANGLE:
                answer += 3
                if i > 1 and a[i - 2] == SQUARE:
                    answer -= 1
            else:
                answer += 4
        elif a[i - 1] == RECTANGLE:
            if a[i] == CIRCLE:
                answer += 3
            else:
                print('Infinite')
                return
        elif a[i - 1] == SQUARE:
            if a[i] == CIRCLE:
                answer += 4
            else:
                print('Infinite')
                return

    print('Finite')
    print(answer)


def __starting_point():
    main()

__starting_point()
inputs: Solve in Python:
Mislove had an array $a_1$, $a_2$, $\cdots$, $a_n$ of $n$ positive integers, but he has lost it. He only remembers the following facts about it:



 The number of different numbers in the array is not less than $l$ and is not greater than $r$;

 For each array's element $a_i$ either $a_i = 1$ or $a_i$ is even and there is a number $\dfrac{a_i}{2}$ in the array.

For example, if $n=5$, $l=2$, $r=3$ then an array could be $[1,2,2,4,4]$ or $[1,1,1,1,2]$; but it couldn't be $[1,2,2,4,8]$ because this array contains $4$ different numbers; it couldn't be $[1,2,2,3,3]$ because $3$ is odd and isn't equal to $1$; and it couldn't be $[1,1,2,2,16]$ because there is a number $16$ in the array but there isn't a number $\frac{16}{2} = 8$.

According to these facts, he is asking you to count the minimal and the maximal possible sums of all elements in an array. 


-----Input-----

The only input line contains three integers $n$, $l$ and $r$ ($1 \leq n \leq 1\,000$, $1 \leq l \leq r \leq \min(n, 20)$) — an array's size, the minimal number and the maximal number of distinct elements in an array.


-----Output-----

Output two numbers — the minimal and the maximal possible sums of all elements in an array.


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

Output
5 7

Input
5 1 5

Output
5 31



-----Note-----

In the first example, an array could be the one of the following: $[1,1,1,2]$, $[1,1,2,2]$ or $[1,2,2,2]$. In the first case the minimal sum is reached and in the last case the maximal sum is reached.

In the second example, the minimal sum is reached at the array $[1,1,1,1,1]$, and the maximal one is reached at the array $[1,2,4,8,16]$.
targets: n,l,r=map(int,input().split())
ans1,ans2=0,0
c=1
for i in range(n):
    if i>(n-l):
        c*=2
    ans1+=c
c=1
for i in range(n):
    ans2+=c
    if i<(r-1):
        c*=2
print(ans1,ans2)
inputs: Solve in Python:
Pasha loves his phone and also putting his hair up... But the hair is now irrelevant.

Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of n row with m pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choose any pixel and color it black. In particular, he can choose the pixel that is already black, then after the boy's move the pixel does not change, that is, it remains black. Pasha loses the game when a 2 × 2 square consisting of black pixels is formed. 

Pasha has made a plan of k moves, according to which he will paint pixels. Each turn in his plan is represented as a pair of numbers i and j, denoting respectively the row and the column of the pixel to be colored on the current move.

Determine whether Pasha loses if he acts in accordance with his plan, and if he does, on what move the 2 × 2 square consisting of black pixels is formed.


-----Input-----

The first line of the input contains three integers n, m, k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 10^5) — the number of rows, the number of columns and the number of moves that Pasha is going to perform. 

The next k lines contain Pasha's moves in the order he makes them. Each line contains two integers i and j (1 ≤ i ≤ n, 1 ≤ j ≤ m), representing the row number and column number of the pixel that was painted during a move.


-----Output-----

If Pasha loses, print the number of the move when the 2 × 2 square consisting of black pixels is formed.

If Pasha doesn't lose, that is, no 2 × 2 square consisting of black pixels is formed during the given k moves, print 0.


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

Output
4

Input
2 3 6
2 3
2 2
1 3
2 2
1 2
1 1

Output
5

Input
5 3 7
2 3
1 2
1 1
4 1
3 1
5 3
3 2

Output
0
targets: __author__ = 'default'
def TaskA():
    #fl = open('TaskA.txt','r')
    n, m, k = list(map(int,input().split()))
    pole = [0]*n
    lose = False
    cmplt = True
    for i in range(n):
        pole[i] = [0]*m
    for i in range(k):
        rdl = list(map(int,input().split()))
        pole[rdl[0]-1][rdl[1]-1] = 1
        lose = check(pole, rdl[0]-1,rdl[1]-1)
        if lose and cmplt:
            cmplt = False
            print(i+1)
    #fl.close()
    if not lose and cmplt:
        print(0)
def check(pole, index1,index):
    if index1-1 >= 0 and index+1 < len(pole[0]):
        if pole[index1][index+1] == 1 and pole[index1-1][index] == 1 and pole[index1-1][index+1] == 1:
            return True
    if index1+1 < len(pole) and index-1>0  >= 0:
        if pole[index1][index-1] == 1 and pole[index1+1][index-1] == 1 and pole[index1+1][index] == 1:
            return True
    if index1-1 >= 0 and index-1 >= 0:
        if pole[index1-1][index] == 1 and pole[index1-1][index-1] == 1 and pole[index1][index-1] == 1:
            return True
    if index1+1 < len(pole) and index+1 < len(pole[0]):
        if pole[index1+1][index] == 1 and pole[index1+1][index+1] == 1 and pole[index1][index+1]:
            return True

TaskA()
inputs: I found an interesting problem on https://codeforces.com/problemset/problem/743/A:
Vladik is a competitive programmer. This year he is going to win the International Olympiad in Informatics. But it is not as easy as it sounds: the question Vladik face now is to find the cheapest way to get to the olympiad.

Vladik knows n airports. All the airports are located on a straight line. Each airport has unique id from 1 to n, Vladik's house is situated next to the airport with id a, and the place of the olympiad is situated next to the airport with id b. It is possible that Vladik's house and the place of the olympiad are located near the same airport. 

To get to the olympiad, Vladik can fly between any pair of airports any number of times, but he has to start his route at the airport a and finish it at the airport b.

Each airport belongs to one of two companies. The cost of flight from the airport i to the airport j is zero if both airports belong to the same company, and |i - j| if they belong to different companies.

Print the minimum cost Vladik has to pay to get to the olympiad.


-----Input-----

The first line contains three integers n, a, and b (1 ≤ n ≤ 10^5, 1 ≤ a, b ≤ n) — the number of airports, the id of the airport from which Vladik starts his route and the id of the airport which he has to reach. 

The second line contains a string with length n, which consists only of characters 0 and 1. If the i-th character in this string is 0, then i-th airport belongs to first company, otherwise it belongs to the second.


-----Output-----

Print single integer — the minimum cost Vladik has to pay to get to the olympiad.


-----Examples-----
Input
4 1 4
1010

Output
1
Input
5 5 2
10110

Output
0


-----Note-----

In the first example Vladik can fly to the airport 2 at first and pay |1 - 2| = 1 (because the airports belong to different companies), and then fly from the airport 2 to the airport 4 for free (because the airports belong to the same company). So the cost of the whole flight is equal to 1. It's impossible to get to the olympiad for free, so the answer is equal to 1. 

In the second...

I tried it in Python, but could not do it. Can you solve it?
targets: read = lambda: list(map(int, input().split()))
n, a, b = read()
s = ' ' + input()
if s[a] == s[b]:
    print(0)
    return
else:
    print(1)
inputs: I found an interesting problem on https://codeforces.com/problemset/problem/870/B:
You are given an array a_1, a_2, ..., a_{n} consisting of n integers, and an integer k. You have to split the array into exactly k non-empty subsegments. You'll then compute the minimum integer on each subsegment, and take the maximum integer over the k obtained minimums. What is the maximum possible integer you can get?

Definitions of subsegment and array splitting are given in notes.


-----Input-----

The first line contains two integers n and k (1 ≤ k ≤ n ≤  10^5) — the size of the array a and the number of subsegments you have to split the array to.

The second line contains n integers a_1,  a_2,  ...,  a_{n} ( - 10^9  ≤  a_{i} ≤  10^9).


-----Output-----

Print single integer — the maximum possible integer you can get if you split the array into k non-empty subsegments and take maximum of minimums on the subsegments.


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

Output
5

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

Output
-5



-----Note-----

A subsegment [l,  r] (l ≤ r) of array a is the sequence a_{l},  a_{l} + 1,  ...,  a_{r}.

Splitting of array a of n elements into k subsegments [l_1, r_1], [l_2, r_2], ..., [l_{k}, r_{k}] (l_1 = 1, r_{k} = n, l_{i} = r_{i} - 1 + 1 for all i > 1) is k sequences (a_{l}_1, ..., a_{r}_1), ..., (a_{l}_{k}, ..., a_{r}_{k}).

In the first example you should split the array into subsegments [1, 4] and [5, 5] that results in sequences (1, 2, 3, 4) and (5). The minimums are min(1, 2, 3, 4) = 1 and min(5) = 5. The resulting maximum is max(1, 5) = 5. It is obvious that you can't reach greater result.

In the second example the only option you have is to split the array into one subsegment [1, 5], that results in one sequence ( - 4,  - 5,  - 3,  - 2,  - 1). The only minimum is min( - 4,  - 5,  - 3,  - 2,  - 1) =  - 5. The resulting maximum is  - 5.

I tried it in Python, but could not do it. Can you solve it?
targets: n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
if k == 1:
    print(min(a))
elif k == 2:
    b = [a[0]] * (n - 1)
    for i in range(1, n - 1):
        b[i] = min(b[i - 1], a[i])
    c = [a[n - 1]] * (n - 1)
    for i in range(n - 3, -1, -1):
        c[i] = min(c[i + 1], a[i + 1])
    ans = - 10 ** 10
    for i in range(n - 1):
        ans = max(ans, max(b[i], c[i]))
    print(ans)
else:
    print(max(a))
inputs: Solve in Python:
Shubham has a binary string $s$. A binary string is a string containing only characters "0" and "1".

He can perform the following operation on the string any amount of times:   Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa. 

A string is called good if it does not contain "010" or "101" as a subsequence  — for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string.

What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.

A string $a$ is a subsequence of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters.


-----Input-----

The first line of the input contains a single integer $t$ $(1\le t \le 100)$ — the number of test cases.

Each of the next $t$ lines contains a binary string $s$ $(1 \le |s| \le 1000)$.


-----Output-----

For every string, output the minimum number of operations required to make it good.


-----Example-----
Input
7
001
100
101
010
0
1
001100

Output
0
0
1
1
0
0
2



-----Note-----

In test cases $1$, $2$, $5$, $6$ no operations are required since they are already good strings.

For the $3$rd test case: "001" can be achieved by flipping the first character  — and is one of the possible ways to get a good string.

For the $4$th test case: "000" can be achieved by flipping the second character  — and is one of the possible ways to get a good string.

For the $7$th test case: "000000" can be achieved by flipping the third and fourth characters  — and is one of the possible ways to get a good string.
targets: q = int(input())
for ii in range(q):
	s = input()
	n = len(s)
	wyn = 5298528589245892
	wyn = min(wyn, s.count('0'))
	wyn = min(wyn, s.count('1'))
	#00001111
	cyk = s.count('0')
	for i in range(n):
		if s[i] == '1':
			cyk +=1
		else:
			cyk -= 1
		wyn = min(wyn,cyk)
	cyk = s.count('1')
	for i in range(n):
		if s[i] == '0':
			cyk += 1
		else:
			cyk -= 1
		wyn = min(wyn,cyk)
	print(wyn)
inputs: Solve in Python:
=====Function Descriptions=====
group()

A group() expression returns one or more subgroups of the match.
Code

>>> import re
>>> m = re.match(r'(\w+)@(\w+)\.(\w+)','username@hackerrank.com')
>>> m.group(0)       # The entire match 
'username@hackerrank.com'
>>> m.group(1)       # The first parenthesized subgroup.
'username'
>>> m.group(2)       # The second parenthesized subgroup.
'hackerrank'
>>> m.group(3)       # The third parenthesized subgroup.
'com'
>>> m.group(1,2,3)   # Multiple arguments give us a tuple.
('username', 'hackerrank', 'com')

groups()

A groups() expression returns a tuple containing all the subgroups of the match.
Code

>>> import re
>>> m = re.match(r'(\w+)@(\w+)\.(\w+)','username@hackerrank.com')
>>> m.groups()
('username', 'hackerrank', 'com')

groupdict()

A groupdict() expression returns a dictionary containing all the named subgroups of the match, keyed by the subgroup name.
Code

>>> m = re.match(r'(?P<user>\w+)@(?P<website>\w+)\.(?P<extension>\w+)','myname@hackerrank.com')
>>> m.groupdict()
{'website': 'hackerrank', 'user': 'myname', 'extension': 'com'}

=====Problem Statement=====
You are given a string S.
Your task is to find the first occurrence of an alphanumeric character in (read from left to right) that has consecutive repetitions. 

=====Input Format=====
A single line of input containing the string S.

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

=====Output Format=====
Print the first occurrence of the repeating character. If there are no repeating characters, print -1.
targets: #!/usr/bin/env python3

import re

def __starting_point():
    string = input()
    
    match = re.search(r'([a-zA-Z0-9])\1+', string)
    
    print((match.group(1) if match else -1))

__starting_point()
inputs: I found an interesting problem on https://www.codechef.com/problems/CHEFZOT:
Chef loves research! Now he is looking for subarray of maximal length with non-zero product.
Chef has an array A with N elements: A1, A2, ..., AN. 

Subarray Aij of array A is elements from index i to index j: Ai, Ai+1, ..., Aj. 
Product of subarray Aij is product of all its elements (from ith to jth). 

-----Input-----
- First line contains sinlge integer N denoting the number of elements.
- Second line contains N space-separated integers A1, A2, ..., AN denoting the elements of array. 

-----Output-----
- In a single line print single integer - the maximal length of subarray with non-zero product. 

-----Constraints-----
- 1 ≤ N ≤ 100000
- 0 ≤ Ai ≤ 10000

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

Output:
2

Input:
1
0

Output:
0

Input:
3
1 0 1

Output:
1

-----Explanation-----
For the first sample subarray is: {2, 3}. 
For the second sample there are no subbarays with non-zero product. 
For the third sample subbarays is {1}, (the first element, or the third one).

I tried it in Python, but could not do it. Can you solve it?
targets: n=int(input())
a=list(map(int,input().split()))
c=m=0
for i in range(n):
 if a[i]!=0:
  c+=1
 else:
  m=max(m,c)
  c=0
 #print(m,c,a[i])
m=max(m,c)
print(m)
inputs: Solve in Python:
There is a country with $n$ citizens. The $i$-th of them initially has $a_{i}$ money. The government strictly controls the wealth of its citizens. Whenever a citizen makes a purchase or earns some money, they must send a receipt to the social services mentioning the amount of money they currently have.

Sometimes the government makes payouts to the poor: all citizens who have strictly less money than $x$ are paid accordingly so that after the payout they have exactly $x$ money. In this case the citizens don't send a receipt.

You know the initial wealth of every citizen and the log of all events: receipts and payouts. Restore the amount of money each citizen has after all events.


-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 2 \cdot 10^{5}$) — the numer of citizens.

The next line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($0 \le a_{i} \le 10^{9}$) — the initial balances of citizens.

The next line contains a single integer $q$ ($1 \le q \le 2 \cdot 10^{5}$) — the number of events.

Each of the next $q$ lines contains a single event. The events are given in chronological order.

Each event is described as either 1 p x ($1 \le p \le n$, $0 \le x \le 10^{9}$), or 2 x ($0 \le x \le 10^{9}$). In the first case we have a receipt that the balance of the $p$-th person becomes equal to $x$. In the second case we have a payoff with parameter $x$.


-----Output-----

Print $n$ integers — the balances of all citizens after all events.


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

Output
3 2 3 4 

Input
5
3 50 2 1 10
3
1 2 0
2 8
1 3 20

Output
8 8 20 8 10 



-----Note-----

In the first example the balances change as follows: 1 2 3 4 $\rightarrow$ 3 3 3 4 $\rightarrow$ 3 2 3 4 $\rightarrow$ 3 2 3 4

In the second example the balances change as follows: 3 50 2 1 10 $\rightarrow$ 3 0 2 1 10 $\rightarrow$ 8 8 8 8 10 $\rightarrow$ 8 8 20 8 10
targets: R=lambda:map(int,input().split())
n=int(input())
a=*zip([1]*n,range(1,n+1),R()),*([*R()]for _ in[0]*int(input()))
r=[-1]*n
m=0
for t,p,*x in a[::-1]:
 if t>1:m=max(m,p)
 elif r[p-1]<0:r[p-1]=max(x[0],m)
print(*r)
inputs: I found an interesting problem on https://codeforces.com/problemset/problem/645/A:
Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a 2 × 2 grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the empty cell as shown below: $\rightarrow$ 

In order to determine if they are truly Best Friends For Life (BFFLs), Bessie and Elsie would like to know if there exists a sequence of moves that takes their puzzles to the same configuration (moves can be performed in both puzzles). Two puzzles are considered to be in the same configuration if each tile is on top of the same grid cell in both puzzles. Since the tiles are labeled with letters, rotations and reflections are not allowed.


-----Input-----

The first two lines of the input consist of a 2 × 2 grid describing the initial configuration of Bessie's puzzle. The next two lines contain a 2 × 2 grid describing the initial configuration of Elsie's puzzle. The positions of the tiles are labeled 'A', 'B', and 'C', while the empty cell is labeled 'X'. It's guaranteed that both puzzles contain exactly one tile with each letter and exactly one empty position.


-----Output-----

Output "YES"(without quotes) if the puzzles can reach the same configuration (and Bessie and Elsie are truly BFFLs). Otherwise, print "NO" (without quotes).


-----Examples-----
Input
AB
XC
XB
AC

Output
YES

Input
AB
XC
AC
BX

Output
NO



-----Note-----

The solution to the first sample is described by the image. All Bessie needs to do is slide her 'A' tile down.

In the second sample, the two puzzles can never be in the same configuration. Perhaps Bessie and Elsie are not meant to be friends after all...

I tried it in Python, but could not do it. Can you solve it?
targets: a, b, c, d = input(), input(), input(), input()
a = a + b[::-1]
x = "X"
for i in range(4):
    if a[i] == x:
        a = a[:i] + a[i + 1:]
        break
c = c + d[::-1]

for i in range(4):
    if c[i] == x:
        c = c[:i] + c[i + 1:]
        break
flag = False
for i in range(4):
    if a == c:
        flag = True
    c = c[1:] + c[0]
if flag:
    print("YES")
else:
    print("NO")
inputs: Solve in Python:
Given are a sequence of N positive integers A_1, A_2, \ldots, A_N and another positive integer S.

For a non-empty subset T of the set \{1, 2, \ldots , N \}, let us define f(T) as follows:

 - f(T) is the number of different non-empty subsets \{x_1, x_2, \ldots , x_k \} of T such that A_{x_1}+A_{x_2}+\cdots +A_{x_k} = S.
Find the sum of f(T) over all 2^N-1 subsets T of \{1, 2, \ldots , N \}. Since the sum can be enormous, print it modulo 998244353.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq N \leq 3000
 - 1 \leq S \leq 3000
 - 1 \leq A_i \leq 3000

-----Input-----
Input is given from Standard Input in the following format:
N S
A_1 A_2 ... A_N

-----Output-----
Print the sum of f(T) modulo 998244353.

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

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

For each T, the value of f(T) is shown below. The sum of these values is 6.
 - f(\{1\}) = 0
 - f(\{2\}) = 0
 - f(\{3\}) = 1 (One subset \{3\} satisfies the condition.)
 - f(\{1, 2\}) = 1 (\{1, 2\})
 - f(\{2, 3\}) = 1 (\{3\})
 - f(\{1, 3\}) = 1 (\{3\})
 - f(\{1, 2, 3\}) = 2 (\{1, 2\}, \{3\})
targets: #!python3

iim = lambda: list(map(int, input().rstrip().split()))

def resolve():
    N, S = iim()
    A = list(iim())
    mod = 998244353
    S1 = S + 1

    dp = [0] * (S+1)

    dp[0] = pow(2, N, mod)
    inv = pow(2, mod-2, mod)

    for ai in A:
        for i in range(S, ai-1, -1):
            dp[i] = (dp[i] + dp[i-ai]*inv) % mod

    print((dp[-1]))


def __starting_point():
    resolve()

__starting_point()
inputs: I found an interesting problem on https://leetcode.com/problems/make-array-strictly-increasing/:
Given two integer arrays arr1 and arr2, return the minimum number of operations (possibly zero) needed to make arr1 strictly increasing.
In one operation, you can choose two indices 0 <= i < arr1.length and 0 <= j < arr2.length and do the assignment arr1[i] = arr2[j].
If there is no way to make arr1 strictly increasing, return -1.
 
Example 1:
Input: arr1 = [1,5,3,6,7], arr2 = [1,3,2,4]
Output: 1
Explanation: Replace 5 with 2, then arr1 = [1, 2, 3, 6, 7].

Example 2:
Input: arr1 = [1,5,3,6,7], arr2 = [4,3,1]
Output: 2
Explanation: Replace 5 with 3 and then replace 3 with 4. arr1 = [1, 3, 4, 6, 7].

Example 3:
Input: arr1 = [1,5,3,6,7], arr2 = [1,6,3,3]
Output: -1
Explanation: You can't make arr1 strictly increasing.
 
Constraints:

1 <= arr1.length, arr2.length <= 2000
0 <= arr1[i], arr2[i] <= 10^9

I tried it in Python, but could not do it. Can you solve it?
targets: import bisect

class Solution:
    def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int:
        N = len(arr1)
        arr1 = [0] + arr1
        # 表示前 i 个元素，执行了 k 次操作后，是有序的
        dp = [[float('inf')] * (N + 1) for _ in range(N + 1)]
        dp[0][0] = -float('inf')
        
        arr2.sort()
        for i in range(1, N + 1):
            for k in range(i + 1):
                # 前i-1个元素，已经完成了k次交换
                if arr1[i] > dp[i-1][k]:
                    dp[i][k] = min(dp[i][k], arr1[i])
                
                # 前 i-1 个元素，已经完成了 k-1次交换，所以这一次一定要交换
                if k >= 1:
                    idx_2 = bisect.bisect_right(arr2, dp[i-1][k-1])
                    if idx_2 != len(arr2):                    
                        dp[i][k] = min(dp[i][k], arr2[idx_2])
        
        res = float('inf')
        for i in range(1, N+1):
            if dp[N][i] != float('inf'):
                res = min(res, i)
        return res if res != float('inf') else -1
inputs: Solve in Python:
# Task
Make a custom esolang interpreter for the language Stick. Stick is a simple, stack-based esoteric programming language with only 7 commands.
# Commands

* `^`: Pop the stack.

* `!`: Add new element to stack with the value of 0.

* `+`: Increment element. 255+1=0.

* `-`: Decrement element. 0-1=255.

* `*`: Add ascii value of **top** element to the output stream.

* `[`: Skip past **next** `]` if element value is 0.

* `]`: Jump back to the command after **previous** `[` if element value is nonzero.

# Syntax and other info

* You don't need to add support for nested brackets.
* Non-command characters should be ignored.
* Code will always have all brackets closed.
* Note the highlighted **next** and **previous** in the commands reference.
* Program begins with the top element having the value of 0 and being the only element in the stack.
* Program ends when command executor reaches the end.

# Examples

## Hello,...
targets: def interpreter(tape):
    stack, output = [0], ''
    i, n = 0, len(tape)
    while i < n:
        cmd = tape[i]
        if cmd == '^':
            stack.pop()
        elif cmd == '!':
            stack.append(0)
        elif cmd == '+':
            stack[0] = 0 if stack[0] == 255 else stack[0] + 1
        elif cmd == '-':
            stack[0] = 255 if stack[0] == 0 else stack[0] - 1
        elif cmd == '*':
            output += chr(stack.pop(0))
        elif cmd == '[' and stack[0] == 0:
            while tape[i] != ']':
                i += 1
        elif cmd == ']' and stack[0] != 0:
            while tape[i] != '[':
                i -= 1
        i += 1
    return output.replace('\n', '\x02')
inputs: Solve in Python:
=====Function Descriptions=====
mean

The mean tool computes the arithmetic mean along the specified axis.

import numpy

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

print numpy.mean(my_array, axis = 0)        #Output : [ 2.  3.]
print numpy.mean(my_array, axis = 1)        #Output : [ 1.5  3.5]
print numpy.mean(my_array, axis = None)     #Output : 2.5
print numpy.mean(my_array)                  #Output : 2.5

By default, the axis is None. Therefore, it computes the mean of the flattened array.

var

The var tool computes the arithmetic variance along the specified axis.

import numpy

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

print numpy.var(my_array, axis = 0)         #Output : [ 1.  1.]
print numpy.var(my_array, axis = 1)         #Output : [ 0.25  0.25]
print numpy.var(my_array, axis = None)      #Output : 1.25
print numpy.var(my_array)                   #Output : 1.25

By default, the axis is None. Therefore, it computes the variance of the flattened array.

std

The std tool computes the arithmetic standard deviation along the specified axis.

import numpy

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

print numpy.std(my_array, axis = 0)         #Output : [ 1.  1.]
print numpy.std(my_array, axis = 1)         #Output : [ 0.5  0.5]
print numpy.std(my_array, axis = None)      #Output : 1.118033988749895
print numpy.std(my_array)                   #Output : 1.118033988749895

By default, the axis is None. Therefore, it computes the standard deviation of the flattened array.

=====Problem Statement=====
You are given a 2-D array of size NXM.
Your task is to find:
The mean along axis 1
The var along axis 0
The std along axis None

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

=====Output Format=====
First, print the mean.
Second, print the var.
Third, print the std.
targets: import numpy as np

n, m = [int(x) for x in input().strip().split()]
array = np.array([[int(x) for x in input().strip().split()] for _ in range(n)], dtype = float)
print(np.mean(array, axis = 1))
print(np.var(array, axis = 0))
print(np.std(array))
inputs: Solve in Python:
You are given an array $a$ consisting of $n$ integer numbers.

Let instability of the array be the following value: $\max\limits_{i = 1}^{n} a_i - \min\limits_{i = 1}^{n} a_i$.

You have to remove exactly one element from this array to minimize instability of the resulting $(n-1)$-elements array. Your task is to calculate the minimum possible instability.


-----Input-----

The first line of the input contains one integer $n$ ($2 \le n \le 10^5$) — the number of elements in the array $a$.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^5$) — elements of the array $a$.


-----Output-----

Print one integer — the minimum possible instability of the array if you have to remove exactly one element from the array $a$.


-----Examples-----
Input
4
1 3 3 7

Output
2

Input
2
1 100000

Output
0



-----Note-----

In the first example you can remove $7$ then instability of the remaining array will be $3 - 1 = 2$.

In the second example you can remove either $1$ or $100000$ then instability of the remaining array will be $100000 - 100000 = 0$ and $1 - 1 = 0$ correspondingly.
targets: def go():
    n = int(input())
    a = [int(i) for i in input().split(' ')]
    if n == 2:
        return 0
    m1 = max(a)
    a.remove(m1)
    m2 = max(a)
    mi1 = min(a)
    a.remove(mi1)
    mi2 = min(a)
    if m2 - mi1 < m1 - mi2:
        return m2 - mi1
    return m1 - mi2

print(go())
inputs: Solve in Python:
Each student eagerly awaits the day he would pass the exams successfully. Thus, Vasya was ready to celebrate, but, alas, he didn't pass it. However, many of Vasya's fellow students from the same group were more successful and celebrated after the exam.

Some of them celebrated in the BugDonalds restaurant, some of them — in the BeaverKing restaurant, the most successful ones were fast enough to celebrate in both of restaurants. Students which didn't pass the exam didn't celebrate in any of those restaurants and elected to stay home to prepare for their reexamination. However, this quickly bored Vasya and he started checking celebration photos on the Kilogramm. He found out that, in total, BugDonalds was visited by $A$ students, BeaverKing — by $B$ students and $C$ students visited both restaurants. Vasya also knows that there are $N$ students in his group.

Based on this info, Vasya wants to determine either if his data contradicts itself or, if it doesn't, how many students in his group didn't pass the exam. Can you help him so he won't waste his valuable preparation time?


-----Input-----

The first line contains four integers — $A$, $B$, $C$ and $N$ ($0 \leq A, B, C, N \leq 100$).


-----Output-----

If a distribution of $N$ students exists in which $A$ students visited BugDonalds, $B$ — BeaverKing, $C$ — both of the restaurants and at least one student is left home (it is known that Vasya didn't pass the exam and stayed at home), output one integer — amount of students (including Vasya) who did not pass the exam. 

If such a distribution does not exist and Vasya made a mistake while determining the numbers $A$, $B$, $C$ or $N$ (as in samples 2 and 3), output $-1$.


-----Examples-----
Input
10 10 5 20

Output
5
Input
2 2 0 4

Output
-1
Input
2 2 2 1

Output
-1


-----Note-----

The first sample describes following situation: $5$ only visited BugDonalds, $5$ students only visited BeaverKing, $5$ visited both of them and $5$ students (including Vasya) didn't pass the exam.

In the second sample $2$...
targets: A, B, C, N = [int(i) for i in input().split()]
summ = A - C + B
if summ >= N or (C > min(A, B)):
	print(-1)
else:
	print(N - summ)