Muennighoff/xP3x-sample huggingface dataset:
inputs: Solve in Python:
Arkady is playing Battleship. The rules of this game aren't really important.

There is a field of $n \times n$ cells. There should be exactly one $k$-decker on the field, i. e. a ship that is $k$ cells long oriented either horizontally or vertically. However, Arkady doesn't know where it is located. For each cell Arkady knows if it is definitely empty or can contain a part of the ship.

Consider all possible locations of the ship. Find such a cell that belongs to the maximum possible number of different locations of the ship.


-----Input-----

The first line contains two integers $n$ and $k$ ($1 \le k \le n \le 100$) — the size of the field and the size of the ship.

The next $n$ lines contain the field. Each line contains $n$ characters, each of which is either '#' (denotes a definitely empty cell) or '.' (denotes a cell that can belong to the ship).


-----Output-----

Output two integers — the row and the column of a cell that belongs to the maximum possible number of different locations of the ship.

If there are multiple answers, output any of them. In particular, if no ship can be placed on the field, you can output any cell.


-----Examples-----
Input
4 3
#..#
#.#.
....
.###

Output
3 2

Input
10 4
#....##...
.#...#....
..#..#..#.
...#.#....
.#..##.#..
.....#...#
...#.##...
.#...#.#..
.....#..#.
...#.#...#

Output
6 1

Input
19 6
##..............###
#......#####.....##
.....#########.....
....###########....
...#############...
..###############..
.#################.
.#################.
.#################.
.#################.
#####....##....####
####............###
####............###
#####...####...####
.#####..####..#####
...###........###..
....###########....
.........##........
#.................#

Output
1 8



-----Note-----

The picture below shows the three possible locations of the ship that contain the cell $(3, 2)$ in the first sample. [Image]
targets: n, k = list(map(int, input().split()))
m = [list(input()) for _ in range(n)]
p = [[0 for _ in range(n)] for _ in range(n)]

for i in range(n):
    for j in range(n):
        s = True
        if i + k - 1 < n:
            for l in range(k):
                if m[i + l][j] != '.':
                    s = False
                    break
            if s:
                for l in range(k):
                    p[i + l][j] += 1

        s = True
        if j + k - 1 < n:
            for l in range(k):
                if m[i][j + l] != '.':
                    s = False
                    break
            if s:
                for l in range(k):
                    p[i][j + l] += 1

mx = -1
for i in range(n):
    for j in range(n):
        if p[i][j] > mx:
            ans = (i + 1, j + 1)
            mx = p[i][j]

print(*ans)
inputs: I found an interesting problem on https://codeforces.com/problemset/problem/1368/D:
Gottfried learned about binary number representation. He then came up with this task and presented it to you.

You are given a collection of $n$ non-negative integers $a_1, \ldots, a_n$. You are allowed to perform the following operation: choose two distinct indices $1 \leq i, j \leq n$. If before the operation $a_i = x$, $a_j = y$, then after the operation $a_i = x~\mathsf{AND}~y$, $a_j = x~\mathsf{OR}~y$, where $\mathsf{AND}$ and $\mathsf{OR}$ are bitwise AND and OR respectively (refer to the Notes section for formal description). The operation may be performed any number of times (possibly zero).

After all operations are done, compute $\sum_{i=1}^n a_i^2$ — the sum of squares of all $a_i$. What is the largest sum of squares you can achieve?


-----Input-----

The first line contains a single integer $n$ ($1 \leq n \leq 2 \cdot 10^5$).

The second line contains $n$ integers $a_1, \ldots, a_n$ ($0 \leq a_i < 2^{20}$).


-----Output-----

Print a single integer — the largest possible sum of squares that can be achieved after several (possibly zero) operations.


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

Output
15129

Input
3
1 3 5

Output
51

Input
2
349525 699050

Output
1099509530625



-----Note-----

In the first sample no operation can be made, thus the answer is $123^2$.

In the second sample we can obtain the collection $1, 1, 7$, and $1^2 + 1^2 + 7^2 = 51$.

If $x$ and $y$ are represented in binary with equal number of bits (possibly with leading zeros), then each bit of $x~\mathsf{AND}~y$ is set to $1$ if and only if both corresponding bits of $x$ and $y$ are set to $1$. Similarly, each bit of $x~\mathsf{OR}~y$ is set to $1$ if and only if at least one of the corresponding bits of $x$ and $y$ are set to $1$. For example, $x = 3$ and $y = 5$ are represented as $011_2$ and $101_2$ (highest bit first). Then, $x~\mathsf{AND}~y = 001_2 = 1$, and $x~\mathsf{OR}~y = 111_2 = 7$.

I tried it in Python, but could not do it. Can you solve it?
targets: n=int(input())
a=list(map(int,input().split()))
x=[0]*20
for i in range(n):
  s="{0:b}".format(a[i])
  b=[]
  for j in range(len(s)):
    b.append(s[j])
  b.reverse()
  for j in range(20-len(s)):
    b.append('0')
  b.reverse()
  for j in range(20):
    if b[j]=='1':
      x[j]+=1
ans=0
for i in range(n):
  s=[]
  for j in range(20):
    if x[j]>0:
      s.append('1')
      x[j]-=1
    else:
      s.append('0')
  ans+=int(''.join(s), 2)**2
print(ans)
inputs: Solve in Python:
You went shopping to buy cakes and donuts with X yen (the currency of Japan).
First, you bought one cake for A yen at a cake shop.
Then, you bought as many donuts as possible for B yen each, at a donut shop.
How much do you have left after shopping?

-----Constraints-----
 - 1 \leq A, B \leq 1 000
 - A + B \leq X \leq 10 000
 - X, A and B are integers.

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

-----Output-----
Print the amount you have left after shopping.

-----Sample Input-----
1234
150
100

-----Sample Output-----
84

You have 1234 - 150 = 1084 yen left after buying a cake.
With this amount, you can buy 10 donuts, after which you have 84 yen left.
targets: X = int(input())
A = int(input())
B = int(input())

print((X - A) % B)
inputs: I found an interesting problem on https://codeforces.com/problemset/problem/1030/E:
Vasya has a sequence $a$ consisting of $n$ integers $a_1, a_2, \dots, a_n$. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number $6$ $(\dots 00000000110_2)$ into $3$ $(\dots 00000000011_2)$, $12$ $(\dots 000000001100_2)$, $1026$ $(\dots 10000000010_2)$ and many others. Vasya can use this operation any (possibly zero) number of times on any number from the sequence.

Vasya names a sequence as good one, if, using operation mentioned above, he can obtain the sequence with bitwise exclusive or of all elements equal to $0$.

For the given sequence $a_1, a_2, \ldots, a_n$ Vasya'd like to calculate number of integer pairs $(l, r)$ such that $1 \le l \le r \le n$ and sequence $a_l, a_{l + 1}, \dots, a_r$ is good.


-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 3 \cdot 10^5$) — length of the sequence.

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^{18}$) — the sequence $a$.


-----Output-----

Print one integer — the number of pairs $(l, r)$ such that $1 \le l \le r \le n$ and the sequence $a_l, a_{l + 1}, \dots, a_r$ is good.


-----Examples-----
Input
3
6 7 14

Output
2

Input
4
1 2 1 16

Output
4



-----Note-----

In the first example pairs $(2, 3)$ and $(1, 3)$ are valid. Pair $(2, 3)$ is valid since $a_2 = 7 \rightarrow 11$, $a_3 = 14 \rightarrow 11$ and $11 \oplus 11 = 0$, where $\oplus$ — bitwise exclusive or. Pair $(1, 3)$ is valid since $a_1 = 6 \rightarrow 3$, $a_2 = 7 \rightarrow 13$, $a_3 = 14 \rightarrow 14$ and $3 \oplus 13 \oplus 14 = 0$.

In the second example pairs $(1, 2)$, $(2, 3)$, $(3, 4)$ and $(1, 4)$ are valid.

I tried it in Python, but could not do it. Can you solve it?
targets: #!/usr/bin/env python3
import sys

def rint():
    return list(map(int, sys.stdin.readline().split()))
#lines = stdin.readlines()

def get_num1(i):
    cnt = 0
    while i:
        if i%2:
            cnt +=1
        i //=2
    return cnt

n = int(input())

a = list(rint())

b = [get_num1(aa) for aa in a]

ans = 0
#S0[i] : 1 if sum of 1s in ragne (0, i) is odd, else 0
S0 = [0]*n
S0[0] = b[0]%2
for i in range(1, n):
    S0[i] = (S0[i-1] + b[i])%2

#total even pairs in (0, n)
even_cnt = S0.count(0)

ans = even_cnt

# check total even pairs in (i, n)
for i in range(1, n):
    if b[i-1] %2:
        even_cnt = n - i - even_cnt
    else:
        even_cnt -= 1
    ans += even_cnt

for i in range(n):
    max_value = 0
    sum_value = 0
    for j in range(1, 62):
        if i + j > n:
            break
        sum_value += b[i+j-1]
        max_value = max(max_value, b[i+j-1])
        if 2 * max_value > sum_value and sum_value%2 == 0:
            ans -= 1

print(ans)
inputs: Solve in Python:
Nian is a monster which lives deep in the oceans. Once a year, it shows up on the land, devouring livestock and even people. In order to keep the monster away, people fill their villages with red colour, light, and cracking noise, all of which frighten the monster out of coming.

Little Tommy has n lanterns and Big Banban has m lanterns. Tommy's lanterns have brightness a_1, a_2, ..., a_{n}, and Banban's have brightness b_1, b_2, ..., b_{m} respectively.

Tommy intends to hide one of his lanterns, then Banban picks one of Tommy's non-hidden lanterns and one of his own lanterns to form a pair. The pair's brightness will be the product of the brightness of two lanterns.

Tommy wants to make the product as small as possible, while Banban tries to make it as large as possible.

You are asked to find the brightness of the chosen pair if both of them choose optimally.


-----Input-----

The first line contains two space-separated integers n and m (2 ≤ n, m ≤ 50).

The second line contains n space-separated integers a_1, a_2, ..., a_{n}.

The third line contains m space-separated integers b_1, b_2, ..., b_{m}.

All the integers range from  - 10^9 to 10^9.


-----Output-----

Print a single integer — the brightness of the chosen pair.


-----Examples-----
Input
2 2
20 18
2 14

Output
252

Input
5 3
-1 0 1 2 3
-1 0 1

Output
2



-----Note-----

In the first example, Tommy will hide 20 and Banban will choose 18 from Tommy and 14 from himself.

In the second example, Tommy will hide 3 and Banban will choose 2 from Tommy and 1 from himself.
targets: n, m = map(int, input().split())
l1 = list(map(int, input().split()))
l2 = list(map(int, input().split()))
ans1 = []
for i in range(n):
    ans = -10 ** 18 - 1
    for j in range(n):
        if j != i:
            for q in range(m):
                if ans < l1[j] * l2[q]:
                    ans = l1[j] * l2[q]
    ans1.append(ans)
print(min(ans1))
inputs: Solve in Python:
# Story&Task
 There are three parties in parliament. The "Conservative Party", the "Reformist Party", and a group of independants.

 You are a member of the “Conservative Party” and you party is trying to pass a bill. The “Reformist Party” is trying to block it.

 In order for a bill to pass, it must have a majority vote, meaning that more than half of all members must approve of a bill before it is passed . The "Conservatives" and "Reformists" always vote the same as other members of thier parties, meaning that all the members of each party will all vote yes, or all vote no .

 However, independants vote individually, and the independant vote is often the determining factor as to whether a bill gets passed or not.

 Your task is to find the minimum number of independents that have to vote for your party's (the Conservative Party's) bill so that it is passed .

 In each test case the makeup of the Parliament will be different . In some cases your party may make up the majority of parliament, and in others it may make up the minority. If your party is the majority, you may find that you do not neeed any independants to vote in favor of your bill in order for it to pass . If your party is the minority, it may be possible that there are not enough independants for your bill to be passed . If it is impossible for your bill to pass, return `-1`.

# Input/Output


 - `[input]` integer `totalMembers`

  The total number of members.


 - `[input]` integer `conservativePartyMembers`

  The number of members in the Conservative Party.


 - `[input]` integer `reformistPartyMembers`

  The number of members in the Reformist Party.

 
 - `[output]` an integer

  The minimum number of independent members that have to vote as you wish so that the bill is passed, or `-1` if you can't pass it anyway.
  
# Example

 For `n = 8, m = 3 and k = 3`, the output should be `2`.
 
 It means: 
 ```
 Conservative Party member --> 3
 Reformist Party member   --> 3
 the independent members --> 8 - 3 - 3 = 2
 If 2 independent members...
targets: def pass_the_bill(par, con, ref):
    return -1 if ref >= (par / 2) else max(0, par // 2 + 1 - con)
inputs: I found an interesting problem on https://www.codechef.com/ZCOPRAC/problems/ZCO12001:
Zonal Computing Olympiad 2012, 26 Nov 2011

A sequence of opening and closing brackets is well-bracketed if we can pair up each opening bracket with a matching closing bracket in the usual sense.  For instance, the sequences (), (()) and ()(()) are well-bracketed, while (, ()), (()(), and )(  are not well-bracketed.

The nesting depth of a well-bracketed sequence tells us the maximum number of levels of inner matched brackets enclosed within outer matched brackets.  For instance, the nesting depth of () and ()()() is 1, the nesting depth of (()) and ()(()) is 2, the nesting depth of ((())) is 3, and so on.  

Given a well-bracketed sequence, we are interested in computing the following: 
-  The nesting depth, and the first position where it occurs–this will be the position of the first opening bracket at this nesting depth, where the positions are numbered starting with 1.
-  The maximum number of symbols between any pair of matched  brackets, including both the outer brackets, and the first position where this occurs–that is, the position of the first opening bracket of this segment

For instance, the nesting depth of ()(())()(()())(()()) is 2 and the first position where this occurs is 4.  The opening bracket at position 10 is also at nesting depth 2 but we have to report the first position where this occurs, which is 4.

In this sequence, the maximum number of symbols between a pair of matched bracket is 6, starting at position 9. There is another such sequence of length 6 starting at position 15, but this is not the first such position.

-----Input format-----
The input consists of two lines. The first line is a single integer N, the length of the bracket sequence. Positions in the sequence are numbered 1,2,…,N. The second line is a sequence of N space-separated integers that encode the bracket expression as follows: 1 denotes an opening bracket ( and 2 denotes a closing bracket ).  Nothing other than 1 or 2 appears in the second line of input and the corresponding expression is guaranteed to be...

I tried it in Python, but could not do it. Can you solve it?
targets: # cook your dish here
import sys
n=int(input().strip())
stringa=input().strip().split()
stringa=''.join(stringa)
counter=0
max_width=0
max_depth=0
for i in range(n):
    if stringa[i]=='1':
        if counter==0:
            start=i
        counter+=1 
    else:
        if counter>max_depth:
            max_depth=counter
            depth_idx=i
        counter-=1
        if counter==0:
            end=i
            if end-start+1>max_width:
                max_width=end-start+1
                start_idx=start+1
print(max_depth, depth_idx, max_width, start_idx)
inputs: Solve in Python:
=====Problem Statement=====
The itertools module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an iterator algebra making it possible to construct specialized tools succinctly and efficiently in pure Python.

You are given a list of N lowercase English letters. For a given integer K, you can select any K indices (assume 1-based indexing) with a uniform probability from the list.
Find the probability that at least one of the K indices selected will contain the letter: ''.

=====Input Format=====
The input consists of three lines. The first line contains the integer N, denoting the length of the list. The next line consists of N space-separated lowercase English letters, denoting the elements of the list.
The third and the last line of input contains the integer K, denoting the number of indices to be selected.

=====Output Format=====
Output a single line consisting of the probability that at least one of the K indices selected contains the letter: 'a'.
Note: The answer must be correct up to 3 decimal places. 

=====Constraints=====
1≤N≤10
1≤K≤N
targets: #!/usr/bin/env python3

import string
symbols = string.ascii_lowercase

from itertools import combinations

def __starting_point():
    n = int(input().strip())
    arr = list(map(str, input().strip().split(' ')))
    times = int(input().strip())
    cmbts = list(combinations(sorted(arr), times))
    
    print(("{:.4f}".format(len(list([a for a in cmbts if a[0] == 'a']))/(len(cmbts)))))
    

__starting_point()
inputs: I found an interesting problem on https://www.codewars.com/kata/565b112d09c1adfdd500019c:
Complete the function that takes an array of words.

You must concatenate the `n`th letter from each word to construct a new word which should be returned as a string, where `n` is the position of the word in the list.

For example:

```
["yoda", "best", "has"]  -->  "yes"
  ^        ^        ^
  n=0     n=1     n=2
```

**Note:** Test cases contain valid input only - i.e. a string array or an empty array; and each word will have enough letters.

I tried it in Python, but could not do it. Can you solve it?
targets: def nth_char(w):
    return ''.join(w[i][i] for i in range(len(w)))
inputs: I found an interesting problem on https://www.codechef.com/problems/CLPNT:
You may have helped Chef and prevented Doof from destroying the even numbers. But, it has only angered Dr Doof even further. However, for his next plan, he needs some time. Therefore, Doof has built $N$ walls to prevent Chef from interrupting him. You have to help Chef by telling him the number of walls he needs to destroy in order to reach Dr Doof.
Formally, the whole area can be represented as the first quadrant with the origin at the bottom-left corner. Dr. Doof is located at the origin $(0, 0)$. There are $N$ walls, the i-th wall is a straight line segment joining the points $(a_i, 0)$ and $(0, a_i)$. For every initial position of Chef $(x_j, y_j)$, find the number of walls he needs to break before reaching Doof. Obviously, chef can't start from a point on the wall. Therefore, if $(x_j, y_j)$ lies on any of the given walls, print $-1$ in a new line.

-----Input-----
- First line contains $T$, denoting the number of testcases.
- The first line of every test case contains a single integer $N$ denoting the number of walls Dr Doof has built.
- The next line contains $N$ space separated distinct integers each denoting $a_i$.
- The next line contains a single integer $Q$ denoting the number of times Chef asks for your help.
- The next $Q$ lines contains two space separated integers $x_j$ and $y_j$, each denoting the co-ordinates of the starting point of Chef.

-----Output-----
For each query, print the number of walls Chef needs to break in order to reach Dr Doof in a separate line. If Chef tries to start from a point on any of the walls, print $-1$.

-----Constraints-----
- $1 \leq T \leq 2 * 10^2$
- $1 \leq N, Q \leq 2 * 10^5$
- $1 \leq a_i \leq 10^9$
- $0 \leq x_j, y_j \leq 10^9$
- $a_1 < a_2 < a_3 < .... < a_N$
- Sum of $N$ and $Q$ over all testcases for a particular test file does not exceed $2 * 10^5$

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

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

-----Explanation-----
The sample input can be represented by the graph given below:

If Chef starts from $(0, 0)$,...

I tried it in Python, but could not do it. Can you solve it?
targets: import sys
from sys import stdin,stdout
from bisect import bisect_right
from os import path
#cin=sys.stdin.readline
cout=sys.stdout.write

if (path.exists('input.txt')):
 #------------------Sublime--------------------------------------#
 sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
 def cinN():return (int(input()))
 def cin():return(map(int,input().split()))
else:
 #------------------PYPY FAst I/o--------------------------------#
 def cinN():return (int(stdin.readline()))
 def cin():return(map(int,stdin.readline().split()))



def find_le(a, x):
 'Find rightmost value less than or equal to x'
 i = bisect_right(a, x)
 if i:
  return i-1
 return -1

def func():
 st=''
 n=cinN()
 l=list(cin())
 l.sort()
 qn=cinN()
 for _ in range(qn):
  x,y=cin()
  k=x+y
  t=find_le(l,k)
  if t==-1:
   ans=(0)
  else:
   if l[t]==k:
    ans=(-1)
   else:ans=(t+1)
  print(ans) 
 #cout(str(ans))

def __starting_point():
 test=cinN()
 for _ in range(test):func()
__starting_point()
inputs: I found an interesting problem on https://codeforces.com/problemset/problem/394/A:
When new students come to the Specialized Educational and Scientific Centre (SESC) they need to start many things from the beginning. Sometimes the teachers say (not always unfairly) that we cannot even count. So our teachers decided to teach us arithmetics from the start. And what is the best way to teach students add and subtract? — That's right, using counting sticks! An here's our new task: 

An expression of counting sticks is an expression of type:[ A sticks][sign +][B sticks][sign =][C sticks] (1 ≤ A, B, C).  

Sign + consists of two crossed sticks: one vertical and one horizontal. Sign = consists of two horizontal sticks. The expression is arithmetically correct if A + B = C.

We've got an expression that looks like A + B = C given by counting sticks. Our task is to shift at most one stick (or we can shift nothing) so that the expression became arithmetically correct. Note that we cannot remove the sticks from the expression, also we cannot shift the sticks from the signs + and =.

We really aren't fabulous at arithmetics. Can you help us?


-----Input-----

The single line contains the initial expression. It is guaranteed that the expression looks like A + B = C, where 1 ≤ A, B, C ≤ 100.


-----Output-----

If there isn't a way to shift the stick so the expression becomes correct, print on a single line "Impossible" (without the quotes). If there is a way, print the resulting expression. Follow the format of the output from the test samples. Don't print extra space characters.

If there are multiple correct answers, print any of them. For clarifications, you are recommended to see the test...

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

s = input()
l = re.compile('[|]+').findall(s)

diff = len(l[0]) + len(l[1]) - len(l[2])

if diff == 0:
    print(s)
elif diff == -2:
    print(l[0]+'|+' + l[1] + '=' + l[2][:-1])
elif diff == 2:
    l[2] += '|'
    if len(l[0]) == 1:
        l[1] = l[1][:-1]
    else:
        l[0] = l[0][:-1]
    print(l[0]+'+'+l[1]+'='+l[2])
else:
    print('Impossible')
inputs: I found an interesting problem on https://codeforces.com/problemset/problem/909/F:
Given an integer N, find two permutations:  Permutation p of numbers from 1 to N such that p_{i} ≠ i and p_{i} & i = 0 for all i = 1, 2, ..., N.  Permutation q of numbers from 1 to N such that q_{i} ≠ i and q_{i} & i ≠ 0 for all i = 1, 2, ..., N. 

& is the bitwise AND operation.


-----Input-----

The input consists of one line containing a single integer N (1 ≤ N ≤ 10^5).


-----Output-----

For each subtask, if the required permutation doesn't exist, output a single line containing the word "NO"; otherwise output the word "YES" in the first line and N elements of the permutation, separated by spaces, in the second line. If there are several possible permutations in a subtask, output any of them.


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

Output
NO
NO

Input
6

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

I tried it in Python, but could not do it. Can you solve it?
targets: from math import log2, floor
n=int(input())
# n=100
if n%2:
	print('NO')
else:
	print("YES")
	k=floor(log2(n))+1
	res = [0 for i in range(n)]
	occupied = [0 for i in range(n)]
	switch = 0
	for i in range(n,0,-1):
		val = 2**k-1-i
		if val > n:
			k-=1
			val = 2**k-1-i
		if occupied[val-1]:
			while occupied[val-1]:
				k-=1
				val = 2**k-1-i
		val = 2**k-1-i
		occupied[val-1] = 1
		res[i-1] = val
	for i in res:
		print(i,end=' ')
	print()

if n in [1,2,3,4,5]:
	print('NO')
elif int(log2(n)) == log2(n):
	print('NO')
elif n == 6:
	print('YES')
	print('3 6 2 5 1 4')
else:
	print('YES')
	print('7 3 2 5 6 4 1',end=' ')
	for i in range(8,n):
		p = pow(2,floor(log2(i))+1)
		if i < pow(2,floor(log2(n))):
			print(p*3//2-1-i,end=' ')
		else:
			print(i+1,end=' ')
	if n > 7:
		print(pow(2,floor(log2(n))))
inputs: I found an interesting problem on https://www.codewars.com/kata/595ddfe2fc339d8a7d000089:
# Introduction 

Hamsters are rodents belonging to the subfamily Cricetinae. The subfamily contains about 25 species, classified in six or seven genera. They have become established as popular small house pets, and, partly because they are easy to breed in captivity, hamsters are often used as laboratory animals.


# Task 

Write a function that accepts two inputs: `code` and `message` and returns an encrypted string from `message` using the `code`.   
The `code` is a string that generates the key in the way shown below:

```
 1  | h a m s t e r
 2  | i b n   u f
 3  | j c o   v g
 4  | k d p   w
 5  | l   q   x
 6  |         y
 7  |         z

```

All letters from `code` get number `1`. All letters which directly follow letters from `code` get number `2` (unless they already have a smaller number assigned), etc. It's difficult to describe but it should be easy to understand from the example below:

```
 1  | a e h m r s t
 2  | b f i n     u
 3  | c g j o     v
 4  | d   k p     w
 5  |     l q     x
 6  |             y
 7  |             z

```

How does the encoding work using the `hamster` code?    

```
a => a1
b => a2
c => a3
d => a4
e => e1
f => e2
...
```

And applying it to strings :

```
hamsterMe('hamster', 'hamster')   => h1a1m1s1t1e1r1
hamsterMe('hamster', 'helpme')    => h1e1h5m4m1e1

```

And you probably started wondering what will happen if there is no `a` in the `code`.  
Just add these letters after the last available letter (in alphabetic order) in the `code`.

The key for code `hmster` is:
```
 1  | e h m r s t
 2  | f i n     u
 3  | g j o     v
 4  |   k p     w
 5  |   l q     x
 6  |           y
 7  |           z
 8  |           a
 9  |           b
10  |           c
11  |           d
```

# Additional notes

The `code` will have at least 1 letter.   
Duplication of letters in `code` is possible and should be handled.    
The `code` and `message` consist of only lowercase letters.

I tried it in Python, but could not do it. Can you solve it?
targets: from string import ascii_lowercase
id = {c:i for i,c in enumerate(ascii_lowercase)}
char = (ascii_lowercase+ascii_lowercase).__getitem__

def hamster_me(code, message):
    res, L = {}, sorted(map(id.get, code))
    for i,j in zip(L, L[1:]+[26+L[0]]):
        start = char(i)
        for k,x in enumerate(map(char, range(i, j)), 1):
            res[x] = f"{start}{k}"
    return ''.join(map(res.get, message))
inputs: I found an interesting problem on https://www.codewars.com/kata/5600e00e42bcb7b9dc00014e:
The image shows how we can obtain the Harmonic Conjugated Point of three aligned points A, B, C.

- We choose any point L, that is not in the line with A, B and C. We form the triangle ABL

- Then we draw a line from point C that intersects the sides of this triangle at points M and N respectively.

- We draw the diagonals of the quadrilateral ABNM; they are AN and BM and they intersect at point K

- We unit, with a line L and K, and this line intersects the line of points A, B and C at point D

The point D is named the Conjugated Harmonic Point of the points A, B, C.
You can get more knowledge related with this point at: (https://en.wikipedia.org/wiki/Projective_harmonic_conjugate)

If we apply the theorems of Ceva (https://en.wikipedia.org/wiki/Ceva%27s_theorem)
and Menelaus (https://en.wikipedia.org/wiki/Menelaus%27_theorem) we will have this formula:



AC, in the above formula is the length of the segment of points A to C in this direction and its value is:

```AC = xA - xC```

Transform the above formula using the coordinates ```xA, xB, xC and xD```

The task is to create a function ```harmon_pointTrip()```, that receives three arguments, the coordinates of points xA, xB and xC, with values such that : ```xA < xB < xC```, this function should output the coordinates of point D for each given triplet, such that

`xA < xD < xB < xC`, or to be clearer

let's see some cases:
```python
harmon_pointTrip(xA, xB, xC) ------> xD # the result should be expressed up to four decimals (rounded result)
harmon_pointTrip(2, 10, 20) -----> 7.1429 # (2 < 7.1429 < 10 < 20, satisfies the constraint)
harmon_pointTrip(3, 9, 18) -----> 6.75
```


Enjoy it and happy coding!!

I tried it in Python, but could not do it. Can you solve it?
targets: def harmon_pointTrip(a, b, c):
    return round((a*c + b*c - 2*a*b) / (2*c - a - b), 4)
inputs: Solve in Python:
Mohit's girlfriend is playing a game with Nicky. The description of the game is as follows:
- Initially on a table Player 1 will put N gem-stones.
- Players will play alternatively, turn by turn.
- At each move a player can take at most M gem-stones (at least 1 gem-stone must be taken) from the available gem-stones on the table.(Each gem-stone has same cost.)
- Each players gem-stone are gathered in player's side.
- The player that empties the table purchases food from it (using all his gem-stones; one gem-stone can buy one unit of food), and the other one puts all his gem-stones back on to the table. Again the game continues with the "loser" player starting.
- The game continues until all the gem-stones are used to buy food.
- The main objective of the game is to consume maximum units of food.

	Mohit's girlfriend is weak in mathematics and prediction so she asks help from Mohit, in return she shall kiss Mohit. Mohit task is to predict the maximum units of food her girlfriend can eat, if, she starts first. Being the best friend of Mohit, help him in predicting the answer.

-----Input-----
- Single line contains two space separated integers N and M.

-----Output-----
- The maximum units of food Mohit's girlfriend can eat.

-----Constraints and Subtasks-----
- 1 <= M <= N <= 100
Subtask 1: 10 points
- 1 <= M <= N <= 5
Subtask 2: 20 points
- 1 <= M <= N <= 10
Subtask 3: 30 points
- 1 <= M <= N <= 50
Subtask 3: 40 points
- Original Constraints.

-----Example-----
Input:
4 2

Output:
2
targets: n,m = list(map(int,input().split()))
l = [ [1],
 [1,2],
 [2,2,3],
 [1,2,3,4],
 [4,3,3,4,5] ]
print(l[n-1][m-1])
inputs: Solve in Python:
The main city magazine offers its readers an opportunity to publish their ads. The format of the ad should be like this:

There are space-separated non-empty words of lowercase and uppercase Latin letters.

There are hyphen characters '-' in some words, their positions set word wrapping points. Word can include more than one hyphen. 

It is guaranteed that there are no adjacent spaces and no adjacent hyphens. No hyphen is adjacent to space. There are no spaces and no hyphens before the first word and after the last word. 

When the word is wrapped, the part of the word before hyphen and the hyphen itself stay on current line and the next part of the word is put on the next line. You can also put line break between two words, in that case the space stays on current line. Check notes for better understanding.

The ad can occupy no more that k lines and should have minimal width. The width of the ad is the maximal length of string (letters, spaces and hyphens are counted) in it.

You should write a program that will find minimal width of the ad.


-----Input-----

The first line contains number k (1 ≤ k ≤ 10^5).

The second line contains the text of the ad — non-empty space-separated words of lowercase and uppercase Latin letters and hyphens. Total length of the ad don't exceed 10^6 characters.


-----Output-----

Output minimal width of the ad.


-----Examples-----
Input
4
garage for sa-le

Output
7

Input
4
Edu-ca-tion-al Ro-unds are so fun

Output
10



-----Note-----

Here all spaces are replaced with dots.

In the first example one of possible results after all word wraps looks like this:

garage.

for.

sa-

le



The second example:

Edu-ca-

tion-al.

Ro-unds.

are.so.fun
targets: n = int(input())
s = input()
s += ' '
def ok(w):
	wordcnt = 0
	lettercnt = 0
	linecnt = 0
	for j in range(len(s)):
		if not (s[j]==' ' or s[j]=='-'):
			lettercnt += 1;
		else:
			lettercnt += 1
			if j==len(s)-1:
				lettercnt -= 1
			if (wordcnt+lettercnt)>w:
				linecnt += 1
				wordcnt = lettercnt
			else:
				wordcnt += lettercnt
			lettercnt = 0
		if wordcnt>w: return False
	
	if wordcnt:
		linecnt += 1
	if linecnt>n:
		return False
	else:
		return True
	
l = 1
r = 1000000
while l<r:
	mid = l + (r-l)//2
	if ok(mid):
		r = mid
	else:
		l = mid + 1
print(l)
inputs: Solve in Python:
There is a grid of squares with H horizontal rows and W vertical columns.
The square at the i-th row from the top and the j-th column from the left is represented as (i, j).
Each square is black or white.
The color of the square is given as an H-by-W matrix (a_{i, j}).
If a_{i, j} is ., the square (i, j) is white; if a_{i, j} is #, the square (i, j) is black.
Snuke is compressing this grid.
He will do so by repeatedly performing the following operation while there is a row or column that consists only of white squares:
 - Operation: choose any one row or column that consists only of white squares, remove it and delete the space between the rows or columns.
It can be shown that the final state of the grid is uniquely determined regardless of what row or column is chosen in each operation.
Find the final state of the grid.

-----Constraints-----
 - 1 \leq H, W \leq 100
 - a_{i, j} is . or #.
 - There is at least one black square in the whole grid.

-----Input-----
Input is given from Standard Input in the following format:
H W
a_{1, 1}...a_{1, W}
:
a_{H, 1}...a_{H, W}

-----Output-----
Print the final state of the grid in the same format as input (without the numbers of rows and columns); see the samples for clarity.

-----Sample Input-----
4 4
##.#
....
##.#
.#.#

-----Sample Output-----
###
###
.##

The second row and the third column in the original grid will be removed.
targets: import sys

input = sys.stdin.readline
H, W = map(int, input().split())
grid = []
for _ in range(H):
    grid.append(list(input().strip()))

h_set = set()
for i in range(H):
    flag = True
    for j in range(W):
        if grid[i][j] == "#":
            flag = False
            break
    if flag:
        h_set.add(i)

w_set = set()
for j in range(W):
    flag = True
    for i in range(H):
        if grid[i][j] == "#":
            flag = False
            break
    if flag:
        w_set.add(j)

for i in range(H):
    if i in h_set:
        continue
    for j in range(W):
        if j in w_set:
            continue
        print(grid[i][j], end="")
    print("")
inputs: I found an interesting problem on https://www.codewars.com/kata/5840946ea3d4c78e90000068:
It's the most hotly anticipated game of the school year - Gryffindor vs Slytherin! Write a function which returns the winning team. 

You will be given two arrays with two values. 

The first given value is the number of points scored by the team's Chasers and the second a string with a 'yes' or 'no' value if the team caught the golden snitch!

The team who catches the snitch wins their team an extra 150 points - but doesn't always win them the game.

If the score is a tie return "It's a draw!""

** The game only ends when someone catches the golden snitch, so one array will always include 'yes' or 'no.' Points scored by Chasers can be any positive integer.

I tried it in Python, but could not do it. Can you solve it?
targets: def game_winners(gryffindor, slytherin):
    g = gryffindor[0] + 150 * (gryffindor[1] == "yes")
    s = slytherin[0] + 150 * (slytherin[1] == "yes")
    return "Gryffindor wins!" if g > s else "Slytherin wins!" if s > g else "It's a draw!"
inputs: I found an interesting problem on https://www.codewars.com/kata/554a44516729e4d80b000012:
Let us begin with an example:

A man has a rather old car being worth $2000. 
He saw a secondhand car being worth $8000. He wants to keep his old car until he can buy the secondhand one.

He thinks he can save $1000 each month but the prices of his old 
car and of the new one decrease of 1.5 percent per month.
Furthermore this percent of loss increases of `0.5` percent 
at the end of every two months.
Our man finds it difficult to make all these calculations.

**Can you help him?**

How many months will it take him to save up enough money to buy the car he wants, and how much money will he have left over?

**Parameters and return of function:**
```
parameter (positive int or float, guaranteed) startPriceOld (Old car price)
parameter (positive int or float, guaranteed) startPriceNew (New car price)
parameter (positive int or float, guaranteed) savingperMonth 
parameter (positive float or int, guaranteed) percentLossByMonth

nbMonths(2000, 8000, 1000, 1.5) should return [6, 766] or (6, 766)
```
###  Detail of the above example:
```
end month 1: percentLoss 1.5 available -4910.0
end month 2: percentLoss 2.0 available -3791.7999...
end month 3: percentLoss 2.0 available -2675.964
end month 4: percentLoss 2.5 available -1534.06489...
end month 5: percentLoss 2.5 available -395.71327...
end month 6: percentLoss 3.0 available 766.158120825...
return [6, 766] or (6, 766)

```

where `6` is the number of months at **the end of which** he can buy the new car and `766` is the nearest integer to `766.158...` (rounding `766.158` gives `766`).

**Note:** 

Selling, buying and saving are normally done at end of month.
Calculations are processed at the end of each considered month
but if, by chance from the start, the value of the old car is bigger than the value of the new one or equal there is no saving to be made, no need to wait so he can at the beginning of the month buy the new car:
```
nbMonths(12000, 8000, 1000, 1.5) should return [0, 4000]
nbMonths(8000, 8000, 1000, 1.5) should return [0, 0]
```

We don't take care...

I tried it in Python, but could not do it. Can you solve it?
targets: def nbMonths(oldCarPrice, newCarPrice, saving, loss):
    months = 0
    budget = oldCarPrice
    
    while budget < newCarPrice:
        months += 1
        if months % 2 == 0:
            loss += 0.5
        
        oldCarPrice *= (100 - loss) / 100
        newCarPrice *= (100 - loss) / 100
        budget = saving * months + oldCarPrice
    
    return [months, round(budget - newCarPrice)]
inputs: I found an interesting problem on https://www.codechef.com/MAY16/problems/CHBLLS:
Chef has bought ten balls of five colours. There are two balls of each colour. Balls of same colour have same weight. Let us enumerate colours by numbers from 1 to 5. Chef knows that all balls, except two (of same colour), weigh exactly one kilogram. He also knows that each of these two balls is exactly 1 kg heavier than other balls.

You need to find the colour which balls are heavier than others. 
To do that, you can use mechanical scales with two weighing pans. As your scales are very accurate, you can know the exact difference of weights of objects from first and second pans. Formally, the scales will give you the difference (signed difference) of weights of the objects put into the first pan and the second pan. See the following examples for details.

- If you put two balls of the same colour on your scales, each ball to one pan, the scales will tell you that difference is "0".
- But if you put into the first pan some balls of total weight 3 kg, and into the second pan of 5 kg, then scales will tell you "-2" because the second pan is 2 kg heavier than first. 
- Similarly, if you put 5 kg weight in first pan and 3 kg in the second pan, then scale will tell you "2" as first pan is 2 kg heavier than second.

-----Input & Output-----
- The interaction process have two phases. At first phase you perform sequence of weighings on the mechanical scales. At the second phase you should output the colour of the heavier balls.
- To use the mechanical scales, you should print "1"(without quotes) and then print two lines, the first line will describe the enumeration of colours of balls on the first pan and second line should that of second pan.
- To describe some pan, you need to print one integer n - the number of balls you put in this pan, followed by n space-separated integers - colours of the balls you put in this pan. 
- Once you have printed required data, you can read from the standard input one integer - the difference of weights of the first and the second pans.
- To output the colour of the heavier balls,...

I tried it in Python, but could not do it. Can you solve it?
targets: print("1")
print("3 1 2 2")
print("3 3 4 4")
import sys 
d = {1:1,
     2:2,
     -1:3,
     -2:4,
     0:5
     }
sys.stdout.flush()
v = eval(input())
print("2")
print(d[v])
inputs: Solve in Python:
# Our Setup

Alice and Bob work in an office. When the workload is light and the boss isn't looking, they often play simple word games for fun. This is one of those days!

# This Game

Today Alice and Bob are playing what they like to call _Mutations_, where they take turns trying to "think up" a new four-letter word identical to the prior word except for one letter. They just keep on going until their memories fail out.

# Their Words

Alice and Bob have memories of the same size, each able to recall `10` to `2000` different four-letter words. Memory words and initial game word are randomly taken from a list of `4000` (unique, four-letter, lowercased) words, any of which may appear in both memories.

The expression to "think up" a new word means that for their turn, the player must submit as their response word the first valid, unused word that appears in their memory (by lowest array index), as their memories are ordered from the most "memorable" words to the least.

# The Rules
* a valid response word must contain four different letters
* `1` letter is replaced while the other `3` stay in position
* it must be the lowest indexed valid word in their memory
* this word cannot have already been used during the game
* the final player to provide a valid word will win the game
* if 1st player fails 1st turn, 2nd can win with a valid word
* when both players fail the initial word, there is no winner

# Your Task
To determine the winner!

# Some Examples

`alice = plat,rend,bear,soar,mare,pare,flap,neat,clan,pore`

`bob   = boar,clap,farm,lend,near,peat,pure,more,plan,soap`

1) In the case of `word = "send"` and `first = 0`:
* Alice responds to `send` with `rend`
* Bob   responds to `rend` with `lend`
* Alice has no valid response to `lend`
* Bob   wins the game.

2) In the case of `word = "flip"` and `first = 1`:
* Bob   has no valid response to `flip`
* Alice responds to `flip` with `flap`
* Alice wins the game.

3) In the case of `word = "maze"` and `first = 0`:
* Alice responds to `maze` with `mare`
* Bob  ...
targets: import re

def genMask(w):
    x = list(w)
    for i in range(len(w)):
        x[i] = '.'
        yield ''.join(x)
        x[i] = w[i]

def mutations(alice, bob, word, first):
    players, seen  = [alice,bob], {word}
    win, failed, i = -1, -1, first^1
    while 1:
        i    ^= 1
        lst   = players[i]
        reg   = re.compile('|'.join(genMask(word)))
        found = next((w for w in lst if reg.match(w) and w not in seen and len(set(w))==4), None)
        if found is None:
            if failed==i^1: break
            failed = i
        else:
            seen.add(found)
            word, win = found, i
            if failed!=-1: break
    return win
inputs: Solve in Python:
Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm.

Sereja takes a blank piece of paper. Then he starts writing out the sequence in m stages. Each time he either adds a new number to the end of the sequence or takes l first elements of the current sequence and adds them c times to the end. More formally, if we represent the current sequence as a_1, a_2, ..., a_{n}, then after we apply the described operation, the sequence transforms into a_1, a_2, ..., a_{n}[, a_1, a_2, ..., a_{l}] (the block in the square brackets must be repeated c times). 

A day has passed and Sereja has completed the sequence. He wonders what are the values of some of its elements. Help Sereja.


-----Input-----

The first line contains integer m (1 ≤ m ≤ 10^5) — the number of stages to build a sequence. 

Next m lines contain the description of the stages in the order they follow. The first number in the line is a type of stage (1 or 2). Type 1 means adding one number to the end of the sequence, in this case the line contains integer x_{i} (1 ≤ x_{i} ≤ 10^5) — the number to add. Type 2 means copying a prefix of length l_{i} to the end c_{i} times, in this case the line further contains two integers l_{i}, c_{i} (1 ≤ l_{i} ≤ 10^5, 1 ≤ c_{i} ≤ 10^4), l_{i} is the length of the prefix, c_{i} is the number of copyings. It is guaranteed that the length of prefix l_{i} is never larger than the current length of the sequence.

The next line contains integer n (1 ≤ n ≤ 10^5) — the number of elements Sereja is interested in. The next line contains the numbers of elements of the final sequence Sereja is interested in. The numbers are given in the strictly increasing order. It is guaranteed that all numbers are strictly larger than zero and do not exceed the length of the resulting sequence. Consider the elements of the final sequence numbered starting from 1 from the beginning to the end of the sequence.

Please, do not use the %lld specifier to read or write 64-bit integers in...
targets: n=int(input())
a=[]
for i in range(n):
	a.append(list(map(int,input().split())))
m=int(input())
b=list([int(x)-1 for x in input().split()])
c=[]
now=0
k=0
ans=[]
for i in range(n):
	t=a[i]
	if t[0]==1:
		now+=1
		if len(c)<100000: c.append(t[1])
		if k<m and b[k]==now-1: 
			ans.append(t[1])
			k+=1
	else:
		last=now
		now+=t[1]*t[2]
		while t[2]:
			if len(c)<100000: c.extend(c[:t[1]])
			else: break
			t[2]-=1
		while k<m and last<=b[k]<now:
			ans.append(c[(b[k]-last)%t[1]])
			k+=1	
print(' '.join(map(str,ans)))
inputs: Solve in Python:
We have a string S of length N consisting of uppercase English letters.
How many times does ABC occur in S as contiguous subsequences (see Sample Inputs and Outputs)?

-----Constraints-----
 - 3 \leq N \leq 50
 - S consists of uppercase English letters.

-----Input-----
Input is given from Standard Input in the following format:
N
S

-----Output-----
Print number of occurrences of ABC in S as contiguous subsequences.

-----Sample Input-----
10
ZABCDBABCQ

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

Two contiguous subsequences of S are equal to ABC: the 2-nd through 4-th characters, and the 7-th through 9-th characters.
targets: n = int(input())
s = list(input())
cnt = 0
for i in range(n-2):
    if s[i]+s[i+1]+s[i+2] == "ABC":
        cnt += 1
print(cnt)