input
stringlengths 50
13.9k
| output_program
stringlengths 5
655k
| output_answer
stringlengths 5
655k
| split
stringclasses 1
value | dataset
stringclasses 1
value |
---|---|---|---|---|
Create a function xMasTree(height) that returns a christmas tree of the correct height. The height is passed through to the function and the function should return a list containing each line of the tree.
```
xMasTree(5) should return : ['____#____', '___###___', '__#####__', '_#######_', '#########', '____#____', '____#____']
xMasTree(3) should return : ['__#__', '_###_', '#####', '__#__', '__#__']
```
The final idea is for the tree to look like this if you decide to print each element of the list:
```
xMasTree(5) will result in:
____#____ 1
___###___ 2
__#####__ 3
_#######_ 4
######### -----> 5 - Height of Tree
____#____ 1
____#____ 2 - Trunk/Stem of Tree
xMasTree(3) will result in:
__#__ 1
_###_ 2
##### -----> 3 - Height of Tree
__#__ 1
__#__ 2 - Trunk/Stem of Tree
```
Pad with underscores i.e _ so each line is the same length. The last line forming the tree having only hashtags, no spaces. Also remember the trunk/stem of the tree. | def xMasTree(n):
n2 = n * 2 - 1
return [('#' * i).center(n2, '_') for i in range(1, n2 + 1, 2)] + ['#'.center(n2, '_')] * 2 | def xMasTree(n):
n2 = n * 2 - 1
return [('#' * i).center(n2, '_') for i in range(1, n2 + 1, 2)] + ['#'.center(n2, '_')] * 2 | train | APPS_structured |
## Description
Your job is to create a simple password validation function, as seen on many websites.
The rules for a valid password are as follows:
- There needs to be at least 1 uppercase letter.
- There needs to be at least 1 lowercase letter.
- There needs to be at least 1 number.
- The password needs to be at least 8 characters long.
You are permitted to use any methods to validate the password.
## Examples:
### Extra info
- You will only be passed strings.
- The string can contain any standard keyboard character.
- Accepted strings can be any length, as long as they are 8 characters or more. | def password(s):
return any(c.isupper() for c in s) and \
any(c.islower() for c in s) and \
any(c.isdigit() for c in s) and \
len(s)>7 | def password(s):
return any(c.isupper() for c in s) and \
any(c.islower() for c in s) and \
any(c.isdigit() for c in s) and \
len(s)>7 | train | APPS_structured |
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.
-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.
-----Output:-----
For each test case, output as the pattern.
-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$
-----Sample Input:-----
3
2
3
4
-----Sample Output:-----
1121
1222
112131
122232
132333
11213141
12223242
13233343
14243444
-----EXPLANATION:-----
No need, else pattern can be decode easily. | for _ in range(int(input())):
n=int(input())
b=1
# 1112
# 2122
for _ in range(1,n+1):
a=1
for __ in range((2*n)):
if __%2==0:
print(a,end="")
a+=1
else:
print(b,end="")
b+=1
print()
print() | for _ in range(int(input())):
n=int(input())
b=1
# 1112
# 2122
for _ in range(1,n+1):
a=1
for __ in range((2*n)):
if __%2==0:
print(a,end="")
a+=1
else:
print(b,end="")
b+=1
print()
print() | train | APPS_structured |
# Task
You are given a decimal number `n` as a **string**. Transform it into an array of numbers (given as **strings** again), such that each number has only one nonzero digit and their sum equals n.
Each number in the output array should be written without any leading and trailing zeros.
# Input/Output
- `[input]` string `n`
A non-negative number.
`1 ≤ n.length ≤ 30.`
- `[output]` a string array
Elements in the array should be sorted in descending order.
# Example
For `n = "7970521.5544"` the output should be:
```
["7000000",
"900000",
"70000",
"500",
"20",
"1",
".5",
".05",
".004",
".0004"]
```
For `n = "7496314"`, the output should be:
```
["7000000",
"400000",
"90000",
"6000",
"300",
"10",
"4"]
```
For `n = "0"`, the output should be `[]` | def split_exp(n):
j = n.find('.') + 1 or len(n) + 1
return [f"{c}{'0'*(j-i-2)}" if i < j else f".{'0'*(i-j)}{c}" for i,c in enumerate(n) if c not in "0."] | def split_exp(n):
j = n.find('.') + 1 or len(n) + 1
return [f"{c}{'0'*(j-i-2)}" if i < j else f".{'0'*(i-j)}{c}" for i,c in enumerate(n) if c not in "0."] | train | APPS_structured |
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p_1, p_2, ..., p_{n}, where p_{i} denotes a parent of vertex i (here, for convenience a root is considered its own parent). [Image] For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p_1, p_2, ..., p_{n}, one is able to restore a tree: There must be exactly one index r that p_{r} = r. A vertex r is a root of the tree. For all other n - 1 vertices i, there is an edge between vertex i and vertex p_{i}.
A sequence p_1, p_2, ..., p_{n} is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a_1, a_2, ..., a_{n}, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
-----Input-----
The first line of the input contains an integer n (2 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ n).
-----Output-----
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a_1, a_2, ..., a_{n}) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
-----Examples-----
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
-----Note-----
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p_4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red. [Image]
In the second sample, the given sequence is already valid. | n=int(input())
a=list(map(int,input().split()))
par=[]
for i in range(n):
if a[i]==i+1:
par.append(i)
v=[False for i in range(n)]
for i in par:
v[i]=True
ccl=[]
for i in range(n):
if v[i]:continue
s=[i]
v[i]=True
p=set(s)
t=True
while s and t:
x=s.pop()
j=a[x]-1
if j in p:
ccl.append(j)
t=False
else:
s.append(j)
p.add(j)
if v[j]:t=False
else:v[j]=True
if len(par)==0:
print(len(ccl))
c=ccl[0]
a[c]=c+1
for i in range(1,len(ccl)):
a[ccl[i]]=c+1
print(*a)
else:
print(len(ccl)+len(par)-1)
c=par[0]
for i in range(1,len(par)):
a[par[i]]=c+1
for i in range(len(ccl)):
a[ccl[i]]=c+1
print(*a) | n=int(input())
a=list(map(int,input().split()))
par=[]
for i in range(n):
if a[i]==i+1:
par.append(i)
v=[False for i in range(n)]
for i in par:
v[i]=True
ccl=[]
for i in range(n):
if v[i]:continue
s=[i]
v[i]=True
p=set(s)
t=True
while s and t:
x=s.pop()
j=a[x]-1
if j in p:
ccl.append(j)
t=False
else:
s.append(j)
p.add(j)
if v[j]:t=False
else:v[j]=True
if len(par)==0:
print(len(ccl))
c=ccl[0]
a[c]=c+1
for i in range(1,len(ccl)):
a[ccl[i]]=c+1
print(*a)
else:
print(len(ccl)+len(par)-1)
c=par[0]
for i in range(1,len(par)):
a[par[i]]=c+1
for i in range(len(ccl)):
a[ccl[i]]=c+1
print(*a) | train | APPS_structured |
*This is the advanced version of the [Total Primes](https://www.codewars.com/kata/total-primes/) kata.*
---
The number `23` is the smallest prime that can be "cut" into **multiple** primes: `2, 3`. Another such prime is `6173`, which can be cut into `61, 73` or `617, 3` or `61, 7, 3` (all primes). A third one is `557` which can be sliced into `5, 5, 7`. Let's call these numbers **total primes**.
Notes:
* one-digit primes are excluded by definition;
* leading zeros are also excluded: e.g. splitting `307` into `3, 07` is **not** valid
## Task
Complete the function that takes a range `[a..b]` (both limits included) and returns the total primes within that range (`a ≤ total primes ≤ b`).
The tests go up to 10^(6).
~~~if:python
For your convenience, a list of primes up to 10^(6) is preloaded, called `PRIMES`.
~~~
## Examples
```
(0, 100) ==> [23, 37, 53, 73]
(500, 600) ==> [523, 541, 547, 557, 571, 577, 593]
```
Happy coding!
---
## My other katas
If you enjoyed this kata then please try [my other katas](https://www.codewars.com/collections/katas-created-by-anter69)! :-)
#### *Translations are welcome!* | import numpy as np
from itertools import accumulate
def sieve_primes(n):
sieve = np.ones(n // 2, dtype = np.bool)
limit = 1 + int(n ** 0.5)
for a in range(3, limit, 2):
if sieve[a // 2]:
sieve[a * a // 2::a] = False
prime_indexes = 2 * np.nonzero(sieve)[0].astype(int) + 1
prime_indexes[0] = 2
return set(map(str, prime_indexes))
primes = sieve_primes(10 ** 6)
def all_primes(s):
if int(s) < 10:
return s in primes
for n in accumulate(s[:-1]):
if n in primes:
m = s[len(n):]
if m in primes or all_primes(m):
return True
def total_primes(a, b):
return [int(a) for a in map(str, range(max(10, a), b + 1)) if a in primes and all_primes(a)] | import numpy as np
from itertools import accumulate
def sieve_primes(n):
sieve = np.ones(n // 2, dtype = np.bool)
limit = 1 + int(n ** 0.5)
for a in range(3, limit, 2):
if sieve[a // 2]:
sieve[a * a // 2::a] = False
prime_indexes = 2 * np.nonzero(sieve)[0].astype(int) + 1
prime_indexes[0] = 2
return set(map(str, prime_indexes))
primes = sieve_primes(10 ** 6)
def all_primes(s):
if int(s) < 10:
return s in primes
for n in accumulate(s[:-1]):
if n in primes:
m = s[len(n):]
if m in primes or all_primes(m):
return True
def total_primes(a, b):
return [int(a) for a in map(str, range(max(10, a), b + 1)) if a in primes and all_primes(a)] | train | APPS_structured |
# Task
You are given integer `n` determining set S = {1, 2, ..., n}. Determine if the number of k-element subsets of S is `ODD` or `EVEN` for given integer k.
# Example
For `n = 3, k = 2`, the result should be `"ODD"`
In this case, we have 3 2-element subsets of {1, 2, 3}:
`{1, 2}, {1, 3}, {2, 3}`
For `n = 2, k = 1`, the result should be `"EVEN"`.
In this case, we have 2 1-element subsets of {1, 2}:
`{1}, {2}`
`Don't bother with naive solution - numbers here are really big.`
# Input/Output
- `[input]` integer `n`
`1 <= n <= 10^9`
- `[input]` integer `k`
`1 <= k <= n`
- `[output]` a string
`"EVEN"` or `"ODD"` depending if the number of k-element subsets of S = {1, 2, ..., n} is ODD or EVEN. | #using lucas's theorem https://en.wikipedia.org/wiki/Lucas%27s_theorem
def to_bin(n):
k = 0
while n >= 2**k: k += 1
s = ""
for i in range(k - 1, -1, -1):
if n - 2**i >= 0:
s += "1"
n -= 2**i
else: s += "0"
return s
def subsets_parity(n, k):
s1 = to_bin(n)
s2 = to_bin(k)
for i in range(-1, -len(s2) - 1, -1):
if s1[i] == "0" and s2[i] == "1": return "EVEN"
return "ODD" | #using lucas's theorem https://en.wikipedia.org/wiki/Lucas%27s_theorem
def to_bin(n):
k = 0
while n >= 2**k: k += 1
s = ""
for i in range(k - 1, -1, -1):
if n - 2**i >= 0:
s += "1"
n -= 2**i
else: s += "0"
return s
def subsets_parity(n, k):
s1 = to_bin(n)
s2 = to_bin(k)
for i in range(-1, -len(s2) - 1, -1):
if s1[i] == "0" and s2[i] == "1": return "EVEN"
return "ODD" | train | APPS_structured |
A little weird green frog speaks in a very strange variation of English: it reverses sentence, omitting all puntuation marks `, ; ( ) - ` except the final exclamation, question or period. We urgently need help with building a proper translator.
To simplify the task, we always use lower-case letters. Apostrophes are forbidden as well.
Translator should be able to process multiple sentences in one go. Sentences are separated by arbitrary amount of spaces.
**Examples**
`you should use python.` -> `python use should you.`
`look, a fly!` -> `fly a look!`
`multisentence is good. is not it?` -> `good is multisentence. it not is?` | def frogify(s):
for c in '.!?':
if c in s:
return f'{c} '.join(map(frogify, s.split(c))).strip()
words = ''.join(c for c in s.lower() if c == ' ' or 'a' <= c <= 'z').split()
return ' '.join(words[::-1]) | def frogify(s):
for c in '.!?':
if c in s:
return f'{c} '.join(map(frogify, s.split(c))).strip()
words = ''.join(c for c in s.lower() if c == ' ' or 'a' <= c <= 'z').split()
return ' '.join(words[::-1]) | train | APPS_structured |
The Little Elephant from the Zoo of Lviv currently is on the military mission. There are N enemy buildings placed in a row and numbered from left to right strating from 0. Each building i (except the first and the last) has exactly two adjacent buildings with indices i-1 and i+1. The first and the last buildings have just a single adjacent building.
Some of the buildings contain bombs. When bomb explodes in some building it destroys it and all adjacent to it buildings.
You are given the string S of length N, where Si is 1 if the i-th building contains bomb, 0 otherwise. Find for the Little Elephant the number of buildings that will not be destroyed after all bombs explode. Please note that all bombs explode simultaneously.
-----Input-----
The first line contains single integer T - the number of test cases. T test cases follow. The first line of each test case contains the single integer N - the number of buildings. The next line contains the string S of length N consisted only of digits 0 and 1.
-----Output-----
In T lines print T inetgers - the answers for the corresponding test cases.
-----Constraints-----
1 <= T <= 100
1 <= N <= 1000
-----Example-----
Input:
3
3
010
5
10001
7
0000000
Output:
0
1
7 | for _ in range(int(input())):
n=int(input())
s=input().strip()
ans=n
for i in range(n):
if s[i]=='1':
ans-=1
elif i!=0 and s[i-1]=='1':
ans-=1
elif i!=n-1 and s[i+1]=='1':
ans-=1
print(ans) | for _ in range(int(input())):
n=int(input())
s=input().strip()
ans=n
for i in range(n):
if s[i]=='1':
ans-=1
elif i!=0 and s[i-1]=='1':
ans-=1
elif i!=n-1 and s[i+1]=='1':
ans-=1
print(ans) | train | APPS_structured |
How can you tell an extrovert from an
introvert at NSA? Va gur ryringbef,
gur rkgebireg ybbxf ng gur BGURE thl'f fubrf.
I found this joke on USENET, but the punchline is scrambled. Maybe you can decipher it?
According to Wikipedia, ROT13 (http://en.wikipedia.org/wiki/ROT13) is frequently used to obfuscate jokes on USENET.
Hint: For this task you're only supposed to substitue characters. Not spaces, punctuation, numbers etc.
Test examples:
```
rot13("EBG13 rknzcyr.") == "ROT13 example.";
rot13("This is my first ROT13 excercise!" == "Guvf vf zl svefg EBG13 rkprepvfr!"
``` | from string import ascii_letters, ascii_lowercase, ascii_uppercase
def shift(s, n):
return s[n:] + s[:n]
table = str.maketrans(
ascii_letters,
shift(ascii_lowercase, 13) + shift(ascii_uppercase, 13))
def rot13(message):
return message.translate(table)
| from string import ascii_letters, ascii_lowercase, ascii_uppercase
def shift(s, n):
return s[n:] + s[:n]
table = str.maketrans(
ascii_letters,
shift(ascii_lowercase, 13) + shift(ascii_uppercase, 13))
def rot13(message):
return message.translate(table)
| train | APPS_structured |
Consider the following numbers (where `n!` is `factorial(n)`):
```
u1 = (1 / 1!) * (1!)
u2 = (1 / 2!) * (1! + 2!)
u3 = (1 / 3!) * (1! + 2! + 3!)
...
un = (1 / n!) * (1! + 2! + 3! + ... + n!)
```
Which will win: `1 / n!` or `(1! + 2! + 3! + ... + n!)`?
Are these numbers going to `0` because of `1/n!` or to infinity due
to the sum of factorials or to another number?
## Task
Calculate `(1 / n!) * (1! + 2! + 3! + ... + n!)`
for a given `n`, where `n` is an integer greater or equal to `1`.
To avoid discussions about rounding, return the result **truncated** to 6 decimal places, for example:
```
1.0000989217538616 will be truncated to 1.000098
1.2125000000000001 will be truncated to 1.2125
```
## Remark
Keep in mind that factorials grow rather rapidly, and you need to handle large inputs.
## Hint
You could try to simplify the expression. | from math import factorial, trunc
def going(n):
sum, past = 1, 1
for k in range(n, 1, -1):
past *= 1/k
sum += past
return (trunc(sum*10**6))/(10**6) | from math import factorial, trunc
def going(n):
sum, past = 1, 1
for k in range(n, 1, -1):
past *= 1/k
sum += past
return (trunc(sum*10**6))/(10**6) | train | APPS_structured |
=====Problem Statement=====
You are given a string s consisting only of digits 0-9, commas ,, and dots .
Your task is to complete the regex_pattern defined below, which will be used to re.split() all of the , and . symbols in s.
It’s guaranteed that every comma and every dot in s is preceeded and followed by a digit. | #!/usr/bin/env python3
import re
def __starting_point():
out = list(re.split('[.,]', input()))
print("\n".join(filter(lambda x: re.match('[0-9]+',x), out)))
__starting_point() | #!/usr/bin/env python3
import re
def __starting_point():
out = list(re.split('[.,]', input()))
print("\n".join(filter(lambda x: re.match('[0-9]+',x), out)))
__starting_point() | train | APPS_structured |
In ChefLand, there is a mountain range consisting of $N$ hills (numbered $1$ through $N$) in a straight line. Let's denote the height of the $i$-th hill from the left by $h_i$.
Ada is working on the water supply system of ChefLand. On some of the hills, she wants to place water reservoirs; then, for each reservoir, she will decide in which direction the water should flow from it — either to the left or to the right (water may not flow in both directions from the same reservoir). From a reservoir on a hill with height $h$, water flows in the chosen direction until it reaches the first hill that is strictly higher than $h$; all hills before this hill (including the hill containing the reservoir) are therefore supplied with water.
For example, suppose we have hills with heights $[7, 2, 3, 5, 8]$. If we place a reservoir on the hill with height $5$, and pump water from it to the left, then the hills with heights $2$, $3$ and $5$ are supplied with water.
Help Ada find the minimum numer of reservoirs needed to provide water to all the hills if she chooses the directions optimally.
-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- The second line contains $N$ space-separated integers $h_1, h_2, \dots, h_N$.
-----Output-----
For each test case, print a single line containing one integer — the minimum required number of reservoirs.
-----Constraints-----
- $2 \le N \le 10^5$
- $1 \le h_i \le 10^9$ for each valid $i$
- $h_i \neq h_j $ for any valid $i \neq j$
- the sum of $N$ over all test cases does not exceed $5 \cdot 10^5$
-----Example Input-----
1
6
4 16 32 6 8 2
-----Example Output-----
2
-----Explanation-----
Example case 1: We can place reservoirs on the second and third hill, pumping water to the left and right respectively. |
def solve(ar):
max = 0
posn = -1
for i in range(len(ar)):
if ar[i]>max:
max = ar[i]
posn = i
if posn == 0 or posn == len(ar)-1:
return 1
return 1+min(solve(ar[:posn]),solve(ar[posn+1:]))
t = int(input())
for i in range(t):
n = int(input())
h = list(map(int,input().split()))
z = solve(h)
print(z)
|
def solve(ar):
max = 0
posn = -1
for i in range(len(ar)):
if ar[i]>max:
max = ar[i]
posn = i
if posn == 0 or posn == len(ar)-1:
return 1
return 1+min(solve(ar[:posn]),solve(ar[posn+1:]))
t = int(input())
for i in range(t):
n = int(input())
h = list(map(int,input().split()))
z = solve(h)
print(z)
| train | APPS_structured |
$Gogi$, $Tapu$ and $Sonu$ are the elite members of $Tapu$ $Sena$. $Gogi$ is always stoned and asks absurd questions, But this time he asked a question which seems to be very serious and interesting. $Tapu$ wants to solve this question to impress $Sonu$. He gave an array of length N to $Tapu$, $Tapu$ can perform the following operations exactly once:
- Remove any subarray from the given array given the resulting array formed after the removal is non-empty.
- Reverse the whole array.
Remember you can’t shuffle the elements of the array.
Tapu needs to find out the maximum possible GCD of all the numbers in the array after applying the given operations exactly once. Tapu is very weak at programming, he wants you to solve this problem so that he can impress $Sonu$.
-----Input:-----
- The first line contains $T$, the number of test cases.
- For each test case
-FIrst line contains $N$.
- Last line contains $N$ numbers of the array.
-----Output:-----
A single integer in a new line, maximum possible GCD.
-----Constraints-----
- $1 \leq T \leq 10^2$
- $1 \leq N \leq 10^4$
- $1 \leq a[i] \leq 10^9$
Summation of N for all testcases is less than $10^6$
-----Sample Input 1:-----
1
1
2
-----Sample Output 1:-----
2 |
t=int(input())
for _ in range(t):
n = int(input())
arr = list(map(int, input().strip().split()))
print(max(arr[0],arr[-1])) |
t=int(input())
for _ in range(t):
n = int(input())
arr = list(map(int, input().strip().split()))
print(max(arr[0],arr[-1])) | train | APPS_structured |
```if:python
Note: Python may currently have some performance issues. If you find them, please let me know and provide suggestions to improve the Python version! It's my weakest language... any help is much appreciated :)
```
Artlessly stolen and adapted from Hackerrank.
Kara Danvers is new to CodeWars, and eager to climb up in the ranks. We want to determine Kara's rank as she progresses up the leaderboard.
This kata uses Dense Ranking, so any identical scores count as the same rank (e.g, a scoreboard of `[100, 97, 97, 90, 82, 80, 72, 72, 60]` corresponds with rankings of `[1, 2, 2, 3, 4, 5, 6, 6, 7]`
You are given an array, `scores`, of leaderboard scores, descending, and another array, `kara`, representing Kara's Codewars score over time, ascending. Your function should return an array with each item corresponding to the rank of Kara's current score on the leaderboard.
**Note:** This kata's performance requirements are significantly steeper than the Hackerrank version. Some arrays will contain millions of elements; optimize your code so you don't time out. If you're timing out before 200 tests are completed, you've likely got the wrong code complexity. If you're timing out around 274 tests (there are 278), you likely need to make some tweaks to how you're handling the arrays.
Examples:
(For the uninitiated, Kara Danvers is Supergirl. This is important, because Kara thinks and moves so fast that she can complete a kata within microseconds. Naturally, latency being what it is, she's already opened many kata across many, many tabs, and solves them one by one on a special keyboard so she doesn't have to wait hundreds of milliseconds in between solving them. As a result, the only person's rank changing on the leaderboard is Kara's, so we don't have to worry about shifting values of other codewarriors. Thanks, Supergirl.)
Good luck! Please upvote if you enjoyed it :) | def leaderboard_climb(arr, kara):
arr = sorted(set(arr),reverse=True)
rank = []
pos = len(arr)
for x in kara:
while pos>=1 and x >= arr[pos-1]:
pos -= 1
rank.append(pos+1)
return rank
| def leaderboard_climb(arr, kara):
arr = sorted(set(arr),reverse=True)
rank = []
pos = len(arr)
for x in kara:
while pos>=1 and x >= arr[pos-1]:
pos -= 1
rank.append(pos+1)
return rank
| train | APPS_structured |
There are N towns located in a line, conveniently numbered 1 through N. Takahashi the merchant is going on a travel from town 1 to town N, buying and selling apples.
Takahashi will begin the travel at town 1, with no apple in his possession. The actions that can be performed during the travel are as follows:
- Move: When at town i (i < N), move to town i + 1.
- Merchandise: Buy or sell an arbitrary number of apples at the current town. Here, it is assumed that one apple can always be bought and sold for A_i yen (the currency of Japan) at town i (1 ≦ i ≦ N), where A_i are distinct integers. Also, you can assume that he has an infinite supply of money.
For some reason, there is a constraint on merchandising apple during the travel: the sum of the number of apples bought and the number of apples sold during the whole travel, must be at most T. (Note that a single apple can be counted in both.)
During the travel, Takahashi will perform actions so that the profit of the travel is maximized. Here, the profit of the travel is the amount of money that is gained by selling apples, minus the amount of money that is spent on buying apples. Note that we are not interested in apples in his possession at the end of the travel.
Aoki, a business rival of Takahashi, wants to trouble Takahashi by manipulating the market price of apples. Prior to the beginning of Takahashi's travel, Aoki can change A_i into another arbitrary non-negative integer A_i' for any town i, any number of times. The cost of performing this operation is |A_i - A_i'|. After performing this operation, different towns may have equal values of A_i.
Aoki's objective is to decrease Takahashi's expected profit by at least 1 yen. Find the minimum total cost to achieve it. You may assume that Takahashi's expected profit is initially at least 1 yen.
-----Constraints-----
- 1 ≦ N ≦ 10^5
- 1 ≦ A_i ≦ 10^9 (1 ≦ i ≦ N)
- A_i are distinct.
- 2 ≦ T ≦ 10^9
- In the initial state, Takahashi's expected profit is at least 1 yen.
-----Input-----
The input is given from Standard Input in the following format:
N T
A_1 A_2 ... A_N
-----Output-----
Print the minimum total cost to decrease Takahashi's expected profit by at least 1 yen.
-----Sample Input-----
3 2
100 50 200
-----Sample Output-----
1
In the initial state, Takahashi can achieve the maximum profit of 150 yen as follows:
- Move from town 1 to town 2.
- Buy one apple for 50 yen at town 2.
- Move from town 2 to town 3.
- Sell one apple for 200 yen at town 3.
If, for example, Aoki changes the price of an apple at town 2 from 50 yen to 51 yen, Takahashi will not be able to achieve the profit of 150 yen. The cost of performing this operation is 1, thus the answer is 1.
There are other ways to decrease Takahashi's expected profit, such as changing the price of an apple at town 3 from 200 yen to 199 yen. | #! /usr/bin/env python3
N, T = map(int, input().split())
A = list(map(int, input().split()))
p = -1
dif = h = hc = lc = c = 0
for i in A[-2::-1]:
a, b = A[p], A[p]-i
if i > a:
p = -c-2
elif b >= dif:
if a != h : h, hc = a, hc+1
if b > dif : dif, lc = b, 0
lc += 1
c += 1
print(min(hc, lc)) | #! /usr/bin/env python3
N, T = map(int, input().split())
A = list(map(int, input().split()))
p = -1
dif = h = hc = lc = c = 0
for i in A[-2::-1]:
a, b = A[p], A[p]-i
if i > a:
p = -c-2
elif b >= dif:
if a != h : h, hc = a, hc+1
if b > dif : dif, lc = b, 0
lc += 1
c += 1
print(min(hc, lc)) | train | APPS_structured |
Lets play some Pong!
![pong](http://gifimage.net/wp-content/uploads/2017/08/pong-gif-3.gif)
For those who don't know what Pong is, it is a simple arcade game where two players can move their paddles to hit a ball towards the opponent's side of the screen, gaining a point for each opponent's miss. You can read more about it [here](https://en.wikipedia.org/wiki/Pong).
___
# Task:
You must finish the `Pong` class. It has a constructor which accepts the `maximum score` a player can get throughout the game, and a method called `play`. This method determines whether the current player hit the ball or not, i.e. if the paddle is at the sufficient height to hit it back. There're 4 possible outcomes: player successfully hits the ball back, player misses the ball, player misses the ball **and his opponent reaches the maximum score winning the game**, either player tries to hit a ball despite the game being over. You can see the input and output description in detail below.
### "Play" method input:
* ball position - The Y coordinate of the ball
* player position - The Y coordinate of the centre(!) of the current player's paddle
### "Play" method output:
One of the following strings:
* `"Player X has hit the ball!"` - If the ball "hits" the paddle
* `"Player X has missed the ball!"` - If the ball is above/below the paddle
* `"Player X has won the game!"` - If one of the players has reached the maximum score
* `"Game Over!"` - If the game has ended but either player still hits the ball
### Important notes:
* Players take turns hitting the ball, always starting the game with the Player 1.
* The paddles are `7` pixels in height.
* The ball is `1` pixel in height.
___
## Example | class Pong:
def __init__(self, max_score):
self.max_score = max_score
self.next = 1
self.score = {1: 0, 2: 0}
def play(self, ball, paddle):
if max(self.score.values()) >= self.max_score:
return "Game Over!"
current, self.next = self.next, 3 - self.next
if paddle - 4 < ball < paddle + 4:
return f"Player {current} has hit the ball!"
else:
self.score[current] += 1
if self.score[current] == self.max_score:
return f"Player {self.next} has won the game!"
return f"Player {current} has missed the ball!" | class Pong:
def __init__(self, max_score):
self.max_score = max_score
self.next = 1
self.score = {1: 0, 2: 0}
def play(self, ball, paddle):
if max(self.score.values()) >= self.max_score:
return "Game Over!"
current, self.next = self.next, 3 - self.next
if paddle - 4 < ball < paddle + 4:
return f"Player {current} has hit the ball!"
else:
self.score[current] += 1
if self.score[current] == self.max_score:
return f"Player {self.next} has won the game!"
return f"Player {current} has missed the ball!" | train | APPS_structured |
A carpet shop sells carpets in different varieties. Each carpet can come in a different roll width and can have a different price per square meter.
Write a function `cost_of_carpet` which calculates the cost (rounded to 2 decimal places) of carpeting a room, following these constraints:
* The carpeting has to be done in one unique piece. If not possible, retrun `"error"`.
* The shop sells any length of a roll of carpets, but always with a full width.
* The cost has to be minimal.
* The length of the room passed as argument can sometimes be shorter than its width (because we define these relatively to the position of the door in the room).
* A length or width equal to zero is considered invalid, return `"error"` if it occurs.
INPUTS:
`room_width`, `room_length`, `roll_width`, `roll_cost` as floats.
OUTPUT:
`"error"` or the minimal cost of the room carpeting, rounded to two decimal places. | def cost_of_carpet(room_length, room_width, roll_width, roll_cost):
if 0 in [room_length, room_width]:
return "error"
mi, mx = min((room_length, room_width)), max((room_length, room_width))
rw, rc = roll_width, roll_cost
return round(mi * rw * rc, 2) if mx <= roll_width else (round(mx * rw * rc, 2) if roll_width >= mi else "error") | def cost_of_carpet(room_length, room_width, roll_width, roll_cost):
if 0 in [room_length, room_width]:
return "error"
mi, mx = min((room_length, room_width)), max((room_length, room_width))
rw, rc = roll_width, roll_cost
return round(mi * rw * rc, 2) if mx <= roll_width else (round(mx * rw * rc, 2) if roll_width >= mi else "error") | train | APPS_structured |
Your task is to return the sum of Triangular Numbers up-to-and-including the `nth` Triangular Number.
Triangular Number: "any of the series of numbers (1, 3, 6, 10, 15, etc.) obtained by continued summation of the natural numbers 1, 2, 3, 4, 5, etc."
```
[01]
02 [03]
04 05 [06]
07 08 09 [10]
11 12 13 14 [15]
16 17 18 19 20 [21]
```
e.g. If `4` is given: `1 + 3 + 6 + 10 = 20`.
Triangular Numbers cannot be negative so return 0 if a negative number is given. | def sum_triangular_numbers(n):
return 0 if n <= 0 else sum([i for i in range(1, n+1)]) + sum_triangular_numbers(n-1) | def sum_triangular_numbers(n):
return 0 if n <= 0 else sum([i for i in range(1, n+1)]) + sum_triangular_numbers(n-1) | train | APPS_structured |
Our friendly friend Pete is really a nice person, but he tends to be rather... Inappropriate.
And possibly loud, if given enough ethanol and free rein, so we ask you to write a function that should take its not always "clean" speech and cover as much as possible of it, in order not to offend some more sensible spirits.
For example, given an input like
```
What the hell am I doing here? And where is my wallet? PETE SMASH!
```
You are expected to turn it into something like:
```
W**t t*e h**l am i d***g h**e? A*d w***e is my w****t? P**e s***h!
```
In case you didn't figure out the rules yet: any words longer than 2 characters need to have its "inside" (meaning every character which is not the first or the last) changed into `*`; as we do not want Pete to scream too much, every uppercase letter which is not at the beginning of the string or coming after a punctuation mark among [".","!","?"] needs to be put to lowercase; spaces and other punctuation marks can be ignored.
Conversely, you need to be sure that the start of each sentence has a capitalized word at the beginning. Sentences are divided by the aforementioned punctuation marks.
Finally, the function will take an additional parameter consisting of an array/list of allowed words (upper or lower case) which are not to be replaced (the match has to be case insensitive).
Extra cookies if you can do it all in some efficient way and/or using our dear regexes ;)
**Note:** Absolutely not related to [a certain codewarrior I know](http://www.codewars.com/users/petegarvin1) :p | import re
def pete_talk(s, a=None):
a = {x.lower() for x in a or []}
def f(x):
x = x[0]
return x if x.lower() in a else x[0] + "*" * (len(x) - 2) + x[-1] * (len(x) > 1)
return "".join(x.capitalize() for x in re.split(r"([!?.] ?)", re.sub(r"\w+", f, s))) | import re
def pete_talk(s, a=None):
a = {x.lower() for x in a or []}
def f(x):
x = x[0]
return x if x.lower() in a else x[0] + "*" * (len(x) - 2) + x[-1] * (len(x) > 1)
return "".join(x.capitalize() for x in re.split(r"([!?.] ?)", re.sub(r"\w+", f, s))) | train | APPS_structured |
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
Example 1:
Input: "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (12).
Example 2:
Input: "226"
Output: 3
Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). | class Solution:
def numDecodings(self, s):
"""
:type s: str
:rtype: int
"""
if s == None or len(s) == 0:
return 0
def in10(c):
return c.isdigit() and c>'0' and c<='9'
def in26(c):
return c.isdigit() and c>='10' and c<='26'
memo = [0 for _ in range(len(s))]
if in10(s[0]):
memo[0] = 1
for i in range(1, len(s)):
if i == 1:
if in10(s[i]):
memo[i] = memo[i-1]
if in26(s[:2]):
memo[i] = memo[i] + 1
else:
if in10(s[i]):
memo[i] += memo[i-1]
if in26(s[i-1:i+1]):
memo[i] += memo[i-2]
return memo[-1]
| class Solution:
def numDecodings(self, s):
"""
:type s: str
:rtype: int
"""
if s == None or len(s) == 0:
return 0
def in10(c):
return c.isdigit() and c>'0' and c<='9'
def in26(c):
return c.isdigit() and c>='10' and c<='26'
memo = [0 for _ in range(len(s))]
if in10(s[0]):
memo[0] = 1
for i in range(1, len(s)):
if i == 1:
if in10(s[i]):
memo[i] = memo[i-1]
if in26(s[:2]):
memo[i] = memo[i] + 1
else:
if in10(s[i]):
memo[i] += memo[i-1]
if in26(s[i-1:i+1]):
memo[i] += memo[i-2]
return memo[-1]
| train | APPS_structured |
We have the numbers with different colours with the sequence: ['red', 'yellow', 'blue'].
That sequence colours the numbers in the following way:
1 2 3 4 5 6 7 8 9 10 11 12 13 .....
We have got the following recursive function:
```
f(1) = 1
f(n) = f(n - 1) + n
```
Some terms of this sequence with their corresponding colour are:
```
term value colour
1 1 "red"
2 3 "blue"
3 6 "blue"
4 10 "red"
5 15 "blue"
6 21 "blue"
7 28 "red"
```
The three terms of the same colour "blue", higher than 3, are: `[6, 15, 21]`
We need a function `same_col_seq(), that may receive three arguments:
- `val`, an integer number
- `k`, an integer number
- `colour`, the name of one of the three colours(red, yellow or blue), as a string.
The function will output a sorted array with the smallest `k` terms, having the same marked colour, but higher than `val`.
Let's see some examples:
```python
same_col_seq(3, 3, 'blue') == [6, 15, 21]
same_col_seq(100, 4, 'red') == [136, 190, 253, 325]
```
The function may output an empty list if it does not find terms of the sequence with the wanted colour in the range [val, 2* k * val]
```python
same_col_seq(250, 6, 'yellow') == []
```
That means that the function did not find any "yellow" term in the range `[250, 3000]`
Tests will be with the following features:
* Nmber of tests: `100`
* `100 < val < 1000000`
* `3 < k < 20` | li, i, pos, d = ['red', 'yellow', 'blue'], 1, 1, {}
while i < 2000:
d[pos] = li[(pos - 1) % 3]
i += 1 ; pos += i
def same_col_seq(after, k, need):
req, status = [], 0
for i, j in d.items():
if i > after : status = 1
if status:
if j == need : req.append(i)
if len(req) == k or i >= 2 * k * after : break
return req | li, i, pos, d = ['red', 'yellow', 'blue'], 1, 1, {}
while i < 2000:
d[pos] = li[(pos - 1) % 3]
i += 1 ; pos += i
def same_col_seq(after, k, need):
req, status = [], 0
for i, j in d.items():
if i > after : status = 1
if status:
if j == need : req.append(i)
if len(req) == k or i >= 2 * k * after : break
return req | train | APPS_structured |
Kostya likes the number 4 much. Of course! This number has such a lot of properties, like:
- Four is the smallest composite number;
- It is also the smallest Smith number;
- The smallest non-cyclic group has four elements;
- Four is the maximal degree of the equation that can be solved in radicals;
- There is four-color theorem that states that any map can be colored in no more than four colors in such a way that no two adjacent regions are colored in the same color;
- Lagrange's four-square theorem states that every positive integer can be written as the sum of at most four square numbers;
- Four is the maximum number of dimensions of a real division algebra;
- In bases 6 and 12, 4 is a 1-automorphic number;
- And there are a lot more cool stuff about this number!
Impressed by the power of this number, Kostya has begun to look for occurrences of four anywhere. He has a list of T integers, for each of them he wants to calculate the number of occurrences of the digit 4 in the decimal representation. He is too busy now, so please help him.
-----Input-----
The first line of input consists of a single integer T, denoting the number of integers in Kostya's list.
Then, there are T lines, each of them contain a single integer from the list.
-----Output-----
Output T lines. Each of these lines should contain the number of occurences of the digit 4 in the respective integer from Kostya's list.
-----Constraints-----
- 1 ≤ T ≤ 105
- (Subtask 1): 0 ≤ Numbers from the list ≤ 9 - 33 points.
- (Subtask 2): 0 ≤ Numbers from the list ≤ 109 - 67 points.
-----Example-----
Input:
5
447474
228
6664
40
81
Output:
4
0
1
1
0 | # cook your dish here
n=int(input())
a=[]
for i in range (0,n):
no=int(input())
a.append(no)
for i in range (0,n):
c=0
while (a[i]!=0):
if (a[i]%10==4):
c+=1
a[i]=a[i]//10
print(c) | # cook your dish here
n=int(input())
a=[]
for i in range (0,n):
no=int(input())
a.append(no)
for i in range (0,n):
c=0
while (a[i]!=0):
if (a[i]%10==4):
c+=1
a[i]=a[i]//10
print(c) | train | APPS_structured |
Implement a data structure supporting the following operations:
Inc(Key) - Inserts a new key with value 1. Or increments an existing key by 1. Key is guaranteed to be a non-empty string.
Dec(Key) - If Key's value is 1, remove it from the data structure. Otherwise decrements an existing key by 1. If the key does not exist, this function does nothing. Key is guaranteed to be a non-empty string.
GetMaxKey() - Returns one of the keys with maximal value. If no element exists, return an empty string "".
GetMinKey() - Returns one of the keys with minimal value. If no element exists, return an empty string "".
Challenge: Perform all these in O(1) time complexity. | class DLL:
def __init__(self, val, key):
self.val = val
self.key = key
self.next = None
self.prev = None
class AllOne:
def __init__(self):
"""
Initialize your data structure here.
"""
self.hash = {}
self.head = None
self.tail = None
def inc(self, key):
"""
Inserts a new key <Key> with value 1. Or increments an existing key by 1.
:type key: str
:rtype: void
"""
self.print_dll()
dll = self.hash.get(key, None)
if not dll:
dll = DLL(1, key)
self.insert_dll(dll)
self.hash[key] = dll
else:
self.incr_dll(dll)
def dec(self, key):
"""
Decrements an existing key by 1. If Key's value is 1, remove it from the data structure.
:type key: str
:rtype: void
"""
self.print_dll()
dll = self.hash.get(key, None)
if not dll:return
self.decr_dll(dll)
if dll.val == 0:
del self.hash[key]
def getMaxKey(self):
"""
Returns one of the keys with maximal value.
:rtype: str
"""
if self.head:
return self.head.key
return ""
def getMinKey(self):
"""
Returns one of the keys with Minimal value.
:rtype: str
"""
if self.tail:
return self.tail.key
return ""
def insert_dll(self, dll):
if self.tail:
self.tail.next = dll
self.tail.next.prev = self.tail
self.tail = dll
else:
self.head = dll
self.tail = dll
def incr_dll(self, dll):
dll.val = dll.val + 1
while dll.prev and dll.val > dll.prev.val:
prev = dll.prev
prev_prev = dll.prev.prev
next_node = dll.next
dll.next = prev
prev.next = next_node
dll.prev = prev_prev
prev.prev = dll
if prev_prev:
prev_prev.next = dll
else:
self.head = dll
if next_node:
next_node.prev = prev
else:
self.tail = prev
def decr_dll(self, dll):
dll.val = dll.val - 1
if dll.val == 0 :
if dll.prev:
dll.prev.next = dll.next
else:
self.head = dll.next
if dll.next:
dll.next.prev = dll.prev
else:
self.tail = dll.prev
elif dll.next and dll.val < dll.next.val:
next_node = dll.next
next_next = dll.next.next
prev = dll.prev
dll.next = next_next
dll.prev = next_node
next_node.next = dll
next_node.prev = prev
if next_next:
next_next.prev = dll
else:
self.tail = dll
if prev:
prev.next = next_node
else:
self.head = next_node
def print_dll(self):
temp = self.head
# while temp:
# print("%s %s" % (temp.key, str(temp.val)))
# temp = temp.next
# print("End")
# Your AllOne object will be instantiated and called as such:
# obj = AllOne()
# obj.inc(key)
# obj.dec(key)
# param_3 = obj.getMaxKey()
# param_4 = obj.getMinKey() | class DLL:
def __init__(self, val, key):
self.val = val
self.key = key
self.next = None
self.prev = None
class AllOne:
def __init__(self):
"""
Initialize your data structure here.
"""
self.hash = {}
self.head = None
self.tail = None
def inc(self, key):
"""
Inserts a new key <Key> with value 1. Or increments an existing key by 1.
:type key: str
:rtype: void
"""
self.print_dll()
dll = self.hash.get(key, None)
if not dll:
dll = DLL(1, key)
self.insert_dll(dll)
self.hash[key] = dll
else:
self.incr_dll(dll)
def dec(self, key):
"""
Decrements an existing key by 1. If Key's value is 1, remove it from the data structure.
:type key: str
:rtype: void
"""
self.print_dll()
dll = self.hash.get(key, None)
if not dll:return
self.decr_dll(dll)
if dll.val == 0:
del self.hash[key]
def getMaxKey(self):
"""
Returns one of the keys with maximal value.
:rtype: str
"""
if self.head:
return self.head.key
return ""
def getMinKey(self):
"""
Returns one of the keys with Minimal value.
:rtype: str
"""
if self.tail:
return self.tail.key
return ""
def insert_dll(self, dll):
if self.tail:
self.tail.next = dll
self.tail.next.prev = self.tail
self.tail = dll
else:
self.head = dll
self.tail = dll
def incr_dll(self, dll):
dll.val = dll.val + 1
while dll.prev and dll.val > dll.prev.val:
prev = dll.prev
prev_prev = dll.prev.prev
next_node = dll.next
dll.next = prev
prev.next = next_node
dll.prev = prev_prev
prev.prev = dll
if prev_prev:
prev_prev.next = dll
else:
self.head = dll
if next_node:
next_node.prev = prev
else:
self.tail = prev
def decr_dll(self, dll):
dll.val = dll.val - 1
if dll.val == 0 :
if dll.prev:
dll.prev.next = dll.next
else:
self.head = dll.next
if dll.next:
dll.next.prev = dll.prev
else:
self.tail = dll.prev
elif dll.next and dll.val < dll.next.val:
next_node = dll.next
next_next = dll.next.next
prev = dll.prev
dll.next = next_next
dll.prev = next_node
next_node.next = dll
next_node.prev = prev
if next_next:
next_next.prev = dll
else:
self.tail = dll
if prev:
prev.next = next_node
else:
self.head = next_node
def print_dll(self):
temp = self.head
# while temp:
# print("%s %s" % (temp.key, str(temp.val)))
# temp = temp.next
# print("End")
# Your AllOne object will be instantiated and called as such:
# obj = AllOne()
# obj.inc(key)
# obj.dec(key)
# param_3 = obj.getMaxKey()
# param_4 = obj.getMinKey() | train | APPS_structured |
Dr. S. De teaches computer architecture in NIT Patna. Whenever he comes across any good question(with complexity $k$), he gives that question to students within roll number range $i$ and $j$
At the start of semester he assigns score of $10$ to every student in his class if a student submits a question of complexity $k$, his score gets multiplied by $k$
This month he gave $M$ questions and he is wondering what will be mean of maximum scores of all the student. He is busy in improving his finger print attendance module, can you help him?
Input file may be large so try to use fast input output
-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a First line of input, two integers $N, M$ i.e. Number of students in the class and number of questions given in this month.
- Next $M$ lines contains 3 integers -$i, j, k$ i.e. starting roll number, end roll number and complexity of the question
-----Output:-----
For each testcase, output in a single line answer - $floor$ value of Mean of maximum possible score for all students.
-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq N, M \leq 10^5$
- $1 \leq i \leq j \leq N$
- $1 \leq k \leq 100$
-----Subtasks-----
Subtask1
-
$1 \leq T \leq 10$
-
$1 \leq N, M \leq 10^4$
Subtask2
-
Original Constraints
-----Sample Input:-----
1
5 3
1 3 5
2 5 2
3 4 7
-----Sample Output:-----
202
-----EXPLANATION:-----
Initial score of students will be : $[10, 10, 10, 10, 10]$
after solving question 1 scores will be: $[50, 50, 50, 10, 10]$
after solving question 2 scores will be: $[50, 100, 100, 20, 20]$
after solving question 1 scores will be: $[50, 100, 700, 140, 20]$
Hence after all questions mean of maximum scores will $(50+100+700+140+20)/5 = 202$ | from sys import stdin, stdout
import numpy as np
t = int(stdin.readline())
while t>0:
t-=1
n,m = stdin.readline().split()
n= int(n)
m = int(m)
b = [1]*(n+1)
c = [1]*(n+1)
b = np.asarray(b)
c = np.asarray(c)
while m>0:
m-=1
i,j,k = stdin.readline().split()
i=int(i)
j=int(j)
k=int(k)
b[i-1]*=k;
c[j]*=k;
ar = [10]*(n+1)
ar = np.asarray(ar)
ar[0] = b[0];
ar[0]/=c[0];
for i in range(n):
ar[i] = ar[i-1];
ar[i] *= b[i];
ar[i]/= (c[i]);
Sum=0
for i in range(n):
Sum+=ar[i];
print(int(Sum/n))
| from sys import stdin, stdout
import numpy as np
t = int(stdin.readline())
while t>0:
t-=1
n,m = stdin.readline().split()
n= int(n)
m = int(m)
b = [1]*(n+1)
c = [1]*(n+1)
b = np.asarray(b)
c = np.asarray(c)
while m>0:
m-=1
i,j,k = stdin.readline().split()
i=int(i)
j=int(j)
k=int(k)
b[i-1]*=k;
c[j]*=k;
ar = [10]*(n+1)
ar = np.asarray(ar)
ar[0] = b[0];
ar[0]/=c[0];
for i in range(n):
ar[i] = ar[i-1];
ar[i] *= b[i];
ar[i]/= (c[i]);
Sum=0
for i in range(n):
Sum+=ar[i];
print(int(Sum/n))
| train | APPS_structured |
Chef has just learned a new data structure - Fenwick tree. This data structure holds information about array of N elements and can process two types of operations:
- Add some value to ith element of the array
- Calculate sum of all elements on any prefix of the array
Both operations take O(log N) time. This data structure is also well known for its low memory usage. To be more precise, it needs exactly the same amount of memory as that of array.
Given some array A, first we build data structure in some other array T. Ti stores the sum of the elements Astart, Astart + 1, ..., Ai. Index start is calculated with formula start = Fdown(i) = (i & (i + 1)). Here "&" denotes bitwise AND operation.
So, in order to find a sum of elements A0, A1, ..., AL you start with index L and calculate sum of TL + TFdown(L)-1 + TFdown(Fdown(L)-1)-1 + ... + TFdown(Fdown(...(Fdown(L)-1)-1)-1. Usually it is performed with cycle that goes from L down to 0 with function Fdown and sums some elements from T. Chef wants to verify that the time complexity to calculate sum of A0, A1, A2, ..., AL is O(log L). In order to do so, he wonders how many times he has to access array T to calculate this sum. Help him to find this out.
Since Chef works with really big indices. The value of L can be very large and is provided to you in binary representation as concatenation of strings L1, L2 repeated N times and string L3.
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The only line of each test case contains three non-empty strings L1, L2, L3 and an integer N. Strings will contain only characters 0 and 1. To obtain binary representation of index L concatenate L1 with L2 repeated N times and with L3. You are guaranteed that the index will be positive.
-----Output-----
For each test case, output a single line containing number of times Fenwick tree data structure will access array T in order to compute sum of A0, A1, A2, ..., AL.
-----Constraints-----
- 1 ≤ T ≤ 300
- 1 ≤ Length(Li) ≤ 1000
- 1 ≤ N ≤ 106
-----Subtasks-----
- Subtask #1 (20 points): |L1| + |L2| * N + |L3| ≤ 60
- Subtask #2 (30 points): 1 ≤ T ≤ 30, 1 ≤ N ≤ 100
- Subtask #3 (50 points): No additional constraints
-----Example-----
Input:
4
001 100 011 4
1000 1101 100 3
1010 001 101 4
010 101 000 4
Output:
6
12
8
10 | t=int(input())
count=[]
for i in range(t) :
s = input()
a,b,c,n = s.split()
n=int(n)
d = int(a+b*n+c,2)
count.append(0)
while(d>0) :
d=(d&(d+1))-1
count[i]+=1
for i in range(t) :
print(count[i])
| t=int(input())
count=[]
for i in range(t) :
s = input()
a,b,c,n = s.split()
n=int(n)
d = int(a+b*n+c,2)
count.append(0)
while(d>0) :
d=(d&(d+1))-1
count[i]+=1
for i in range(t) :
print(count[i])
| train | APPS_structured |
In English and programming, groups can be made using symbols such as `()` and `{}` that change meaning. However, these groups must be closed in the correct order to maintain correct syntax.
Your job in this kata will be to make a program that checks a string for correct grouping. For instance, the following groups are done correctly:
```
({})
[[]()]
[{()}]
```
The next are done incorrectly:
```
{(})
([]
[])
```
A correct string cannot close groups in the wrong order, open a group but fail to close it, or close a group before it is opened.
Your function will take an input string that may contain any of the symbols `()`, `{}` or `[]` to create groups.
It should return `True` if the string is empty or otherwise grouped correctly, or `False` if it is grouped incorrectly. | def group_check(s):
while "{}" in s or "()" in s or "[]" in s:
s = s.replace("{}","").replace("()","").replace("[]","")
return not s | def group_check(s):
while "{}" in s or "()" in s or "[]" in s:
s = s.replace("{}","").replace("()","").replace("[]","")
return not s | train | APPS_structured |
Given two words and a letter, return a single word that's a combination of both words, merged at the point where the given letter first appears in each word. The returned word should have the beginning of the first word and the ending of the second, with the dividing letter in the middle. You can assume both words will contain the dividing letter.
## Examples
```python
string_merge("hello", "world", "l") ==> "held"
string_merge("coding", "anywhere", "n") ==> "codinywhere"
string_merge("jason", "samson", "s") ==> "jasamson"
string_merge("wonderful", "people", "e") ==> "wondeople"
``` | def string_merge(string1, string2, letter):
"""given two words and a letter, merge one word that combines both at the first occurence of
the letter
>>> "hello","world","l"
held
>>> "jason","samson","s"
jasamson
"""
return string1[0:(string1.find(letter))] + string2[(string2.find(letter)):] | def string_merge(string1, string2, letter):
"""given two words and a letter, merge one word that combines both at the first occurence of
the letter
>>> "hello","world","l"
held
>>> "jason","samson","s"
jasamson
"""
return string1[0:(string1.find(letter))] + string2[(string2.find(letter)):] | train | APPS_structured |
There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back.
Jinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that: this list contains all Jinotega's flights in this year (in arbitrary order), Jinotega has only flown from his hometown to a snooker contest and back, after each competition Jinotega flies back home (though they may attend a competition in one place several times), and finally, at the beginning of the year Jinotega was at home.
Please help them to determine Jinotega's location!
-----Input-----
In the first line of input there is a single integer n: the number of Jinotega's flights (1 ≤ n ≤ 100). In the second line there is a string of 3 capital Latin letters: the name of Jinotega's home airport. In the next n lines there is flight information, one flight per line, in form "XXX->YYY", where "XXX" is the name of departure airport "YYY" is the name of arrival airport. Exactly one of these airports is Jinotega's home airport.
It is guaranteed that flights information is consistent with the knowledge of Jinotega's friends, which is described in the main part of the statement.
-----Output-----
If Jinotega is now at home, print "home" (without quotes), otherwise print "contest".
-----Examples-----
Input
4
SVO
SVO->CDG
LHR->SVO
SVO->LHR
CDG->SVO
Output
home
Input
3
SVO
SVO->HKT
HKT->SVO
SVO->RAP
Output
contest
-----Note-----
In the first sample Jinotega might first fly from SVO to CDG and back, and then from SVO to LHR and back, so now they should be at home. In the second sample Jinotega must now be at RAP because a flight from RAP back to SVO is not on the list. | n = int(input())
h = input()
d = []
for _ in range(n):
s = input()
fr = s[:3]
to = s[5:]
if (to, fr) in d:
del d[d.index((to, fr))]
else:
d.append((fr, to))
if len(d):
print('contest')
else:
print('home') | n = int(input())
h = input()
d = []
for _ in range(n):
s = input()
fr = s[:3]
to = s[5:]
if (to, fr) in d:
del d[d.index((to, fr))]
else:
d.append((fr, to))
if len(d):
print('contest')
else:
print('home') | train | APPS_structured |
Math geeks and computer nerds love to anthropomorphize numbers and assign emotions and personalities to them. Thus there is defined the concept of a "happy" number. A happy number is defined as an integer in which the following sequence ends with the number 1.
* Start with the number itself.
* Calculate the sum of the square of each individual digit.
* If the sum is equal to 1, then the number is happy. If the sum is not equal to 1, then repeat steps 1 and 2. A number is considered unhappy once the same number occurs multiple times in a sequence because this means there is a loop and it will never reach 1.
For example, the number 7 is a "happy" number:
7^(2) = 49 --> 4^(2) + 9^(2) = 97 --> 9^(2) + 7^(2) = 130 --> 1^(2) + 3^(2) + 0^(2) = 10 --> 1^(2) + 0^(2) = 1
Once the sequence reaches the number 1, it will stay there forever since 1^(2) = 1
On the other hand, the number 6 is not a happy number as the sequence that is generated is the following: 6, 36, 45, 41, 17, 50, 25, 29, 85, 89, 145, 42, 20, 4, 16, 37, 58, 89
Once the same number occurs twice in the sequence, the sequence is
guaranteed to go on infinitely, never hitting the number 1, since it repeat
this cycle.
Your task is to write a program which will print a list of all happy numbers between 1 and x (both inclusive), where:
```python
2 <= x <= 5000
```
___
Disclaimer: This Kata is an adaptation of a HW assignment I had for McGill University's COMP 208 (Computers in Engineering) class.
___
If you're up for a challenge, you may want to try a [performance version of this kata](https://www.codewars.com/kata/happy-numbers-performance-edition) by FArekkusu. | def happy_numbers(n):
return [q for q in range(n+1) if isHappy(q)]
def isHappy(o, lister=[]):
#Terminator
if len(lister)>len(set(lister)): return False
#Test for Happiness
summer=sum([int(p)**2 for p in str(o)])
return True if summer==1 else isHappy(summer, lister+[summer]) | def happy_numbers(n):
return [q for q in range(n+1) if isHappy(q)]
def isHappy(o, lister=[]):
#Terminator
if len(lister)>len(set(lister)): return False
#Test for Happiness
summer=sum([int(p)**2 for p in str(o)])
return True if summer==1 else isHappy(summer, lister+[summer]) | train | APPS_structured |
I started this as a joke among friends, telling that converting numbers to other integer bases is for n00bs, while an actual coder at least converts numbers to more complex bases like [pi (or π or however you wish to spell it in your language)](http://en.wikipedia.org/wiki/Pi), so they dared me proving I was better.
And I did it in few hours, discovering that what I started as a joke actually has [some math ground and application (particularly the conversion to base pi, it seems)](http://en.wikipedia.org/wiki/Non-integer_representation).
That said, now I am daring you to do the same, that is to build a function so that it takes a **number** (any number, you are warned!) and optionally the **number of decimals** (default: 0) and a **base** (default: pi), returning the proper conversion **as a string**:
#Note
In Java there is no easy way with optional parameters so all three parameters will be given; the same in C# because, as of now, the used version is not known.
```python
converter(13) #returns '103'
converter(13,3) #returns '103.010'
converter(-13,0,2) #returns '-1101'
```
I know most of the world uses a comma as a [decimal mark](http://en.wikipedia.org/wiki/Decimal_mark), but as English language and culture are *de facto* the Esperanto of us coders, we will stick to our common glorious traditions and uses, adopting the trivial dot (".") as decimal separator; if the absolute value of the result is <1, you have of course to put one (and only one) leading 0 before the decimal separator.
Finally, you may assume that decimals if provided will always be >= 0 and that no test base will be smaller than 2 (because, you know, converting to base 1 is pretty lame) or greater than 36; as usual, for digits greater than 9 you can use uppercase alphabet letter, so your base of numeration is going to be: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
That is my first 3-languages-kata, so I count on you all to give me extensive feedback, no matter how harsh it may sound, so to improve myself even further :) | from math import pi
from math import log
def converter(n, decimals=0, base=pi):
DIGITS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
representation = []
if (n < 0):
representation.append('-')
n *= -1
if (n == 0):
decimalCount = 0
else:
decimalCount = int(log(n, base))
for dplace in [pow(base, power) for power in range(decimalCount, -1 - decimals, -1)]:
rNumber = int(n / dplace)
n -= rNumber * dplace
representation.append(DIGITS[rNumber])
if dplace == 1 and decimals > 0:
representation.append('.')
return ''.join(representation)
| from math import pi
from math import log
def converter(n, decimals=0, base=pi):
DIGITS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
representation = []
if (n < 0):
representation.append('-')
n *= -1
if (n == 0):
decimalCount = 0
else:
decimalCount = int(log(n, base))
for dplace in [pow(base, power) for power in range(decimalCount, -1 - decimals, -1)]:
rNumber = int(n / dplace)
n -= rNumber * dplace
representation.append(DIGITS[rNumber])
if dplace == 1 and decimals > 0:
representation.append('.')
return ''.join(representation)
| train | APPS_structured |
An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case.
```python
is_isogram("Dermatoglyphics" ) == true
is_isogram("aba" ) == false
is_isogram("moOse" ) == false # -- ignore letter case
```
```C
is_isogram("Dermatoglyphics" ) == true;
is_isogram("aba" ) == false;
is_isogram("moOse" ) == false; // -- ignore letter case
``` | def is_isogram(string):
return len(string) == len(set(string.lower())) | def is_isogram(string):
return len(string) == len(set(string.lower())) | train | APPS_structured |
Deoxyribonucleic acid, DNA is the primary information storage molecule in biological systems. It is composed of four nucleic acid bases Guanine ('G'), Cytosine ('C'), Adenine ('A'), and Thymine ('T').
Ribonucleic acid, RNA, is the primary messenger molecule in cells. RNA differs slightly from DNA its chemical structure and contains no Thymine. In RNA Thymine is replaced by another nucleic acid Uracil ('U').
Create a function which translates a given DNA string into RNA.
For example:
```
"GCAT" => "GCAU"
```
The input string can be of arbitrary length - in particular, it may be empty. All input is guaranteed to be valid, i.e. each input string will only ever consist of `'G'`, `'C'`, `'A'` and/or `'T'`. | #! python3
import re
dnaRegex = re.compile(r'T')
def dna_to_rna(dna):
return dnaRegex.sub('U',dna)
| #! python3
import re
dnaRegex = re.compile(r'T')
def dna_to_rna(dna):
return dnaRegex.sub('U',dna)
| train | APPS_structured |
There is a haunted town called HauntedLand. The structure of HauntedLand can be thought of as a grid of size n * m. There is a house in each cell of the grid. Some people have fled from their houses because they were haunted. '.' represents a haunted house whereas '*' represents a house in which people are living.
One day, Devu, the famous perfumer came to town with a perfume whose smell can hypnotize people. Devu can put the perfume in at most one of the houses. This takes Devu one second. Then, the perfume spreads from one house (need not be inhabited by people) to all its adjacent houses in one second, and the cycle continues. Two houses are said to be a adjacent to each other, if they share a corner or an edge, i.e., each house (except those on the boundaries) will have 8 adjacent houses.
You want to save people from Devu's dark perfumery by sending them a message to flee from the town. So, you need to estimate the minimum amount of time Devu needs to hypnotize all the people? Note that if there are no houses inhabited by people, Devu doesn't need to put perfume in any cell.
-----Input-----
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows.
First line of each test case contains two space separated integers n, m denoting the dimensions of the town.
For each of next n lines, each line has m characters (without any space) denoting a row of houses of the town.
-----Output-----
For each test case, output a single integer corresponding to the answer of the problem.
-----Constraints-----
- 1 ≤ T ≤ 20
Subtask #1: (40 points)
- 1 ≤ n, m ≤ 100Subtask #2: (60 points)
- 1 ≤ n, m ≤ 1000
-----Example-----
Input:
2
2 2
*...
3 4
.*..***..*..
Output:
1
2
-----Explanation-----
In the first example, it will take Devu one second for putting the perfume at the only house. So, the answer is 1.
In the second example, He will first put the perfume at the * at cell (1, 1) (assuming 0-based indexing).
Now, it will take Devu 1 secs to put perfume. In the next second, the perfume will spread to all of its adjacent cells, thus making each house haunted.
So, the answer is 2. | for _ in range(int(input())):
x,y=list(map(int,input().split()))
p=q=c=0
r=s=1001
for i in range(x):
a=input()
for j in range(y):
if a[j]=='*':
c=1
#print i,j
if i>p:
p=i
if j>q:
q=j
if i<r:
r=i
if j<s:
s=j
g=p-((p+r)//2)
h=q-((q+s)//2)
if c:
c+=max(g,h)
print(c) | for _ in range(int(input())):
x,y=list(map(int,input().split()))
p=q=c=0
r=s=1001
for i in range(x):
a=input()
for j in range(y):
if a[j]=='*':
c=1
#print i,j
if i>p:
p=i
if j>q:
q=j
if i<r:
r=i
if j<s:
s=j
g=p-((p+r)//2)
h=q-((q+s)//2)
if c:
c+=max(g,h)
print(c) | train | APPS_structured |
Mr Leicester's cheese factory is the pride of the East Midlands, but he's feeling a little blue. It's the time of the year when **the taxman is coming round to take a slice of his cheddar** - and the final thing he has to work out is how much money he's spending on his staff. Poor Mr Leicester can barely sleep he's so stressed. Can you help?
- Mr Leicester **employs 4 staff**, who together make **10 wheels of cheese every 6 minutes**.
- Worker pay is calculated on **how many wheels of cheese they produce in a day**.
- Mr Leicester pays his staff according to the UK living wage, which is currently **£8.75p an hour**. There are **100 pence (p) to the UK pound (£)**.
The input for function payCheese will be provided as an array of five integers, one for each amount of cheese wheels produced each day.
When the workforce don't work a nice integer number of minutes - much to the chagrin of the company accountant - Mr Leicester very generously **rounds up to the nearest hour** at the end of the week (*not the end of each day*). Which means if the workers make 574 wheels on each day of the week, they're each paid 29 hours for the week (28.699 hours rounded up) and not 30 (6 hours a day rounded up * 5).
The return value should be a string (with the £ included) of the **total £ of staff wages for that week.** | from math import ceil
def pay_cheese(lst):
return f"L{35 * ceil(sum(lst) / 100)}" | from math import ceil
def pay_cheese(lst):
return f"L{35 * ceil(sum(lst) / 100)}" | train | APPS_structured |
Ripul was skilled in the art of lapidary. He used to collect stones and convert it into decorative items for sale. There were n stone shops. Each shop was having one exclusive stone of value s[i] , where 1<=i<=n. If number of stones collected are more than 1, then total value will be product of values of all the stones he collected. Ripul wants to have maximum value of stones he collected. Help Ripul in picking up the subarray which leads to maximum value of stones he collected.
-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- The first line of each testcase contains an integer $N$, denoting number of elements in the given array.
- The second line contains $N$ space-separated integers $S1$, $S2$, …, $SN$ denoting the value of stone in each shop.
-----Output:-----
For each testcase, output the maximum value of stones possible, the starting index and ending index of the chosen subarray (0-based indexing). If there are multiple subarrays with same value, print the one with greater starting index. If there are multiple answer subarrays with same starting index, print the one with greater ending index. (The answer will fit in 64 bit binary number).
-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq N \leq 10^5$
- $-100 \leq S[i] \leq 100$
-----Subtasks-----
- 30 points : $1 \leq N \leq 10^3$
- 70 points : $1 \leq N \leq 10^5$
-----Sample Input:-----
1
3
1 2 3
-----Sample Output:-----
6 1 2
-----EXPLANATION:-----
If Ripul collects all the all the three gems, total value will be 6 (1 * 2 * 3).
If Ripul collects last two gems, total value will be 6 (1 * 2 * 3).
So, he picks the subarray with greater starting index. | import numpy
for _ in range(int(input())):
n=int(input())
l=list(map(int,input().split()))
ans=float('-inf')
iidx=0
fidx=0
for i in range(len(l) + 1):
for j in range(i + 1, len(l) + 1):
sub = l[i:j]
if len(sub)==0:
continue
p=numpy.prod(sub)
if p>=ans:
ans=p
if i>=iidx:
iidx=i
if j>=fidx:
fidx=j
print(ans,iidx,fidx-1)
| import numpy
for _ in range(int(input())):
n=int(input())
l=list(map(int,input().split()))
ans=float('-inf')
iidx=0
fidx=0
for i in range(len(l) + 1):
for j in range(i + 1, len(l) + 1):
sub = l[i:j]
if len(sub)==0:
continue
p=numpy.prod(sub)
if p>=ans:
ans=p
if i>=iidx:
iidx=i
if j>=fidx:
fidx=j
print(ans,iidx,fidx-1)
| train | APPS_structured |
Given an array arr. You can choose a set of integers and remove all the occurrences of these integers in the array.
Return the minimum size of the set so that at least half of the integers of the array are removed.
Example 1:
Input: arr = [3,3,3,3,5,5,5,2,2,7]
Output: 2
Explanation: Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array).
Possible sets of size 2 are {3,5},{3,2},{5,2}.
Choosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has size greater than half of the size of the old array.
Example 2:
Input: arr = [7,7,7,7,7,7]
Output: 1
Explanation: The only possible set you can choose is {7}. This will make the new array empty.
Example 3:
Input: arr = [1,9]
Output: 1
Example 4:
Input: arr = [1000,1000,3,7]
Output: 1
Example 5:
Input: arr = [1,2,3,4,5,6,7,8,9,10]
Output: 5
Constraints:
1 <= arr.length <= 10^5
arr.length is even.
1 <= arr[i] <= 10^5 | from collections import Counter
class Solution:
def minSetSize(self, arr: List[int]) -> int:
cnt = Counter(arr)
temp = sorted(list(cnt.keys()), key = lambda x: cnt[x])
curr = 0
for i in range(1, len(temp)+1):
curr += cnt[temp[-i]]
if curr >= len(arr)/2:
return i
| from collections import Counter
class Solution:
def minSetSize(self, arr: List[int]) -> int:
cnt = Counter(arr)
temp = sorted(list(cnt.keys()), key = lambda x: cnt[x])
curr = 0
for i in range(1, len(temp)+1):
curr += cnt[temp[-i]]
if curr >= len(arr)/2:
return i
| train | APPS_structured |
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!! | harmon_pointTrip=lambda a,b,c:round(1.*(b*(c-a)+a*(c-b))/((c-a)+(c-b)),4) | harmon_pointTrip=lambda a,b,c:round(1.*(b*(c-a)+a*(c-b))/((c-a)+(c-b)),4) | train | APPS_structured |
In another Kata I came across a weird `sort` function to implement. We had to sort characters as usual ( 'A' before 'Z' and 'Z' before 'a' ) except that the `numbers` had to be sorted **after** the `letters` ( '0' after 'z') !!!
(After a couple of hours trying to solve this unusual-sorting-kata I discovered final tests used **usual** sort (digits **before** letters :-)
So, the `unusualSort/unusual_sort` function you'll have to code will sort `letters` as usual, but will put `digits` (or one-digit-long `numbers` ) **after** `letters`.
## Examples
```python
unusual_sort(["a","z","b"]) # -> ["a","b","z"] as usual
unusual_sort(["a","Z","B"]) # -> ["B","Z","a"] as usual
//... but ...
unusual_sort(["1","z","a"]) # -> ["a","z","1"]
unusual_sort(["1","Z","a"]) # -> ["Z","a","1"]
unusual_sort([3,2,1"a","z","b"]) # -> ["a","b","z",1,2,3]
unusual_sort([3,"2",1,"a","c","b"]) # -> ["a","b","c",1,"2",3]
```
**Note**: `digits` will be sorted **after** "`same-digit-numbers`", eg: `1` is before `"1"`, `"2"` after `2`.
```python
unusual_sort([3,"2",1,"1","3",2]) # -> [1,"1",2,"2",3,"3"]
```
You may assume that **argument** will always be an `array/list` of **characters** or **one-digit-long numbers**. | import string
def unusual_sort(array):
#your code here
upper = sorted([i for i in array if i in list(string.ascii_uppercase)])
lower = sorted([it for it in array if it in list(string.ascii_lowercase)])
intint = sorted([num for num in array if num in list(map(int,list(string.digits)))])
strints = sorted([e for e in array if e in list(string.digits)])
upper.extend(lower)
intint.extend(strints)
want = []
for i in intint:
if type(i) is not int:
want.append((int(i), i))
else:
want.append((i, i))
ans = [i[1] for i in sorted(want,key = lambda x: x[0])]
upper.extend(ans)
return upper | import string
def unusual_sort(array):
#your code here
upper = sorted([i for i in array if i in list(string.ascii_uppercase)])
lower = sorted([it for it in array if it in list(string.ascii_lowercase)])
intint = sorted([num for num in array if num in list(map(int,list(string.digits)))])
strints = sorted([e for e in array if e in list(string.digits)])
upper.extend(lower)
intint.extend(strints)
want = []
for i in intint:
if type(i) is not int:
want.append((int(i), i))
else:
want.append((i, i))
ans = [i[1] for i in sorted(want,key = lambda x: x[0])]
upper.extend(ans)
return upper | train | APPS_structured |
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note:
In the string, each word is separated by single space and there will not be any extra space in the string. | class Solution:
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
words = s.split(" ")
output = []
for i in words:
output += [''.join(reversed(i))]
return ' '.join(output) | class Solution:
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
words = s.split(" ")
output = []
for i in words:
output += [''.join(reversed(i))]
return ' '.join(output) | train | APPS_structured |
You are given a string $s$. And you have a function $f(x)$ defined as:
f(x) = 1, if $x$ is a vowel
f(x) = 0, if $x$ is a constant
Your task is to apply the above function on all the characters in the string s and convert
the obtained binary string in decimal number $M$.
Since the number $M$ can be very large, compute it modulo $10^9+7$.
-----Input:-----
- The first line of the input contains a single integer $T$ i.e the no. of test cases.
- Each test line contains one String $s$ composed of lowercase English alphabet letters.
-----Output:-----
For each case, print a single line containing one integer $M$ modulo $10^9 + 7$.
-----Constraints-----
- $1 ≤ T ≤ 50$
- $|s|≤10^5$
-----Subtasks-----
- 20 points : $|s|≤30$
- 80 points : $ \text{original constraints}$
-----Sample Input:-----
1
hello
-----Sample Output:-----
9 | # cook your dish here
def val(c):
if c >= '0' and c <= '9':
return ord(c) - ord('0')
else:
return ord(c) - ord('A') + 10;
# Function to convert a number
# from given base 'b' to decimal
def toDeci(str,base):
llen = len(str)
power = 1 #Initialize power of base
num = 0 #Initialize result
# Decimal equivalent is str[len-1]*1 +
# str[len-1]*base + str[len-1]*(base^2) + ...
for i in range(llen - 1, -1, -1):
# A digit in input number must
# be less than number's base
if val(str[i]) >= base:
print('Invalid Number')
return -1
num += val(str[i]) * power
power = power * base
return num
t=int(input())
for _ in range(t):
s=input()
s1=[]
for i in range(len(s)):
if s[i]=='a'or s[i]=='e'or s[i]=='i' or s[i]=='o' or s[i]=='u':
s1.append(1)
else:
s1.append(0)
s2=''.join([str(elem) for elem in s1])
print(toDeci(s2, 2))
| # cook your dish here
def val(c):
if c >= '0' and c <= '9':
return ord(c) - ord('0')
else:
return ord(c) - ord('A') + 10;
# Function to convert a number
# from given base 'b' to decimal
def toDeci(str,base):
llen = len(str)
power = 1 #Initialize power of base
num = 0 #Initialize result
# Decimal equivalent is str[len-1]*1 +
# str[len-1]*base + str[len-1]*(base^2) + ...
for i in range(llen - 1, -1, -1):
# A digit in input number must
# be less than number's base
if val(str[i]) >= base:
print('Invalid Number')
return -1
num += val(str[i]) * power
power = power * base
return num
t=int(input())
for _ in range(t):
s=input()
s1=[]
for i in range(len(s)):
if s[i]=='a'or s[i]=='e'or s[i]=='i' or s[i]=='o' or s[i]=='u':
s1.append(1)
else:
s1.append(0)
s2=''.join([str(elem) for elem in s1])
print(toDeci(s2, 2))
| train | APPS_structured |
Given integers n and k, find the lexicographically k-th smallest integer in the range from 1 to n.
Note: 1 ≤ k ≤ n ≤ 109.
Example:
Input:
n: 13 k: 2
Output:
10
Explanation:
The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10. | class Solution(object):
def findKthNumber(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
s,nn=0,str(n)
while nn:
if not k: return s
c,m=0,10**(len(nn)-1)
mm,p,t=(m-1)//9,int(nn)//m,0
for i in range(1 if not s else 0,p):
cc=c+m+mm
if cc>=k:
s=10*s+i
k-=c+1
nn='9'*(len(nn)-1)
t=1
break
c=cc
if not t:
cc=c+int(nn)-(m*p)+1+mm
if cc>=k:
s=10*s+p
k-=c+1
nn=nn[1:]
else:
c=cc
for i in range(p+1,10):
cc=c+mm
if cc>=k:
s=10*s+i
k-=c+1
nn='9'*(len(nn)-2)
break
c=cc
return s | class Solution(object):
def findKthNumber(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
s,nn=0,str(n)
while nn:
if not k: return s
c,m=0,10**(len(nn)-1)
mm,p,t=(m-1)//9,int(nn)//m,0
for i in range(1 if not s else 0,p):
cc=c+m+mm
if cc>=k:
s=10*s+i
k-=c+1
nn='9'*(len(nn)-1)
t=1
break
c=cc
if not t:
cc=c+int(nn)-(m*p)+1+mm
if cc>=k:
s=10*s+p
k-=c+1
nn=nn[1:]
else:
c=cc
for i in range(p+1,10):
cc=c+mm
if cc>=k:
s=10*s+i
k-=c+1
nn='9'*(len(nn)-2)
break
c=cc
return s | train | APPS_structured |
You are given K eggs, and you have access to a building with N floors from 1 to N.
Each egg is identical in function, and if an egg breaks, you cannot drop it again.
You know that there exists a floor F with 0 <= F <= N such that any egg dropped at a floor higher than F will break, and any egg dropped at or below floor F will not break.
Each move, you may take an egg (if you have an unbroken one) and drop it from any floor X (with 1 <= X <= N).
Your goal is to know with certainty what the value of F is.
What is the minimum number of moves that you need to know with certainty what F is, regardless of the initial value of F?
Example 1:
Input: K = 1, N = 2
Output: 2
Explanation:
Drop the egg from floor 1. If it breaks, we know with certainty that F = 0.
Otherwise, drop the egg from floor 2. If it breaks, we know with certainty that F = 1.
If it didn't break, then we know with certainty F = 2.
Hence, we needed 2 moves in the worst case to know what F is with certainty.
Example 2:
Input: K = 2, N = 6
Output: 3
Example 3:
Input: K = 3, N = 14
Output: 4
Note:
1 <= K <= 100
1 <= N <= 10000 | class Solution:
def superEggDrop(self, K: int, N: int) -> int:
self.memo = {}
return self.cal_eggs(K, N)
def find_that_floor(self,K,N):
left, right = 1, N
while (left <= right):
mid = (left + right) // 2
# if it breaks;
r1 = 1 + self.cal_eggs(K - 1, mid - 1)
# if it not breaks;
r2 = 1 + self.cal_eggs(K, N - mid)
if r1 == r2:
return mid
elif r1 < r2:
left = mid + 1
else:
right = mid - 1
return right
def cal_eggs(self, K, N):
# print(K,N)
if N == 0: return 0
if K == 1: return N
if (K, N) not in self.memo:
r = 2 ** 32 - 1
now_floor = self.find_that_floor(K,N)
for floor in range(now_floor, min(now_floor + 2,N+1)):
# if it breaks;
r1 = 1 + self.cal_eggs(K - 1, floor - 1)
# if it not breaks;
r2 = 1 + self.cal_eggs(K, N - floor)
r = min(r, max(r1, r2))
self.memo[(K, N)] = r
return self.memo[(K, N)]
| class Solution:
def superEggDrop(self, K: int, N: int) -> int:
self.memo = {}
return self.cal_eggs(K, N)
def find_that_floor(self,K,N):
left, right = 1, N
while (left <= right):
mid = (left + right) // 2
# if it breaks;
r1 = 1 + self.cal_eggs(K - 1, mid - 1)
# if it not breaks;
r2 = 1 + self.cal_eggs(K, N - mid)
if r1 == r2:
return mid
elif r1 < r2:
left = mid + 1
else:
right = mid - 1
return right
def cal_eggs(self, K, N):
# print(K,N)
if N == 0: return 0
if K == 1: return N
if (K, N) not in self.memo:
r = 2 ** 32 - 1
now_floor = self.find_that_floor(K,N)
for floor in range(now_floor, min(now_floor + 2,N+1)):
# if it breaks;
r1 = 1 + self.cal_eggs(K - 1, floor - 1)
# if it not breaks;
r2 = 1 + self.cal_eggs(K, N - floor)
r = min(r, max(r1, r2))
self.memo[(K, N)] = r
return self.memo[(K, N)]
| train | APPS_structured |
You have k lists of sorted integers in ascending order. Find the smallest range that includes at least one number from each of the k lists.
We define the range [a,b] is smaller than range [c,d] if b-a < d-c or a < c if b-a == d-c.
Example 1:
Input:[[4,10,15,24,26], [0,9,12,20], [5,18,22,30]]
Output: [20,24]
Explanation:
List 1: [4, 10, 15, 24,26], 24 is in range [20,24].
List 2: [0, 9, 12, 20], 20 is in range [20,24].
List 3: [5, 18, 22, 30], 22 is in range [20,24].
Note:
The given list may contain duplicates, so ascending order means >= here.
1 k
-105 value of elements 5.
For Java users, please note that the input type has been changed to List<List<Integer>>. And after you reset the code template, you'll see this point. | from functools import reduce
class Solution:
def smallestRange(self, nums):
"""
:type nums: List[List[int]]
:rtype: List[int]
"""
k = len(nums)
idx = [0]*k
dic = collections.defaultdict(list)
for i in range(k):
dic[nums[i][0]].append(i)
mi, ma = min(dic.keys()), max(dic.keys())
ret = (mi, ma)
while True:
for i in dic[mi]:
idx[i] += 1
if idx[i]==len(nums[i]):
return ret
dic[nums[i][idx[i]]].append(i)
dic.pop(mi)
mi, ma = min(dic.keys()), max(dic.keys())
if ma-mi<ret[1]-ret[0]:
ret = (mi, ma)
| from functools import reduce
class Solution:
def smallestRange(self, nums):
"""
:type nums: List[List[int]]
:rtype: List[int]
"""
k = len(nums)
idx = [0]*k
dic = collections.defaultdict(list)
for i in range(k):
dic[nums[i][0]].append(i)
mi, ma = min(dic.keys()), max(dic.keys())
ret = (mi, ma)
while True:
for i in dic[mi]:
idx[i] += 1
if idx[i]==len(nums[i]):
return ret
dic[nums[i][idx[i]]].append(i)
dic.pop(mi)
mi, ma = min(dic.keys()), max(dic.keys())
if ma-mi<ret[1]-ret[0]:
ret = (mi, ma)
| train | APPS_structured |
=====Problem Statement=====
You are given a positive integer N.
Your task is to print a palindromic triangle of size N.
For example, a palindromic triangle of size 5 is:
1
121
12321
1234321
123454321
You can't take more than two lines. The first line (a for-statement) is already written for you.
You have to complete the code using exactly one print statement.
Note:
Using anything related to strings will give a score of 0.
Using more than one for-statement will give a score of 0.
=====Input Format=====
A single line of input containing the integer N.
=====Constraints=====
0<N<10
=====Output Format=====
Print the palindromic triangle of size N as explained above. | for i in range(1,int(input())+1): #More than 2 lines will result in 0 score. Do not leave a blank line also
print(((10**i//9)**2))
| for i in range(1,int(input())+1): #More than 2 lines will result in 0 score. Do not leave a blank line also
print(((10**i//9)**2))
| train | APPS_structured |
Given a sentence text (A sentence is a string of space-separated words) in the following format:
First letter is in upper case.
Each word in text are separated by a single space.
Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order.
Return the new text following the format shown above.
Example 1:
Input: text = "Leetcode is cool"
Output: "Is cool leetcode"
Explanation: There are 3 words, "Leetcode" of length 8, "is" of length 2 and "cool" of length 4.
Output is ordered by length and the new first word starts with capital letter.
Example 2:
Input: text = "Keep calm and code on"
Output: "On and keep calm code"
Explanation: Output is ordered as follows:
"On" 2 letters.
"and" 3 letters.
"keep" 4 letters in case of tie order by position in original text.
"calm" 4 letters.
"code" 4 letters.
Example 3:
Input: text = "To be or not to be"
Output: "To be or to be not"
Constraints:
text begins with a capital letter and then contains lowercase letters and single space between words.
1 <= text.length <= 10^5 | from operator import itemgetter
class Solution:
def arrangeWords(self, text: str) -> str:
words = [[str.lower(v), k, len(v)] for k,v in enumerate(text.split(' '))]
words2 = sorted(words, key=itemgetter(2))
print(words)
print(words2)
words3 = [word[0] for word in words2]
print(words3)
words4 = [str.title(words3[x]) if x == 0 else words3[x] for x in range(len(words3))]
return ' '.join(words4) | from operator import itemgetter
class Solution:
def arrangeWords(self, text: str) -> str:
words = [[str.lower(v), k, len(v)] for k,v in enumerate(text.split(' '))]
words2 = sorted(words, key=itemgetter(2))
print(words)
print(words2)
words3 = [word[0] for word in words2]
print(words3)
words4 = [str.title(words3[x]) if x == 0 else words3[x] for x in range(len(words3))]
return ' '.join(words4) | train | APPS_structured |
Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).
q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation.
Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone.
-----Input-----
The first line of input contains two integers n and q (1 ≤ n, q ≤ 300 000) — the number of applications and the number of events to happen.
The next q lines contain the events. The i-th of these lines starts with an integer type_{i} — type of the i-th event. If type_{i} = 1 or type_{i} = 2 then it is followed by an integer x_{i}. Otherwise it is followed by an integer t_{i} (1 ≤ type_{i} ≤ 3, 1 ≤ x_{i} ≤ n, 1 ≤ t_{i} ≤ q).
-----Output-----
Print the number of unread notifications after each event.
-----Examples-----
Input
3 4
1 3
1 1
1 2
2 3
Output
1
2
3
2
Input
4 6
1 2
1 4
1 2
3 3
1 3
1 3
Output
1
2
3
0
1
2
-----Note-----
In the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left.
In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | from sys import stdin
input = stdin.readline
n, q, = list(map(int, input().split()))
arr = [tuple(map(int, input().split())) for _ in range(q)]
adj = [[] for _ in range(n+1)]
curr, cnt, res, vis = 0, 0, [], []
for t, v in arr:
if t == 1:
adj[v].append(len(vis))
vis.append(0)
cnt += 1
elif t == 2:
for u in adj[v]:
if not vis[u]:
vis[u] = 1
cnt -= 1
adj[v] = []
else:
while v > curr:
if not vis[curr]:
vis[curr] = 1
cnt -= 1
curr += 1
res.append(cnt)
print('\n'.join(map(str, res)))
| from sys import stdin
input = stdin.readline
n, q, = list(map(int, input().split()))
arr = [tuple(map(int, input().split())) for _ in range(q)]
adj = [[] for _ in range(n+1)]
curr, cnt, res, vis = 0, 0, [], []
for t, v in arr:
if t == 1:
adj[v].append(len(vis))
vis.append(0)
cnt += 1
elif t == 2:
for u in adj[v]:
if not vis[u]:
vis[u] = 1
cnt -= 1
adj[v] = []
else:
while v > curr:
if not vis[curr]:
vis[curr] = 1
cnt -= 1
curr += 1
res.append(cnt)
print('\n'.join(map(str, res)))
| train | APPS_structured |
Hi there!
You have to implement the
`String get_column_title(int num) // syntax depends on programming language`
function that takes an integer number (index of the Excel column) and returns the string represents the title of this column.
#Intro
In the MS Excel lines are numbered by decimals, columns - by sets of letters.
For example, the first column has the title "A", second column - "B", 26th - "Z", 27th - "AA".
"BA"(53) comes after "AZ"(52), "AAA" comes after "ZZ".
Excel? Columns? More details [here](https://en.wikipedia.org/wiki/Microsoft_Excel)
#Input
It takes only one argument - column decimal index number.
Argument `num` is a natural number.
#Output
Output is the upper-case string represents the title of column. It contains the English letters: A..Z
#Errors
For cases `num < 1` your function should throw/raise `IndexError`. In case of non-integer argument you should throw/raise `TypeError`.
In Java, you should throw `Exceptions`.
Nothing should be returned in Haskell.
#Examples
Python, Ruby:
```
>>> get_column_title(52)
"AZ"
>>> get_column_title(1337)
"AYK"
>>> get_column_title(432778)
"XPEH"
>>> get_column_title()
TypeError:
>>> get_column_title("123")
TypeError:
>>> get_column_title(0)
IndexError:
```
JS, Java:
```
>>> getColumnTitle(52)
"AZ"
>>> getColumnTitle(1337)
"AYK"
>>> getColumnTitle(432778)
"XPEH"
>>> getColumnTitle()
TypeError:
>>> getColumnTitle("123")
TypeError:
>>> getColumnTitle(0)
IndexError:
```
#Hint
The difference between the 26-digits notation and Excel columns numeration that in the first system, after "Z" there are "BA", "BB", ..., while in the Excel columns scale there is a range of 26 elements: AA, AB, ... , AZ between Z and BA.
It is as if in the decimal notation was the following order: 0, 1, 2, .., 9, 00, 01, 02, .., 09, 10, 11, .., 19, 20..29..99, 000, 001 and so on.
#Also
The task is really sapid and hard. If you're stuck - write to the discussion board, there are many smart people willing to help. | def get_column_title(num):
if type(num) != int: raise TypeError
if num < 1: raise IndexError
abc = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
col_title = ""
while num > 0:
letter_index = num % 26
if letter_index == 0:
letter_index = 26
num -= 26
num //= 26
col_title = abc[letter_index] + col_title
return col_title.strip()
| def get_column_title(num):
if type(num) != int: raise TypeError
if num < 1: raise IndexError
abc = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
col_title = ""
while num > 0:
letter_index = num % 26
if letter_index == 0:
letter_index = 26
num -= 26
num //= 26
col_title = abc[letter_index] + col_title
return col_title.strip()
| train | APPS_structured |
[Run-length encoding](http://en.wikipedia.org/wiki/Run-length_encoding) (RLE) is a very simple form of lossless data compression in which runs of data are stored as a single data value and count.
A simple form of RLE would encode the string `"AAABBBCCCD"` as `"3A3B3C1D"` meaning, first there are `3 A`, then `3 B`, then `3 C` and last there is `1 D`.
Your task is to write a RLE encoder and decoder using this technique. The texts to encode will always consist of only uppercase characters, no numbers. | encode=lambda s: "".join(f"{len(list(group))}{char}" for char, group in __import__("itertools").groupby(s))
decode=lambda s: "".join(c * int(n) for n, c in __import__("re").findall(r"(\d+)(\D{1})", s))
| encode=lambda s: "".join(f"{len(list(group))}{char}" for char, group in __import__("itertools").groupby(s))
decode=lambda s: "".join(c * int(n) for n, c in __import__("re").findall(r"(\d+)(\D{1})", s))
| train | APPS_structured |
In the official contest this problem has a different statement, for which jury's solution was working incorrectly, and for this reason it was excluded from the contest. This mistake have been fixed and the current given problem statement and model solution corresponds to what jury wanted it to be during the contest.
Vova and Lesha are friends. They often meet at Vova's place and compete against each other in a computer game named The Ancient Papyri: Swordsink. Vova always chooses a warrior as his fighter and Leshac chooses an archer. After that they should choose initial positions for their characters and start the fight. A warrior is good at melee combat, so Vova will try to make the distance between fighters as small as possible. An archer prefers to keep the enemy at a distance, so Lesha will try to make the initial distance as large as possible.
There are n (n is always even) possible starting positions for characters marked along the Ox axis. The positions are given by their distinct coordinates x_1, x_2, ..., x_{n}, two characters cannot end up at the same position.
Vova and Lesha take turns banning available positions, Vova moves first. During each turn one of the guys bans exactly one of the remaining positions. Banned positions cannot be used by both Vova and Lesha. They continue to make moves until there are only two possible positions remaining (thus, the total number of moves will be n - 2). After that Vova's character takes the position with the lesser coordinate and Lesha's character takes the position with the bigger coordinate and the guys start fighting.
Vova and Lesha are already tired by the game of choosing positions, as they need to play it before every fight, so they asked you (the developer of the The Ancient Papyri: Swordsink) to write a module that would automatically determine the distance at which the warrior and the archer will start fighting if both Vova and Lesha play optimally.
-----Input-----
The first line on the input contains a single integer n (2 ≤ n ≤ 200 000, n is even) — the number of positions available initially. The second line contains n distinct integers x_1, x_2, ..., x_{n} (0 ≤ x_{i} ≤ 10^9), giving the coordinates of the corresponding positions.
-----Output-----
Print the distance between the warrior and the archer at the beginning of the fight, provided that both Vova and Lesha play optimally.
-----Examples-----
Input
6
0 1 3 7 15 31
Output
7
Input
2
73 37
Output
36
-----Note-----
In the first sample one of the optimum behavior of the players looks like that: Vova bans the position at coordinate 15; Lesha bans the position at coordinate 3; Vova bans the position at coordinate 31; Lesha bans the position at coordinate 1.
After these actions only positions 0 and 7 will remain, and the distance between them is equal to 7.
In the second sample there are only two possible positions, so there will be no bans. | import os
import random
import sys
# from typing import List, Dict
#
#
# class Int:
# def __init__(self, val):
# self.val = val
#
# def get(self):
# return self.val + 111
#
# class Unique:
# def __init__(self):
# self.s = set()
#
# def add(self, val : int):
# self.s.add(val)
#
# def __contains__(self, item : int) -> bool:
# return self.s.__contains__(item)
#
# def ceil(top : int, bottom : int) -> int:
# return (top + bottom - 1) // bottom
#
# def concat(l : List[int]):
# return "".join(map(str, l))
#
# def get(d : Dict[int, str], val : int) -> Dict[int, str]:
# return d[val]
#guy who wants small moves first
#then guy who wants large moves
#so lets say we have 4 positions
# 1, 2, 3, 4
#small wants to ban edges, because if he bans 2 or 3 he is fucked
#so he bans 1
# and we have 2, 3, 4
# then large bans middle so we have 2, 4 and the ans is 2
# 0, 1, 2, 3, 4, 5, 6, 7
# 0, 1, 2, 3, 4, 5, 6
# 0, 1, 2, 3, 5, 6
# 0, 1, 2, 3, 5
# 0, 1, 3, 5
# 0, 1, 3
# 0, 3
# 0, 1, 2, 3, 4, 5, 6, 7
# 0, 4
# # 0, 3
#1 5 9 19 21 22
# 5 9 19 21 22
# 5 19 21 22
# 19 21 22
# 0, 1, 3, 7, 15
# 0, 1, 7, 15
# 0, 1, 7
# 0, 7
def slowsolve(a):
a.sort()
small = True
while len(a) > 2:
if small:
if a[1] - a[0] > a[-1] - a[-2]:
a.pop(0)
else:
a.pop()
small = False
else:
a.pop(len(a) // 2)
small = True
return a[1] - a[0]
def solve(a):
a.sort()
candelete = len(a) // 2 - 1
res = 10 ** 18
for leftdelete in range(0, candelete + 1):
leftrem = leftdelete
rightrem = leftdelete + candelete + 1
res = min(res, a[rightrem] - a[leftrem])
return res
def prt(l): return print(' '.join(l))
def rv(): return map(int, input().split())
def rl(n): return [list(map(int, input().split())) for _ in range(n)]
if os.path.exists("test.txt"): sys.stdin = open("test.txt")
n, = rv()
a, = rl(1)
# a = sorted([random.randrange(10**2) for _ in range(6)])
# print(a)
# print(solve(a), slowsolve(a))
print(solve(a)) | import os
import random
import sys
# from typing import List, Dict
#
#
# class Int:
# def __init__(self, val):
# self.val = val
#
# def get(self):
# return self.val + 111
#
# class Unique:
# def __init__(self):
# self.s = set()
#
# def add(self, val : int):
# self.s.add(val)
#
# def __contains__(self, item : int) -> bool:
# return self.s.__contains__(item)
#
# def ceil(top : int, bottom : int) -> int:
# return (top + bottom - 1) // bottom
#
# def concat(l : List[int]):
# return "".join(map(str, l))
#
# def get(d : Dict[int, str], val : int) -> Dict[int, str]:
# return d[val]
#guy who wants small moves first
#then guy who wants large moves
#so lets say we have 4 positions
# 1, 2, 3, 4
#small wants to ban edges, because if he bans 2 or 3 he is fucked
#so he bans 1
# and we have 2, 3, 4
# then large bans middle so we have 2, 4 and the ans is 2
# 0, 1, 2, 3, 4, 5, 6, 7
# 0, 1, 2, 3, 4, 5, 6
# 0, 1, 2, 3, 5, 6
# 0, 1, 2, 3, 5
# 0, 1, 3, 5
# 0, 1, 3
# 0, 3
# 0, 1, 2, 3, 4, 5, 6, 7
# 0, 4
# # 0, 3
#1 5 9 19 21 22
# 5 9 19 21 22
# 5 19 21 22
# 19 21 22
# 0, 1, 3, 7, 15
# 0, 1, 7, 15
# 0, 1, 7
# 0, 7
def slowsolve(a):
a.sort()
small = True
while len(a) > 2:
if small:
if a[1] - a[0] > a[-1] - a[-2]:
a.pop(0)
else:
a.pop()
small = False
else:
a.pop(len(a) // 2)
small = True
return a[1] - a[0]
def solve(a):
a.sort()
candelete = len(a) // 2 - 1
res = 10 ** 18
for leftdelete in range(0, candelete + 1):
leftrem = leftdelete
rightrem = leftdelete + candelete + 1
res = min(res, a[rightrem] - a[leftrem])
return res
def prt(l): return print(' '.join(l))
def rv(): return map(int, input().split())
def rl(n): return [list(map(int, input().split())) for _ in range(n)]
if os.path.exists("test.txt"): sys.stdin = open("test.txt")
n, = rv()
a, = rl(1)
# a = sorted([random.randrange(10**2) for _ in range(6)])
# print(a)
# print(solve(a), slowsolve(a))
print(solve(a)) | train | APPS_structured |
-----Indian National Olympiad in Informatics 2014-----
Nikhil’s slogan has won the contest conducted by Drongo Airlines and he is entitled to a free ticket between any two destinations served by the airline. All cities served by Drongo Airlines can be reached from each other by some sequence of connecting flights. Nikhil is allowed to take as many connecting flights as needed, but he must take the cheapest route between his chosen destinations.
Each direct flight between two cities has a fixed price. All pairs of cities connected by direct flights have flights in both directions and the price is the same in either direction. The price for a sequence of connecting flights is the sum of the prices of the direct flights along the route.
Nikhil has information about the cost of each direct flight. He would like to maximize the value of his prize, so he would like to choose a pair of cities on the network for which the cost of the cheapest route is as high as possible.
For instance, suppose the network consists of four cities {1, 2, 3, 4}, connected as shown on the right.
In this case, Nikhil should choose to travel between 1 and 4, where the cheapest route has cost 19. You can check that for all other pairs of cities, the cheapest route has a smaller cost. For instance, notice that though the direct flight from 1 to 3 costs 24, there is a cheaper route of cost 12 from 1 to 2 to 3.
-----Input Format:-----
- Line 1 : Two space-separated integers, C and F . C is the number of cities on the network, numbered 1, 2, . . . , C. F is the number of pairs of cities connected by a direct flight
- Lines 2 to F + 1 : Each line describes one direct flight between a pair of cities and consists of three integers, x, y and p, where x and y are the two cities connected by this flight and p is the price of this
For all direct flights, $x \neq y$, and no pair of cities is connected by more than one direct flight. If there is a direct flight from x to y with price p, there is also a flight from y to x with price p and exactly one of these two will be listed.
-----Output Format-----
- The output consists of a single integer, the maximum cost among the cheapest routes between all pairs of cities across the airline’s network.
-----Test Data-----
The testdata is grouped into three subtasks. In all subtasks, 2 ≤ C ≤ 230 and 1 ≤ F ≤ 23665. In addition, each subtask has the following constraints on the inputs.
- Subtask 1 (20 marks) : F = C − 1 (that is, the airline network is a tree) and p = 1 for each direct flight.
- Subtask 2 (30 marks) : There is no constraint on the shape of the network, but for each direct flight, p = 1.
- Subtask 3 (50 marks) : There is no constraint on the shape of the network, but for each direct flight, 0 ≤ p ≤ $10^5$.
-----Sample Input-----
4 5
1 2 10
1 3 24
2 3 2
2 4 15
3 4 7
-----Sample Output-----
19
Note: Your program should not print anything other than what is specified in the output format. Please remove all diagnostic print statements before making your final submission. A program with extraneous output will be treated as incorrect! | MAX = 999999
c, f = list(map(int, input().split()))
d = []
for i in range(c):
d.append([-1 for j in range(c)] )
for i in range(f):
x, y, p = list(map(int, input().split()))
d[x-1][y-1] = p
d[y-1][x-1] = p
for i in range(c):
for j in range(c):
if i == j:
d[i][j] = 0
elif d[i][j] == -1:
d[i][j] = MAX
for w in range(c):
for i in range(c):
for j in range(c):
d[i][j] = min(d[i][j], (d[i][w] + d[w][j]))
p = 0
for i in range(c):
for j in range(c):
p = max(d[i][j], p)
print(p)
| MAX = 999999
c, f = list(map(int, input().split()))
d = []
for i in range(c):
d.append([-1 for j in range(c)] )
for i in range(f):
x, y, p = list(map(int, input().split()))
d[x-1][y-1] = p
d[y-1][x-1] = p
for i in range(c):
for j in range(c):
if i == j:
d[i][j] = 0
elif d[i][j] == -1:
d[i][j] = MAX
for w in range(c):
for i in range(c):
for j in range(c):
d[i][j] = min(d[i][j], (d[i][w] + d[w][j]))
p = 0
for i in range(c):
for j in range(c):
p = max(d[i][j], p)
print(p)
| train | APPS_structured |
## The Story
Green Lantern's long hours of study and practice with his ring have really paid off -- his skills, focus, and control have improved so much that now he can even use his ring to update and redesign his web site. Earlier today he was focusing his will and a beam from his ring upon the Justice League web server, while intensely brainstorming and visualizing in minute detail different looks and ideas for his web site, and when he finished and reloaded his home page, he was absolutely thrilled to see that among other things it now displayed
~~~~
In brightest day, in blackest night,
There's nothing cooler than my site!
~~~~
in his favorite font in very large blinking green letters.
The problem is, Green Lantern's ring has no power over anything yellow, so if he's experimenting with his web site and accidentally changes some text or background color to yellow, he will no longer be able to make any changes to those parts of the content or presentation (because he doesn't actually know any HTML, CSS, programming languages, frameworks, etc.) until he gets a more knowledgable friend to edit the code for him.
## Your Mission
You can help Green Lantern by writing a function that will replace any color property values that are too yellow with shades of green or blue-green. Presumably at a later time the two of you will be doing some testing to find out at exactly which RGB values yellow stops being yellow and starts being off-white, orange, brown, etc. as far as his ring is concerned, but here's the plan to get version 1.0 up and running as soon as possible:
Your function will receive either an HTML color name or a six-digit hex color code. (You're not going to bother with other types of color codes just now because you don't think they will come up.) If the color is too yellow, your function needs to return a green or blue-green shade instead, but if it is not too yellow, it needs to return the original color name or hex color code unchanged.
### HTML Color Names
(If don't know what HTML color names are, take a look at this HTML colors names reference.)
For HMTL color names, you are going to start out trying a pretty strict definition of yellow, replacing any of the following colors as specified:
~~~~
Gold => ForestGreen
Khaki => LimeGreen
LemonChiffon => PaleGreen
LightGoldenRodYellow => SpringGreen
LightYellow => MintCream
PaleGoldenRod => LightGreen
Yellow => Lime
~~~~
HTML color names are case-insensitive, so your function will need to be able to identify the above yellow shades regardless of the cases used, but should output the green shades as capitalized above.
Some examples:
```
"lemonchiffon" "PaleGreen"
"GOLD" "ForestGreen"
"pAlEgOlDeNrOd" "LightGreen"
"BlueViolet" "BlueViolet"
```
### Hex Color Codes
(If you don't know what six-digit hex color codes are, take a look at this Wikipedia description. Basically the six digits are made up of three two-digit numbers in base 16, known as hexidecimal or hex, from 00 to FF (equivalent to 255 in base 10, also known as decimal), with the first two-digit number specifying the color's red value, the second the green value, and the third blue.)
With six-digit color hex codes, you are going to start out going really overboard, interpreting as "yellow" any hex code where the red (R) value and the green (G) value are each greater than the blue (B) value. When you find one of these "yellow" hex codes, your function will take the three hex values and rearrange them that the largest goes to G, the middle goes to B, and the smallest to R.
For example, with the six-digit hex color code `#FFD700`, which has an R value of hex FF (decimal 255), a G value of hex D7 (decimal 215), and a B value of hex 00 (decimal 0), as the R and G values are each larger than the B value, you would return it as `#00FFD7` -- the FF reassigned to G, the D7 to B, and the 00 to R.
Hex color codes are also case-insensitive, but your function should output them in the same case they were received in, just for consistency with whatever style is being used.
Some examples:
```
"#000000" "#000000"
"#b8860b" "#0bb886"
"#8FBC8F" "#8FBC8F"
"#C71585" "#C71585"
``` | COLORDICT = {"gold" : "ForestGreen",
"khaki" : "LimeGreen",
"lemonchiffon" : "PaleGreen",
"lightgoldenrodyellow" : "SpringGreen",
"lightyellow" : "MintCream",
"palegoldenrod" : "LightGreen",
"yellow" : "Lime"}
def yellow_be_gone(clrIn):
if "#"==clrIn[0]:
R, G, B = clrIn[1:3], clrIn[3:5], clrIn[5:7]
if R>B and G>B: return "#"+B+G+R if R<G else "#"+B+R+G
for clr in COLORDICT.keys():
if clr==clrIn.lower(): return COLORDICT[clr]
return clrIn | COLORDICT = {"gold" : "ForestGreen",
"khaki" : "LimeGreen",
"lemonchiffon" : "PaleGreen",
"lightgoldenrodyellow" : "SpringGreen",
"lightyellow" : "MintCream",
"palegoldenrod" : "LightGreen",
"yellow" : "Lime"}
def yellow_be_gone(clrIn):
if "#"==clrIn[0]:
R, G, B = clrIn[1:3], clrIn[3:5], clrIn[5:7]
if R>B and G>B: return "#"+B+G+R if R<G else "#"+B+R+G
for clr in COLORDICT.keys():
if clr==clrIn.lower(): return COLORDICT[clr]
return clrIn | train | APPS_structured |
Define n!! as
n!! = 1 \* 3 \* 5 \* ... \* n if n is odd,
n!! = 2 \* 4 \* 6 \* ... \* n if n is even.
Hence 8!! = 2 \* 4 \* 6 \* 8 = 384, there is no zero at the end.
30!! has 3 zeros at the end.
For a positive integer n, please count how many zeros are there at
the end of n!!.
Example:
count\_zeros\_n\_double\_fact(30) should return 3 | def count_zeros_n_double_fact(n):
if n % 2: return 0
s, n = 0, n // 2
while n >= 5:
n //= 5
s += n
return s | def count_zeros_n_double_fact(n):
if n % 2: return 0
s, n = 0, n // 2
while n >= 5:
n //= 5
s += n
return s | train | APPS_structured |
Given an undirected tree consisting of n vertices numbered from 1 to n. A frog starts jumping from the vertex 1. In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices it jumps randomly to one of them with the same probability, otherwise, when the frog can not jump to any unvisited vertex it jumps forever on the same vertex.
The edges of the undirected tree are given in the array edges, where edges[i] = [fromi, toi] means that exists an edge connecting directly the vertices fromi and toi.
Return the probability that after t seconds the frog is on the vertex target.
Example 1:
Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4
Output: 0.16666666666666666
Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 after second 1 and then jumping with 1/2 probability to vertex 4 after second 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666.
Example 2:
Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7
Output: 0.3333333333333333
Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 after second 1.
Example 3:
Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 20, target = 6
Output: 0.16666666666666666
Constraints:
1 <= n <= 100
edges.length == n-1
edges[i].length == 2
1 <= edges[i][0], edges[i][1] <= n
1 <= t <= 50
1 <= target <= n
Answers within 10^-5 of the actual value will be accepted as correct. | class Solution:
def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:
graph = {}
for x, y in edges:
graph[x] = graph.get(x, set())
graph[x].add(y)
graph[y] = graph.get(y, set())
graph[y].add(x)
queue = [(1, 0, 1)]
visited = set([1])
while queue:
if queue[0][1] == t:
break
node, time, p = queue.pop(0)
neis = [x for x in graph.get(node, []) if x not in visited]
size =len(neis)
if neis:
for nei in neis:
queue.append([nei, time + 1, p*1/size])
visited.add(nei)
else:
queue.append((node,time + 1, p*1))
while queue:
node,t, prob = queue.pop(0)
if node == target:
return prob
return 0 | class Solution:
def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:
graph = {}
for x, y in edges:
graph[x] = graph.get(x, set())
graph[x].add(y)
graph[y] = graph.get(y, set())
graph[y].add(x)
queue = [(1, 0, 1)]
visited = set([1])
while queue:
if queue[0][1] == t:
break
node, time, p = queue.pop(0)
neis = [x for x in graph.get(node, []) if x not in visited]
size =len(neis)
if neis:
for nei in neis:
queue.append([nei, time + 1, p*1/size])
visited.add(nei)
else:
queue.append((node,time + 1, p*1))
while queue:
node,t, prob = queue.pop(0)
if node == target:
return prob
return 0 | train | APPS_structured |
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a.
What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
Input
The input contains three positive integer numbers in the first line: n, m and a (1 ≤ n, m, a ≤ 10^9).
Output
Print the needed number of flagstones in new line.
Examples
input
6 6 4
output
4 | try:
n,m,a=map(int,input().split())
if n%a!=0:
number1=(n//a)+1
else:
number1=(n//a)
if m%a!=0:
number2=(m//a)+1
else:
number2=(m//a)
print(number1*number2)
except:
pass | try:
n,m,a=map(int,input().split())
if n%a!=0:
number1=(n//a)+1
else:
number1=(n//a)
if m%a!=0:
number2=(m//a)+1
else:
number2=(m//a)
print(number1*number2)
except:
pass | train | APPS_structured |
If n is the numerator and d the denominator of a fraction, that fraction is defined a (reduced) proper fraction if and only if GCD(n,d)==1.
For example `5/16` is a proper fraction, while `6/16` is not, as both 6 and 16 are divisible by 2, thus the fraction can be reduced to `3/8`.
Now, if you consider a given number d, how many proper fractions can be built using d as a denominator?
For example, let's assume that d is 15: you can build a total of 8 different proper fractions between 0 and 1 with it: 1/15, 2/15, 4/15, 7/15, 8/15, 11/15, 13/15 and 14/15.
You are to build a function that computes how many proper fractions you can build with a given denominator:
```python
proper_fractions(1)==0
proper_fractions(2)==1
proper_fractions(5)==4
proper_fractions(15)==8
proper_fractions(25)==20
```
Be ready to handle big numbers.
Edit: to be extra precise, the term should be "reduced" fractions, thanks to [girianshiido](http://www.codewars.com/users/girianshiido) for pointing this out and sorry for the use of an improper word :) | def proper_fractions(n):
if n<3: return n-1
s,t,i =[],1,2
while True:
while n%i==0:t,s,n= t*(i if i in s else i-1),s+[i],n//i
if i*i > n:return t*(n-1) if n>1 else t
i+=1 | def proper_fractions(n):
if n<3: return n-1
s,t,i =[],1,2
while True:
while n%i==0:t,s,n= t*(i if i in s else i-1),s+[i],n//i
if i*i > n:return t*(n-1) if n>1 else t
i+=1 | train | APPS_structured |
# Introduction
Digital Cypher assigns a unique number to each letter of the alphabet:
```
a b c d e f g h i j k l m n o p q r s t u v w x y z
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
```
In the encrypted word we write the corresponding numbers instead of the letters. For example, the word `scout` becomes:
```
s c o u t
19 3 15 21 20
```
Then we add to each number a digit from the key (repeated if necessary). For example if the key is `1939`:
```
s c o u t
19 3 15 21 20
+ 1 9 3 9 1
---------------
20 12 18 30 21
m a s t e r p i e c e
13 1 19 20 5 18 16 9 5 3 5
+ 1 9 3 9 1 9 3 9 1 9 3
--------------------------------
14 10 22 29 6 27 19 18 6 12 8
```
# Task
Write a function that accepts a `message` string and an array of integers `code`. As the result, return the `key` that was used to encrypt the `message`. The `key` has to be shortest of all possible keys that can be used to code the `message`: i.e. when the possible keys are `12` , `1212`, `121212`, your solution should return `12`.
#### Input / Output:
* The `message` is a string containing only lowercase letters.
* The `code` is an array of positive integers.
* The `key` output is a positive integer.
# Examples
```python
find_the_key("scout", [20, 12, 18, 30, 21]) # --> 1939
find_the_key("masterpiece", [14, 10, 22, 29, 6, 27, 19, 18, 6, 12, 8]) # --> 1939
find_the_key("nomoretears", [15, 17, 14, 17, 19, 7, 21, 7, 2, 20, 20]) # --> 12
```
# Digital cypher series
- [Digital cypher vol 1](https://www.codewars.com/kata/592e830e043b99888600002d)
- [Digital cypher vol 2](https://www.codewars.com/kata/592edfda5be407b9640000b2)
- [Digital cypher vol 3 - missing key](https://www.codewars.com/kata/5930d8a4b8c2d9e11500002a) | def find_the_key(message, code):
diffs = "".join( str(c - ord(m) + 96) for c, m in zip(code, message) )
for size in range(1, len(code) +1):
key = diffs[:size]
if (key * len(code))[:len(code)] == diffs:
return int(key) | def find_the_key(message, code):
diffs = "".join( str(c - ord(m) + 96) for c, m in zip(code, message) )
for size in range(1, len(code) +1):
key = diffs[:size]
if (key * len(code))[:len(code)] == diffs:
return int(key) | train | APPS_structured |
# Task:
Based on the received dimensions, `a` and `b`, of an ellipse, calculare its area and perimeter.
## Example:
```python
Input: ellipse(5,2)
Output: "Area: 31.4, perimeter: 23.1"
```
**Note:** The perimeter approximation formula you should use: `π * (3/2(a+b) - sqrt(ab))`
___
## Have fun :) | import math
def ellipse(a, b):
area = str(round(a*b*math.pi,1))
perimetro = str(round(math.pi *( 3/2*(a+b) - math.sqrt(a*b)),1))
return "Area: "+area +", perimeter: "+perimetro
| import math
def ellipse(a, b):
area = str(round(a*b*math.pi,1))
perimetro = str(round(math.pi *( 3/2*(a+b) - math.sqrt(a*b)),1))
return "Area: "+area +", perimeter: "+perimetro
| train | APPS_structured |
Design a data structure that supports the following two operations:
* `addWord` (or `add_word`) which adds a word,
* `search` which searches a literal word or a regular expression string containing lowercase letters `"a-z"` or `"."` where `"."` can represent any letter
You may assume that all given words contain only lowercase letters.
## Examples
```python
add_word("bad")
add_word("dad")
add_word("mad")
search("pad") == False
search("bad") == True
search(".ad") == True
search("b..") == True
```
**Note:** the data structure will be initialized multiple times during the tests! | class WordDictionary:
def __init__(self): self.dct = set()
def add_word(self, word): self.dct.add(word)
def word_match(self, w, s):
if len(w) != len(s): return False
try:
for i,c in enumerate(s):
if c != '.' and c != w[i]: return False
return True
except: return False
def search(self, s):
for w in self.dct:
if self.word_match(w, s): return True
return False | class WordDictionary:
def __init__(self): self.dct = set()
def add_word(self, word): self.dct.add(word)
def word_match(self, w, s):
if len(w) != len(s): return False
try:
for i,c in enumerate(s):
if c != '.' and c != w[i]: return False
return True
except: return False
def search(self, s):
for w in self.dct:
if self.word_match(w, s): return True
return False | train | APPS_structured |
Implement a function which takes a string, and returns its hash value.
Algorithm steps:
* `a` := sum of the ascii values of the input characters
* `b` := sum of every difference between the consecutive characters of the input (second char minus first char, third minus second, ...)
* `c` := (`a` OR `b`) AND ((NOT `a`) shift left by 2 bits)
* `d` := `c` XOR (32 * (`total_number_of_spaces` + 1))
* return `d`
**Note**: OR, AND, NOT, XOR are bitwise operations.
___
### Examples
```
input = "a"
a = 97
b = 0
result = 64
input = "ca"
a = 196
b = -2
result = -820
```
___
Give an example why this hashing algorithm is bad? | def string_hash(s):
a = sum(ord(c) for c in s)
b = sum(ord(b) - ord(a) for a, b in zip(s, s[1:]))
c = (a | b) & (~a << 2)
return c ^ (32 * (s.count(" ") + 1))
| def string_hash(s):
a = sum(ord(c) for c in s)
b = sum(ord(b) - ord(a) for a, b in zip(s, s[1:]))
c = (a | b) & (~a << 2)
return c ^ (32 * (s.count(" ") + 1))
| train | APPS_structured |
Complete the solution so that it reverses the string passed into it.
```
'world' => 'dlrow'
``` | solution=lambda _:_[::-1] | solution=lambda _:_[::-1] | train | APPS_structured |
Jeff's friends know full well that the boy likes to get sequences and arrays for his birthday. Thus, Jeff got sequence p_1, p_2, ..., p_{n} for his birthday.
Jeff hates inversions in sequences. An inversion in sequence a_1, a_2, ..., a_{n} is a pair of indexes i, j (1 ≤ i < j ≤ n), such that an inequality a_{i} > a_{j} holds.
Jeff can multiply some numbers of the sequence p by -1. At that, he wants the number of inversions in the sequence to be minimum. Help Jeff and find the minimum number of inversions he manages to get.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 2000). The next line contains n integers — sequence p_1, p_2, ..., p_{n} (|p_{i}| ≤ 10^5). The numbers are separated by spaces.
-----Output-----
In a single line print the answer to the problem — the minimum number of inversions Jeff can get.
-----Examples-----
Input
2
2 1
Output
0
Input
9
-2 0 -1 0 -1 2 1 0 -1
Output
6 | n = int(input())
inp = input()
seq = inp.split(' ')
seq = [ abs(int(x)) for x in seq ]
Max = max(seq)
nxt = [0] * n
cnt = [0] * n
pos = [n] * (Max+1)
for i in range(n-1, -1, -1):
nxt[i] = pos[seq[i]]
pos[seq[i]] = i
for i in range(0, Max+1):
j = pos[i]
while(j<n):
front = sum(cnt[0:j])
back = sum(cnt[j+1:n])
if(front < back):
seq[j] = 0 - seq[j]
j = nxt[j]
j = pos[i]
while(j < n):
cnt[j] = 1
j = nxt[j]
#for i in range(0, n-1):
# print(seq[i], sep=' ')
#print(seq[n-1])
inv = 0
for i in range(len(seq)):
for j in range(i+1, len(seq)):
if(seq[i] > seq[j]):
inv += 1
print(inv)
| n = int(input())
inp = input()
seq = inp.split(' ')
seq = [ abs(int(x)) for x in seq ]
Max = max(seq)
nxt = [0] * n
cnt = [0] * n
pos = [n] * (Max+1)
for i in range(n-1, -1, -1):
nxt[i] = pos[seq[i]]
pos[seq[i]] = i
for i in range(0, Max+1):
j = pos[i]
while(j<n):
front = sum(cnt[0:j])
back = sum(cnt[j+1:n])
if(front < back):
seq[j] = 0 - seq[j]
j = nxt[j]
j = pos[i]
while(j < n):
cnt[j] = 1
j = nxt[j]
#for i in range(0, n-1):
# print(seq[i], sep=' ')
#print(seq[n-1])
inv = 0
for i in range(len(seq)):
for j in range(i+1, len(seq)):
if(seq[i] > seq[j]):
inv += 1
print(inv)
| train | APPS_structured |
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'} | class Solution:
def kSimilarity(self, A: str, B: str) -> int:
A, B = list(A), list(B)
N = len(A)
if not N:
return 0
cnt = 0
q = deque()
q.append((cnt, A, 0))
while q:
cnt, v, i = q.popleft()
if v == B:
return cnt
for j in range(i+1, N):
while v[i]==B[i]:
i += 1
if v[j]==B[i] and v[j]!=B[j]:
candidate = v[:]
candidate[i], candidate[j] = candidate[j], candidate[i]
q.append((cnt+1, candidate, i+1))
| class Solution:
def kSimilarity(self, A: str, B: str) -> int:
A, B = list(A), list(B)
N = len(A)
if not N:
return 0
cnt = 0
q = deque()
q.append((cnt, A, 0))
while q:
cnt, v, i = q.popleft()
if v == B:
return cnt
for j in range(i+1, N):
while v[i]==B[i]:
i += 1
if v[j]==B[i] and v[j]!=B[j]:
candidate = v[:]
candidate[i], candidate[j] = candidate[j], candidate[i]
q.append((cnt+1, candidate, i+1))
| train | APPS_structured |
-----Problem-----
There is an infinite one dimensional array ranging from (-infinity, infinity).A Zombie is currently at cell number 0. The zombie wants to reach cell number H. The Zombie moves in only two ways. The Zombie either
Makes U steps to the right (positive side) or
Makes D steps to the left (negative side).
Your task is to find the minimum number of moves the Zombie require to reach the goal.
-----Input-----
The first line contains the number of test cases T. Each of the next T lines contains 3 space
separated integers, H U D.
-----Output-----
For each test case, output one line with an integer, the minimum number of moves required to reach H from 0. If it is impossible, print -1 instead.
-----Constraints-----
-
T ≤ 10000
-
1 ≤ H, U, D ≤ 109
-----Sample Input-----
2
3 2 1
3 2 2
-----Sample Output-----
3
-1
-----Explanation-----
-
In the first sample case, first move 2 steps to the right to reach cell number 2. Then 1 step to the left to reach cell number 1 and finally 2 more steps to the right to reach the goal. Thus 3 moves are required
which is the minimum.
-
Because both U and D are even, you will always be in an even cell.Thus there is no way to reach cell number 3.
p { text-align:justify } | import fractions
for t in range(int(input())):
h,u,d = list(map(int,input().split()))
g = fractions.gcd(u,d)
if (h%g!=0):
print(-1)
else:
m = 0
n = -1
while (True):
n = (float(m)*u-h)/d
if (n>0 and int(n) == n):
break
m+=1
print(int(m+n)) | import fractions
for t in range(int(input())):
h,u,d = list(map(int,input().split()))
g = fractions.gcd(u,d)
if (h%g!=0):
print(-1)
else:
m = 0
n = -1
while (True):
n = (float(m)*u-h)/d
if (n>0 and int(n) == n):
break
m+=1
print(int(m+n)) | train | APPS_structured |
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
Example:
Input: 13
Output: 6
Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13. | class Solution:
def countDigitOne(self, n):
"""
:type n: int
:rtype: int
"""
if n <= 0:
return 0
q, x, ans = n, 1, 0
while q > 0:
digit = q % 10
q = q // 10
ans += q * x
if digit == 1:
ans += n % x + 1
elif digit > 1:
ans += x
x *= 10
return ans | class Solution:
def countDigitOne(self, n):
"""
:type n: int
:rtype: int
"""
if n <= 0:
return 0
q, x, ans = n, 1, 0
while q > 0:
digit = q % 10
q = q // 10
ans += q * x
if digit == 1:
ans += n % x + 1
elif digit > 1:
ans += x
x *= 10
return ans | train | APPS_structured |
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.
-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.
-----Output:-----
For each test case, output as the pattern.
-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$
-----Sample Input:-----
4
1
2
3
4
-----Sample Output:-----
1
13
57
135
7911
131517
1357
9111315
17192123
25272931
-----EXPLANATION:-----
No need, else pattern can be decode easily. | t=int(input())
for i in range(0,t):
n=int(input())
p=1
for j in range(0,n):
for k in range(0,n):
print(p,end="")
p=p+2
print(" ") | t=int(input())
for i in range(0,t):
n=int(input())
p=1
for j in range(0,n):
for k in range(0,n):
print(p,end="")
p=p+2
print(" ") | train | APPS_structured |
```if:python,php
In this kata you will have to write a function that takes `litres` and `price_per_litre` as arguments. Purchases of 2 or more litres get a discount of 5 cents per litre, purchases of 4 or more litres get a discount of 10 cents per litre, and so on every two litres, up to a maximum discount of 25 cents per litre. But total discount per litre cannot be more than 25 cents. Return the toal cost rounded to 2 decimal places. Also you can guess that there will not be negative or non-numeric inputs.
Good Luck!
```
```if:csharp,java,javascript
In this kata you will have to write a function that takes `litres` and `pricePerLitre` as arguments. Purchases of 2 or more litres get a discount of 5 cents per litre, purchases of 4 or more litres get a discount of 10 cents per litre, and so on every two litres, up to a maximum discount of 25 cents per litre. But total discount per litre cannot be more than 25 cents. Return the toal cost rounded to 2 decimal places. Also you can guess that there will not be negative or non-numeric inputs.
Good Luck!
``` | def fuel_price(litres, price):
if litres <2:
return round(litres * price, 2)
elif litres <4:
return round(litres * (price-0.05),2)
elif litres <6:
return round(litres * (price-0.1),2)
elif litres <8:
return round(litres * (price-0.15),2)
elif litres <10:
return round(litres * (price-0.2),2)
else:
return round(litres * (price-0.25),2) | def fuel_price(litres, price):
if litres <2:
return round(litres * price, 2)
elif litres <4:
return round(litres * (price-0.05),2)
elif litres <6:
return round(litres * (price-0.1),2)
elif litres <8:
return round(litres * (price-0.15),2)
elif litres <10:
return round(litres * (price-0.2),2)
else:
return round(litres * (price-0.25),2) | train | APPS_structured |
Just like in the ["father" kata](http://www.codewars.com/kata/find-fibonacci-last-digit/), you will have to return the last digit of the nth element in the Fibonacci sequence (starting with 1,1, to be extra clear, not with 0,1 or other numbers).
You will just get much bigger numbers, so good luck bruteforcing your way through it ;)
```python
last_fib_digit(1) == 1
last_fib_digit(2) == 1
last_fib_digit(3) == 2
last_fib_digit(1000) == 5
last_fib_digit(1000000) == 5
```
``` haskell
lastFibDigit 1 == 1
lastFibDigit 2 == 1
lastFibDigit 3 == 2
lastFibDigit 1000 == 5
lastFibDigit 1000000 == 5
``` | def last_fib_digit(n):
last = 0
tmp = 1
n = n % 60
for i in range(n):
last, tmp = tmp, (last + tmp)
return last % 10 | def last_fib_digit(n):
last = 0
tmp = 1
n = n % 60
for i in range(n):
last, tmp = tmp, (last + tmp)
return last % 10 | train | APPS_structured |
Complete the function that accepts a valid string and returns an integer.
Wait, that would be too easy! Every character of the string should be converted to the hex value of its ascii code, then the result should be the sum of the numbers in the hex strings (ignore letters).
## Examples
```
"Yo" ==> "59 6f" ==> 5 + 9 + 6 = 20
"Hello, World!" ==> 91
"Forty4Three" ==> 113
``` | def hex_hash(code):
r=0
for c in code:
for d in hex(ord(c))[2:]:
if d.isdigit():
r+=int(d)
return r | def hex_hash(code):
r=0
for c in code:
for d in hex(ord(c))[2:]:
if d.isdigit():
r+=int(d)
return r | train | APPS_structured |
Chef recently printed directions from his home to a hot new restaurant across the town, but forgot to print the directions to get back home. Help Chef to transform the directions to get home from the restaurant.
A set of directions consists of several instructions. The first instruction is of the form "Begin on XXX", indicating the street that the route begins on. Each subsequent instruction is of the form "Left on XXX" or "Right on XXX", indicating a turn onto the specified road.
When reversing directions, all left turns become right turns and vice versa, and the order of roads and turns is reversed. See the sample input for examples.
-----Input-----
Input will begin with an integer T, the number of test cases that follow. Each test case begins with an integer N, the number of instructions in the route. N lines follow, each with exactly one instruction in the format described above.
-----Output-----
For each test case, print the directions of the reversed route, one instruction per line. Print a blank line after each test case.
-----Constraints-----
- 1 ≤ T ≤ 15
- 2 ≤ N ≤ 40
- Each line in the input will contain at most 50 characters, will contain only alphanumeric characters and spaces and will not contain consecutive spaces nor trailing spaces. By alphanumeric characters we mean digits and letters of the English alphabet (lowercase and uppercase).
-----Sample Input-----
2
4
Begin on Road A
Right on Road B
Right on Road C
Left on Road D
6
Begin on Old Madras Road
Left on Domlur Flyover
Left on 100 Feet Road
Right on Sarjapur Road
Right on Hosur Road
Right on Ganapathi Temple Road
-----Sample Output-----
Begin on Road D
Right on Road C
Left on Road B
Left on Road A
Begin on Ganapathi Temple Road
Left on Hosur Road
Left on Sarjapur Road
Left on 100 Feet Road
Right on Domlur Flyover
Right on Old Madras Road
-----Explanation-----
In the first test case, the destination lies on Road D, hence the reversed route begins on Road D. The final turn in the original route is turning left from Road C onto Road D. The reverse of this, turning right from Road D onto Road C, is the first turn in the reversed route. | tc = int(input())
while tc:
n = int(input())
direction = []
road = []
for i in range(0,n):
line = input()
direction.append(line[0])
if line[0] == 'B' or line[0] == 'R':
road.append(line[9:])
else:
road.append(line[8:])
print('Begin on ' + road[n-1])
for i in range(0,n-1):
if(direction[n-i-1] == 'R'):
op = 'Left on '
else:
op = 'Right on '
print(op + road[n-i-2])
print()
tc -= 1 | tc = int(input())
while tc:
n = int(input())
direction = []
road = []
for i in range(0,n):
line = input()
direction.append(line[0])
if line[0] == 'B' or line[0] == 'R':
road.append(line[9:])
else:
road.append(line[8:])
print('Begin on ' + road[n-1])
for i in range(0,n-1):
if(direction[n-i-1] == 'R'):
op = 'Left on '
else:
op = 'Right on '
print(op + road[n-i-2])
print()
tc -= 1 | train | APPS_structured |
Create an identity matrix of the specified size( >= 0).
Some examples:
```
(1) => [[1]]
(2) => [ [1,0],
[0,1] ]
[ [1,0,0,0,0],
[0,1,0,0,0],
(5) => [0,0,1,0,0],
[0,0,0,1,0],
[0,0,0,0,1] ]
``` | def get_matrix(n):
return [[int(i == j) for j in range(n)] for i in range(n)] | def get_matrix(n):
return [[int(i == j) for j in range(n)] for i in range(n)] | train | APPS_structured |
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.
-----Input:-----
-First-line will contain $T$, the number of test cases. Then the test cases follow.
-Each test case contains a single line of input, one integer $K$.
-----Output:-----
For each test case, output as the pattern.
-----Constraints-----
- $1 \leq T \leq 26$
- $1 \leq K \leq 26$
-----Sample Input:-----
2
2
4
-----Sample Output:-----
A
12
A
12
ABC
1234
-----EXPLANATION:-----
No need, else pattern can be decode easily. | # cook your dish here
try:
for _ in range(int(input())):
n=int(input())
k=n-1
c=65
num=1
for i in range(0,n):
for j in range(0,k):
print(end=' ')
k=k-1
for j in range(0,i+1):
if i%2==0:
print(chr(c+j),end='')
else:
print(num+j,end='')
print('\r')
except:pass
| # cook your dish here
try:
for _ in range(int(input())):
n=int(input())
k=n-1
c=65
num=1
for i in range(0,n):
for j in range(0,k):
print(end=' ')
k=k-1
for j in range(0,i+1):
if i%2==0:
print(chr(c+j),end='')
else:
print(num+j,end='')
print('\r')
except:pass
| train | APPS_structured |
Create a function which checks a number for three different properties.
- is the number prime?
- is the number even?
- is the number a multiple of 10?
Each should return either true or false, which should be given as an array. Remark: The Haskell variant uses `data Property`.
### Examples
```python
number_property(7) # ==> [true, false, false]
number_property(10) # ==> [false, true, true]
```
The number will always be an integer, either positive or negative. Note that negative numbers cannot be primes, but they can be multiples of 10:
```python
number_property(-7) # ==> [false, false, false]
number_property(-10) # ==> [false, true, true]
``` | import math
def number_property(n):
return [isprime(n), n % 2 == 0, n % 10 == 0]
def isprime(fltx):
if fltx == 2: return True
if fltx <= 1 or fltx % 2 == 0: return False
return all(fltx % i != 0 for i in range(3,int(math.sqrt(fltx))+1,2)) | import math
def number_property(n):
return [isprime(n), n % 2 == 0, n % 10 == 0]
def isprime(fltx):
if fltx == 2: return True
if fltx <= 1 or fltx % 2 == 0: return False
return all(fltx % i != 0 for i in range(3,int(math.sqrt(fltx))+1,2)) | train | APPS_structured |
You are given a string S consisting of lowercase English letters.
Determine whether we can turn S into a palindrome by repeating the operation of swapping two adjacent characters. If it is possible, find the minimum required number of operations.
-----Constraints-----
- 1 \leq |S| \leq 2 × 10^5
- S consists of lowercase English letters.
-----Input-----
Input is given from Standard Input in the following format:
S
-----Output-----
If we cannot turn S into a palindrome, print -1. Otherwise, print the minimum required number of operations.
-----Sample Input-----
eel
-----Sample Output-----
1
We can turn S into a palindrome by the following operation:
- Swap the 2-nd and 3-rd characters. S is now ele. | a2n=lambda x:ord(x)-ord('a')
# 数値(1〜26)→アルファベット(a〜z)
n2a = lambda x:chr(x+ord('a')).lower()
s=list(map(a2n,list(input())))
n=len(s)
cary=[0]*26
from collections import deque
ary=[deque([]) for _ in range(26)]
for i,x in enumerate(s):
cary[x]+=1
ary[x].append(i)
oddcnt=0
for x in cary:
if x%2==1:oddcnt+=1
if oddcnt>1:
print(-1)
return
# 0-indexed binary indexed tree
class BIT:
def __init__(self, n):
self.n = n
self.data = [0]*(n+1)
self.el = [0]*(n+1)
# sum of [0,i) sum(a[:i])
def sum(self, i):
if i==0:return 0
s = 0
while i > 0:
s += self.data[i]
i -= i & -i
return s
def add(self, i, x):
i+=1
self.el[i] += x
while i <= self.n:
self.data[i] += x
i += i & -i
# sum of [l,r) sum(a[l:r])
def sumlr(self, i, j):
return self.sum(j) - self.sum(i)
# a[i]
def get(self,i):
i+=1
return self.el[i]
bit=BIT(n)
for i in range(n):
bit.add(i,1)
ans=0
m=n
for i in range(n//2):
# idx=i,n-1-iにくるものを考える
t=-1
v=float('inf')
for j in range(26):
if not ary[j]:continue
l=ary[j][0]
r=ary[j][-1]
tmp=0
# lからiへ
tmp+=bit.sum(l)
# rからn-1-iへ
tmp+=m-2*i-bit.sum(r+1)
if v>tmp:
v=tmp
t=j
r=ary[t].pop()
l=ary[t].popleft()
bit.add(l,-1)
bit.add(r,-1)
ans+=v
print(ans) | a2n=lambda x:ord(x)-ord('a')
# 数値(1〜26)→アルファベット(a〜z)
n2a = lambda x:chr(x+ord('a')).lower()
s=list(map(a2n,list(input())))
n=len(s)
cary=[0]*26
from collections import deque
ary=[deque([]) for _ in range(26)]
for i,x in enumerate(s):
cary[x]+=1
ary[x].append(i)
oddcnt=0
for x in cary:
if x%2==1:oddcnt+=1
if oddcnt>1:
print(-1)
return
# 0-indexed binary indexed tree
class BIT:
def __init__(self, n):
self.n = n
self.data = [0]*(n+1)
self.el = [0]*(n+1)
# sum of [0,i) sum(a[:i])
def sum(self, i):
if i==0:return 0
s = 0
while i > 0:
s += self.data[i]
i -= i & -i
return s
def add(self, i, x):
i+=1
self.el[i] += x
while i <= self.n:
self.data[i] += x
i += i & -i
# sum of [l,r) sum(a[l:r])
def sumlr(self, i, j):
return self.sum(j) - self.sum(i)
# a[i]
def get(self,i):
i+=1
return self.el[i]
bit=BIT(n)
for i in range(n):
bit.add(i,1)
ans=0
m=n
for i in range(n//2):
# idx=i,n-1-iにくるものを考える
t=-1
v=float('inf')
for j in range(26):
if not ary[j]:continue
l=ary[j][0]
r=ary[j][-1]
tmp=0
# lからiへ
tmp+=bit.sum(l)
# rからn-1-iへ
tmp+=m-2*i-bit.sum(r+1)
if v>tmp:
v=tmp
t=j
r=ary[t].pop()
l=ary[t].popleft()
bit.add(l,-1)
bit.add(r,-1)
ans+=v
print(ans) | train | APPS_structured |
You are given a 1×1×2$1 \times 1 \times 2$ bar (a cuboid) and a grid A$A$ with N$N$ rows (numbered 1$1$ through N$N$) and M$M$ columns (numbered 1$1$ through M$M$). Let's denote the cell in row r$r$ and column c$c$ by (r,c)$(r, c)$. Some cells of the grid are blocked, the remaining cells are free.
Each cell has dimensions 1×1$1 \times 1$, the same as two opposite faces of the cuboid. When the bar is placed on the grid in such a way that one of its two 1×1$1 \times 1$ faces fully covers a cell (r,c)$(r, c)$, we say that the bar is standing on the cell (r,c)$(r, c)$. Initially, the bar is standing on a cell (x,y)$(x, y)$.
When the bar is placed on the grid, one of its faces is touching the grid; this face is called the base. In one move, you must roll the bar over one of its base edges (sides of the base); this base edge does not move and the bar is rotated 90∘$90^\circ$ around it in such a way that it is still lying on the grid, but with a different base. In different moves, the bar may be rotated around different edges in different directions. After each move, the base of the bar must lie fully inside the grid and it must not cover any blocked cells.
An example sequence of moves is shown here.
For each cell of the grid, determine the minimum number of moves necessary to achieve the state where the bar is standing on this cell or determine that it is impossible to achieve.
-----Input-----
- The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows.
- The first line of each test case contains two space-separated integers N$N$ and M$M$.
- The second line contains two space-separated integers x$x$ and y$y$.
- N$N$ lines follow. For each i$i$ (1≤i≤N$1 \le i \le N$), the i$i$-th of these lines contains M$M$ integers Ai,1,Ai,2,…,Ai,M$A_{i, 1}, A_{i, 2}, \ldots, A_{i, M}$ (a string with length M$M$). For each valid i,j$i, j$, Ai,j=0$A_{i, j} = 0$ denotes that the cell (i,j)$(i, j)$ is blocked and Ai,j=1$A_{i, j} = 1$ denotes that it is free.
-----Output-----
For each test case, print N$N$ lines, each containing M$M$ space-separated integers. For each valid i,j$i, j$, the j$j$-th integer on the i$i$-th of these lines should denote the minimum number of moves necessary to have the bar stand on cell (i,j)$(i, j)$, or it should be −1$-1$ if it is impossible.
-----Constraints-----
- 1≤T≤50$1 \le T \le 50$
- 1≤N,M≤1,000$1 \le N, M \le 1,000$
- 1≤x≤N$1 \le x \le N$
- 1≤y≤M$1 \le y \le M$
- 0≤Ai,j≤1$0 \le A_{i, j} \le 1$ for each valid i,j$i, j$
- Ax,y=1$A_{x, y} = 1$
- the sum of N⋅M$N \cdot M$ over all test cases does not exceed 106$10^6$
-----Subtasks-----
Subtask #1 (15 points):
- x=1$x = 1$
- y=1$y = 1$
- Ai,j=1$A_{i, j} = 1$ for each valid i,j$i, j$
Subtask #2 (85 points): original constraints
-----Example Input-----
2
2 4
1 1
1111
0111
2 4
1 1
1111
0011
-----Example Output-----
0 -1 -1 2
-1 -1 -1 3
0 -1 -1 2
-1 -1 -1 -1
-----Explanation-----
Example case 1: Initially, the base of the bar occupies the cell (1,1)$(1, 1)$. After the first move, it occupies the cells (1,2)$(1, 2)$ and (1,3)$(1, 3)$. After the second move, it can occupy the cell (1,4)$(1, 4)$.
Alternatively, after the second move, it can occupy the cells (2,2)$(2, 2)$ and (2,3)$(2, 3)$, and after the third move, it can occupy the cell (2,4)$(2, 4)$. | from math import inf
t = int(input())
for _ in range(t):
n, m = map(int, input().split())
r, c = map(int, input().split())
a = [[0] * (m+2) for _ in range(n+2)]
for i in range(n):
s = input()
for j, x in enumerate(s):
a[i][j] = x
r -= 1
c -= 1
ans = [[[inf, inf, inf] for i in range(m)] for j in range(n)]
ans[r][c][0] = 0
touched = set()
touched.add((r, c, 0))
while len(touched):
visited = set()
while len(touched):
r, c, o = touched.pop()
count = 1 + ans[r][c][o]
if o == 0:
if a[r][c+1] == '1' and a[r][c+2] == '1' and ans[r][c+1][1] > count:
ans[r][c+1][1] = count
visited.add((r, c+1, 1))
if a[r][c-2] == '1' and a[r][c-1] == '1' and ans[r][c-2][1] > count:
ans[r][c-2][1] = count
visited.add((r, c-2, 1))
if a[r+1][c] == '1' and a[r+2][c] == '1' and ans[r+1][c][2] > count:
ans[r+1][c][2] = count
visited.add((r+1, c, 2))
if a[r-1][c] == '1' and a[r-2][c] == '1' and ans[r-2][c][2] > count:
ans[r-2][c][2] = count
visited.add((r-2, c, 2))
elif o == 1:
if a[r][c+2] == '1' and ans[r][c+2][0] > count:
ans[r][c+2][0] = count
visited.add((r, c+2, 0))
if a[r][c-1] == '1' and ans[r][c-1][0] > count:
ans[r][c-1][0] = count
visited.add((r, c-1, 0))
if a[r+1][c] == '1' and a[r+1][c+1] == '1' and ans[r+1][c][1] > count:
ans[r+1][c][1] = count
visited.add((r+1, c, 1))
if a[r-1][c] == '1' and a[r-1][c+1] == '1' and ans[r-1][c][1] > count:
ans[r-1][c][1] = count
visited.add((r-1, c, 1))
else:
if a[r][c+1] == '1' and a[r+1][c+1] == '1' and ans[r][c+1][2] > count:
ans[r][c+1][2] = count
visited.add((r, c+1, 2))
if a[r][c-1] == '1' and a[r+1][c-1] == '1' and ans[r][c-1][2] > count:
ans[r][c-1][2] = count
visited.add((r, c-1, 2))
if a[r+2][c] == '1' and ans[r+2][c][0] > count:
ans[r+2][c][0] = count
visited.add((r+2, c, 0))
if a[r-1][c] == '1' and ans[r-1][c][0] > count:
ans[r-1][c][0] = count
visited.add((r-1, c, 0))
touched = visited
for i in range(n):
for j in range(m):
print(ans [i][j][0] if ans[i][j][0] != inf else -1, end=' ')
print() | from math import inf
t = int(input())
for _ in range(t):
n, m = map(int, input().split())
r, c = map(int, input().split())
a = [[0] * (m+2) for _ in range(n+2)]
for i in range(n):
s = input()
for j, x in enumerate(s):
a[i][j] = x
r -= 1
c -= 1
ans = [[[inf, inf, inf] for i in range(m)] for j in range(n)]
ans[r][c][0] = 0
touched = set()
touched.add((r, c, 0))
while len(touched):
visited = set()
while len(touched):
r, c, o = touched.pop()
count = 1 + ans[r][c][o]
if o == 0:
if a[r][c+1] == '1' and a[r][c+2] == '1' and ans[r][c+1][1] > count:
ans[r][c+1][1] = count
visited.add((r, c+1, 1))
if a[r][c-2] == '1' and a[r][c-1] == '1' and ans[r][c-2][1] > count:
ans[r][c-2][1] = count
visited.add((r, c-2, 1))
if a[r+1][c] == '1' and a[r+2][c] == '1' and ans[r+1][c][2] > count:
ans[r+1][c][2] = count
visited.add((r+1, c, 2))
if a[r-1][c] == '1' and a[r-2][c] == '1' and ans[r-2][c][2] > count:
ans[r-2][c][2] = count
visited.add((r-2, c, 2))
elif o == 1:
if a[r][c+2] == '1' and ans[r][c+2][0] > count:
ans[r][c+2][0] = count
visited.add((r, c+2, 0))
if a[r][c-1] == '1' and ans[r][c-1][0] > count:
ans[r][c-1][0] = count
visited.add((r, c-1, 0))
if a[r+1][c] == '1' and a[r+1][c+1] == '1' and ans[r+1][c][1] > count:
ans[r+1][c][1] = count
visited.add((r+1, c, 1))
if a[r-1][c] == '1' and a[r-1][c+1] == '1' and ans[r-1][c][1] > count:
ans[r-1][c][1] = count
visited.add((r-1, c, 1))
else:
if a[r][c+1] == '1' and a[r+1][c+1] == '1' and ans[r][c+1][2] > count:
ans[r][c+1][2] = count
visited.add((r, c+1, 2))
if a[r][c-1] == '1' and a[r+1][c-1] == '1' and ans[r][c-1][2] > count:
ans[r][c-1][2] = count
visited.add((r, c-1, 2))
if a[r+2][c] == '1' and ans[r+2][c][0] > count:
ans[r+2][c][0] = count
visited.add((r+2, c, 0))
if a[r-1][c] == '1' and ans[r-1][c][0] > count:
ans[r-1][c][0] = count
visited.add((r-1, c, 0))
touched = visited
for i in range(n):
for j in range(m):
print(ans [i][j][0] if ans[i][j][0] != inf else -1, end=' ')
print() | train | APPS_structured |
Here's a way to construct a list containing every positive rational number:
Build a binary tree where each node is a rational and the root is `1/1`, with the following rules for creating the nodes below:
* The value of the left-hand node below `a/b` is `a/a+b`
* The value of the right-hand node below `a/b` is `a+b/b`
So the tree will look like this:
```
1/1
/ \
1/2 2/1
/ \ / \
1/3 3/2 2/3 3/1
/ \ / \ / \ / \
1/4 4/3 3/5 5/2 2/5 5/3 3/4 4/1
...
```
Now traverse the tree, breadth first, to get a list of rationals.
```
[ 1/1, 1/2, 2/1, 1/3, 3/2, 2/3, 3/1, 1/4, 4/3, 3/5, 5/2, .. ]
```
Every positive rational will occur, in its reduced form, exactly once in the list, at a finite index.
```if:haskell
In the kata, we will use tuples of type `(Integer, Integer)` to represent rationals, where `(a, b)` represents `a / b`
```
```if:javascript
In the kata, we will use tuples of type `[ Number, Number ]` to represent rationals, where `[a,b]` represents `a / b`
```
Using this method you could create an infinite list of tuples:
matching the list described above:
However, constructing the actual list is too slow for our purposes. Instead, study the tree above, and write two functions:
For example: | # This is not my code :,(
# I used those functions from here http://240hoursoflearning.blogspot.com/2017/09/the-calkin-wilf-tree.html
# Shame and dishonor on me :,(
def rat_at(n):
# This is not my code :,(
frac = [0, 1]
n += 1
nums = [n]
while n > 0:
n = n//2
nums.append(n)
for n in reversed(nums):
if n%2!=0:
frac[0] += frac[1]
else:
frac[1] += frac[0]
return tuple(frac)
def index_of(a, b):
# This is not my code :,(
if [a, b] == [1, 1]:
return 0
path = ''
while [a, b] != [1, 1]:
if a < b:
b -= a
path += '0'
else:
a -= b
path += '1'
addForDepth = 2**len(path)-1
return addForDepth + int(path[::-1], 2)
| # This is not my code :,(
# I used those functions from here http://240hoursoflearning.blogspot.com/2017/09/the-calkin-wilf-tree.html
# Shame and dishonor on me :,(
def rat_at(n):
# This is not my code :,(
frac = [0, 1]
n += 1
nums = [n]
while n > 0:
n = n//2
nums.append(n)
for n in reversed(nums):
if n%2!=0:
frac[0] += frac[1]
else:
frac[1] += frac[0]
return tuple(frac)
def index_of(a, b):
# This is not my code :,(
if [a, b] == [1, 1]:
return 0
path = ''
while [a, b] != [1, 1]:
if a < b:
b -= a
path += '0'
else:
a -= b
path += '1'
addForDepth = 2**len(path)-1
return addForDepth + int(path[::-1], 2)
| train | APPS_structured |
Write a function that counts how many different ways you can make change for an amount of money, given an array of coin denominations. For example, there are 3 ways to give change for 4 if you have coins with denomination 1 and 2:
```
1+1+1+1, 1+1+2, 2+2.
```
The order of coins does not matter:
```
1+1+2 == 2+1+1
```
Also, assume that you have an infinite amount of coins.
Your function should take an amount to change and an array of unique denominations for the coins:
```python
count_change(4, [1,2]) # => 3
count_change(10, [5,2,3]) # => 4
count_change(11, [5,7]) # => 0
``` | def count_change(money, coins):
#
if money == 0: return 1
if money < 0: return 0
if not coins: return 0
return count_change(money-coins[0], coins) + count_change(money, coins[1:]) | def count_change(money, coins):
#
if money == 0: return 1
if money < 0: return 0
if not coins: return 0
return count_change(money-coins[0], coins) + count_change(money, coins[1:]) | train | APPS_structured |
The objective is to disambiguate two given names: the original with another
Let's start simple, and just work with plain ascii strings.
The function ```could_be``` is given the original name and another one to test
against.
```python
# should return True if the other name could be the same person
> could_be("Chuck Norris", "Chuck")
True
# should False otherwise (whatever you may personnaly think)
> could_be("Chuck Norris", "superman")
False
```
Let's say your name is *Carlos Ray Norris*, your objective is to return True if
the other given name matches any combinaison of the original fullname:
```python
could_be("Carlos Ray Norris", "Carlos Ray Norris") : True
could_be("Carlos Ray Norris", "Carlos Ray") : True
could_be("Carlos Ray Norris", "Norris") : True
could_be("Carlos Ray Norris", "Norris Carlos") : True
```
For the sake of simplicity:
* the function is case sensitive and accent sensitive for now
* it is also punctuation sensitive
* an empty other name should not match any original
* an empty orginal name should not be matchable
* the function is not symmetrical
The following matches should therefore fail:
```python
could_be("Carlos Ray Norris", " ") : False
could_be("Carlos Ray Norris", "carlos") : False
could_be("Carlos Ray Norris", "Norris!") : False
could_be("Carlos Ray Norris", "Carlos-Ray Norris") : False
could_be("Ray Norris", "Carlos Ray Norris") : False
could_be("Carlos", "Carlos Ray Norris") : False
```
Too easy ? Try the next steps:
* [Author Disambiguation: a name is a Name!](https://www.codewars.com/kata/author-disambiguation-a-name-is-a-name)
* or even harder: [Author Disambiguation: Signatures worth it](https://www.codewars.com/kata/author-disambiguation-signatures-worth-it) | def could_be(original, another):
return bool(original and another and (set(original.split(' ')) >= set(another.split(' '))))
| def could_be(original, another):
return bool(original and another and (set(original.split(' ')) >= set(another.split(' '))))
| train | APPS_structured |
You are given two arrays `arr1` and `arr2`, where `arr2` always contains integers.
Write the function `find_array(arr1, arr2)` such that:
For `arr1 = ['a', 'a', 'a', 'a', 'a']`, `arr2 = [2, 4]`
`find_array returns ['a', 'a']`
For `arr1 = [0, 1, 5, 2, 1, 8, 9, 1, 5]`, `arr2 = [1, 4, 7]`
`find_array returns [1, 1, 1]`
For `arr1 = [0, 3, 4]`, `arr2 = [2, 6]`
`find_array returns [4]`
For `arr1=["a","b","c","d"]` , `arr2=[2,2,2]`,
`find_array returns ["c","c","c"]`
For `arr1=["a","b","c","d"]`, `arr2=[3,0,2]`
`find_array returns ["d","a","c"]`
If either `arr1` or `arr2` is empty, you should return an empty arr (empty list in python,
empty vector in c++). Note for c++ use std::vector arr1, arr2. | def find_array(arr1, arr2):
return [arr1[i] for i in arr2 if i <= len(arr1)] | def find_array(arr1, arr2):
return [arr1[i] for i in arr2 if i <= len(arr1)] | train | APPS_structured |
Implement `String#to_cents`, which should parse prices expressed as `$1.23` and return number of cents, or in case of bad format return `nil`. | import re
def to_cents(amount):
if not re.match(r"^\$(0|[1-9]+\d*)\.\d{2}\Z", amount):
return None
return int(re.sub(r"[\$\.]", "", amount)) | import re
def to_cents(amount):
if not re.match(r"^\$(0|[1-9]+\d*)\.\d{2}\Z", amount):
return None
return int(re.sub(r"[\$\.]", "", amount)) | train | APPS_structured |
Snuke is playing a puzzle game.
In this game, you are given a rectangular board of dimensions R × C, filled with numbers. Each integer i from 1 through N is written twice, at the coordinates (x_{i,1},y_{i,1}) and (x_{i,2},y_{i,2}).
The objective is to draw a curve connecting the pair of points where the same integer is written, for every integer from 1 through N.
Here, the curves may not go outside the board or cross each other.
Determine whether this is possible.
-----Constraints-----
- 1 ≤ R,C ≤ 10^8
- 1 ≤ N ≤ 10^5
- 0 ≤ x_{i,1},x_{i,2} ≤ R(1 ≤ i ≤ N)
- 0 ≤ y_{i,1},y_{i,2} ≤ C(1 ≤ i ≤ N)
- All given points are distinct.
- All input values are integers.
-----Input-----
Input is given from Standard Input in the following format:
R C N
x_{1,1} y_{1,1} x_{1,2} y_{1,2}
:
x_{N,1} y_{N,1} x_{N,2} y_{N,2}
-----Output-----
Print YES if the objective is achievable; print NO otherwise.
-----Sample Input-----
4 2 3
0 1 3 1
1 1 4 1
2 0 2 2
-----Sample Output-----
YES
The above figure shows a possible solution. | import sys
input = lambda: sys.stdin.readline().rstrip()
R, C, N = map(int, input().split())
X = {0, R}
Y = {0, C}
Z = []
for i in range(N):
x1, y1, x2, y2 = map(int, input().split())
if (x1 == 0 or x1 == R or y1 == 0 or y1 == C) and (x2 == 0 or x2 == R or y2 == 0 or y2 == C):
Z.append((x1, y1, x2, y2))
X.add(x1)
X.add(x2)
Y.add(y1)
Y.add(y2)
DX = {a: i for i, a in enumerate(sorted(list(X)))}
DY = {a: i for i, a in enumerate(sorted(list(Y)))}
R, C = DX[R], DY[C]
def calc(a, b):
if b == 0:
return a
if a == R:
return b + R
if b == C:
return R + C + (R - a)
if a == 0:
return R + C + R + (C - b)
A = []
for i, (x1, y1, x2, y2) in enumerate(Z):
x3, y3, x4, y4 = DX[x1], DY[y1], DX[x2], DY[y2]
A.append((calc(x3, y3), i))
A.append((calc(x4, y4), i))
A = [l[1] for l in sorted(A, key = lambda x: x[0])]
B = []
while A:
while len(B) and A[-1] == B[-1]:
A.pop()
B.pop()
if A:
B.append(A.pop())
print("NO" if len(B) else "YES") | import sys
input = lambda: sys.stdin.readline().rstrip()
R, C, N = map(int, input().split())
X = {0, R}
Y = {0, C}
Z = []
for i in range(N):
x1, y1, x2, y2 = map(int, input().split())
if (x1 == 0 or x1 == R or y1 == 0 or y1 == C) and (x2 == 0 or x2 == R or y2 == 0 or y2 == C):
Z.append((x1, y1, x2, y2))
X.add(x1)
X.add(x2)
Y.add(y1)
Y.add(y2)
DX = {a: i for i, a in enumerate(sorted(list(X)))}
DY = {a: i for i, a in enumerate(sorted(list(Y)))}
R, C = DX[R], DY[C]
def calc(a, b):
if b == 0:
return a
if a == R:
return b + R
if b == C:
return R + C + (R - a)
if a == 0:
return R + C + R + (C - b)
A = []
for i, (x1, y1, x2, y2) in enumerate(Z):
x3, y3, x4, y4 = DX[x1], DY[y1], DX[x2], DY[y2]
A.append((calc(x3, y3), i))
A.append((calc(x4, y4), i))
A = [l[1] for l in sorted(A, key = lambda x: x[0])]
B = []
while A:
while len(B) and A[-1] == B[-1]:
A.pop()
B.pop()
if A:
B.append(A.pop())
print("NO" if len(B) else "YES") | train | APPS_structured |
Chef got in the trouble! He is the king of Chefland and Chessland. There is one queen in Chefland and one queen in Chessland and they both want a relationship with him. Chef is standing before a difficult choice…
Chessland may be considered a chessboard with $N$ rows (numbered $1$ through $N$) and $M$ columns (numbered $1$ through $M$). Let's denote a unit square in row $r$ and column $c$ by $(r, c)$. Chef lives at square $(X, Y)$ of this chessboard.
Currently, both queens are living in Chessland too. Each queen, when alone on the chessboard, can see all squares that lie on the same row, column or diagonal as itself. A queen from $(x_q, y_q)$ cannot see a square $(r, c)$ if the square $(X, Y)$ is strictly between them. Of course, if the queens can see each other, the kingdom will soon be in chaos!
Help Chef calculate the number of possible configurations of the queens such that the kingdom will not be in chaos. A configuration is an unordered pair of distinct squares $(x_{q1}, y_{q1})$ and $(x_{q2}, y_{q2})$ such that neither of them is the square $(X, Y)$. Two configurations are different if the position of queen $1$ is different or the position of queen $2$ is different.
-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains four space-separated integers $N$, $M$, $X$ and $Y$.
-----Output-----
For each test case, print a single line containing one integer — the number of configurations such that the kingdom will not be in chaos.
-----Constraints-----
- $1 \le T \le 1000$
- $1 \le X \le N \le 10^2$
- $1 \le Y \le M \le 10^2$
- $2 \le N, M$
-----Example Input-----
2
3 3 2 2
4 4 2 3
-----Example Output-----
24
94
-----Explanation-----
Example case 1: Half of these configurations are:
- $(1, 1), (3, 3)$
- $(1, 1), (2, 3)$
- $(1, 1), (3, 2)$
- $(1, 2), (3, 3)$
- $(1, 2), (3, 2)$
- $(1, 2), (3, 1)$
- $(1, 3), (3, 1)$
- $(1, 3), (3, 2)$
- $(1, 3), (2, 1)$
- $(2, 1), (2, 3)$
- $(2, 1), (1, 3)$
- $(2, 1), (3, 3)$ | def ncr(n, r):
if n < r :
return 0
elif r == 2:
return(n*(n-1)/2)
elif r == 1:
return n
else:
t = 0
t = int(input())
for p in range(t):
n,m,x,y = input().split()
n,m,x,y = int(n),int(m),int(x),int(y)
maxi = ncr(n*m-1,2)
sub1 = ncr(n,2) * (m-1)
sub2 = ncr(m,2) * (n-1)
maxi = maxi - (sub1 + sub2)
#print(maxi)
sub3 = ncr(y-1,2) + ncr(m-y,2)
sub4 = ncr(x-1,2) + ncr(n-x,2)
#print(sub3,sub4)
maxi = maxi - (sub3 + sub4)
#print(maxi)
if n < m:
temp = n
diff = m-n
else:
temp = m
diff = n-m
sub5 = 0
sub6 = 0
for i in range(2,temp):
sub5 += ncr(i,2)
for j in range(diff+1):
sub6 += ncr(temp,2)
sub5 *= 4
sub6 *= 2
#print(sub5,sub6)
maxi = maxi - (sub5 + sub6)
#print(maxi)
l1 = min(n-x,y-1)
l2 = min(m-y,x-1)
maxi = maxi + l1 + l2 + (l1*l2)
l3 = min(x-1,y-1)
l4 = min(m-y,n-x)
maxi = maxi + l3 + l4 + (l3*l4)
print(int(maxi*2))
| def ncr(n, r):
if n < r :
return 0
elif r == 2:
return(n*(n-1)/2)
elif r == 1:
return n
else:
t = 0
t = int(input())
for p in range(t):
n,m,x,y = input().split()
n,m,x,y = int(n),int(m),int(x),int(y)
maxi = ncr(n*m-1,2)
sub1 = ncr(n,2) * (m-1)
sub2 = ncr(m,2) * (n-1)
maxi = maxi - (sub1 + sub2)
#print(maxi)
sub3 = ncr(y-1,2) + ncr(m-y,2)
sub4 = ncr(x-1,2) + ncr(n-x,2)
#print(sub3,sub4)
maxi = maxi - (sub3 + sub4)
#print(maxi)
if n < m:
temp = n
diff = m-n
else:
temp = m
diff = n-m
sub5 = 0
sub6 = 0
for i in range(2,temp):
sub5 += ncr(i,2)
for j in range(diff+1):
sub6 += ncr(temp,2)
sub5 *= 4
sub6 *= 2
#print(sub5,sub6)
maxi = maxi - (sub5 + sub6)
#print(maxi)
l1 = min(n-x,y-1)
l2 = min(m-y,x-1)
maxi = maxi + l1 + l2 + (l1*l2)
l3 = min(x-1,y-1)
l4 = min(m-y,n-x)
maxi = maxi + l3 + l4 + (l3*l4)
print(int(maxi*2))
| train | APPS_structured |
Remember the game 2048?
The main part of this game is merging identical tiles in a row.
* Implement a function that models the process of merging all of the tile values in a single row.
* This function takes the array line as a parameter and returns a new array with the tile values from line slid towards the front of the array (index 0) and merged.
* A given tile can only merge once.
* Empty grid squares are represented as zeros.
* Your function should work on arrays containing arbitrary number of elements.
## Examples
```
merge([2,0,2,2]) --> [4,2,0,0]
```
Another example with repeated merges:
```
merge([4,4,8,16]) --> [8,8,16,0]
merge([8,8,16,0]) --> [16,16,0,0]
merge([16,16,0,0]) --> [32,0,0,0]
``` | def merge(a):
a = [i for i in a if i] + [i for i in a if not i]
for i in range(len(a) - 1):
if a[i] == a[i+1]: a[i], a[i+1] = 2 * a[i], 0
return [i for i in a if i] + [i for i in a if not i] | def merge(a):
a = [i for i in a if i] + [i for i in a if not i]
for i in range(len(a) - 1):
if a[i] == a[i+1]: a[i], a[i+1] = 2 * a[i], 0
return [i for i in a if i] + [i for i in a if not i] | train | APPS_structured |
In 17th century our Chef was a Wizard. He asked his small son "Anshu" to bring him the secret of the Magical Mountain. The boy after travelling a lot reached the Mountain.
The description of the Mountain was as follows:
- Mountain contains N magical stones. Each of them has a unique number.
- Mountain was divided into many levels, where at ith level atmost 2^i stones can be found.
- Between stones there exist a magical path containing lava.
- A stone can be connected with maximum of three stones.
- Peak of the mountain contains stone with number 1.
- If Stone 1 is first connected to stone 2 and then to 3. Assume 2 is to the left of 3.
Now, to get the secret of the mountain, Anshu started climbing from the left. On the way he used his magical wand to protect him from lava. But, while climbing he came to know that he is able to see only the one stone at each level. After reaching the peak he slided down and did the the same process. These stones that he saw shows the secret of the mountain, if they are placed in a non decreasing order on a sunny day. Anshu doesn't remember the stones number that he saw. Help him in recollecting them and getting the secret to his father.
The mountain looks like this
-----Input-----
- First line contains T the number of test cases.
- First line of each test test case contains N.
- Next N-1 lines contains X and Y the stones which are connected.
-----Output-----
- Output the required non decreasing sequence.
-----Constraints and Subtasks-----
- 1 <= T <= 10
- 1 <= X, Y <= N
Subtask 1: 20 points
- 3<=N<=100
Subtask 2: 30 points
- 3<=N<=10000
Subtask 3: 50 points
- 3<=N<=100000
-----Example-----
Input:
1
5
1 2
1 3
2 4
2 5
Output:
1 2 3 4 5 | for t in range(eval(input())):
n = eval(input())
a = [ [] for i in range(n+1) ]
for i in range(n-1):
x,y = list(map( int, input().split() ))
a[x].append(y)
a[y].append(x)
vis = [0] * (n+1)
vis[1] = 1
ans = [1]
t1 = [1]
t2 = []
while len(t1) > 0 :
for u in t1:
for x in a[u]:
if vis[x] == 0 :
vis[x] = 1
t2.append(x)
if len(t2) > 1 :
ans.append(t2[0])
ans.append(t2[-1])
if len(t2) == 1 :
ans.append(t2[0])
t1 = t2
t2 = []
for x in sorted(ans):
print(x, end=' ')
print('') | for t in range(eval(input())):
n = eval(input())
a = [ [] for i in range(n+1) ]
for i in range(n-1):
x,y = list(map( int, input().split() ))
a[x].append(y)
a[y].append(x)
vis = [0] * (n+1)
vis[1] = 1
ans = [1]
t1 = [1]
t2 = []
while len(t1) > 0 :
for u in t1:
for x in a[u]:
if vis[x] == 0 :
vis[x] = 1
t2.append(x)
if len(t2) > 1 :
ans.append(t2[0])
ans.append(t2[-1])
if len(t2) == 1 :
ans.append(t2[0])
t1 = t2
t2 = []
for x in sorted(ans):
print(x, end=' ')
print('') | train | APPS_structured |
Looking at consecutive powers of `2`, starting with `2^1`:
`2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, ...`
Note that out of all the digits `0-9`, the last one ever to appear is `7`. It only shows up for the first time in the number `32768 (= 2^15)`.
So let us define LAST DIGIT TO APPEAR as the last digit to be written down when writing down all the powers of `n`, starting with `n^1`.
## Your task
You'll be given a positive integer ```1 =< n <= 10000```, and must return the last digit to appear, as an integer.
If for any reason there are digits which never appear in the sequence of powers, return `None`/`nil`.
Please note: The Last digit to appear can be in the same number as the penultimate one. For example for `n = 8`, the last digit to appear is `7`, although `3` appears slightly before it, in the same number:
`8, 64, 512, 4096, 32768, ...` | def LDTA(n):
digits = []
num = 1
pow = 1
while num < n**pow and pow < 20:
num *= n
pow += 1
if len(digits) == 10:
return digits[-1]
else:
for d in str(num):
if int(d) not in digits:
digits.append(int(d))
return None | def LDTA(n):
digits = []
num = 1
pow = 1
while num < n**pow and pow < 20:
num *= n
pow += 1
if len(digits) == 10:
return digits[-1]
else:
for d in str(num):
if int(d) not in digits:
digits.append(int(d))
return None | train | APPS_structured |
Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.
Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move.
Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him.
-----Input-----
The first line contains two integers, n and k (1 ≤ n ≤ 10^5; 1 ≤ k ≤ 10^9).
Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 10^5. Each string of the group consists only of lowercase English letters.
-----Output-----
If the player who moves first wins, print "First", otherwise print "Second" (without the quotes).
-----Examples-----
Input
2 3
a
b
Output
First
Input
3 1
a
b
c
Output
First
Input
1 2
ab
Output
Second | import math
import sys
from itertools import permutations
input = sys.stdin.readline
class Node:
def __init__(self):
self.children = [None]*26
self.isEnd = False
self.win = False
self.lose = False
class Trie:
def __init__(self):
self.root = Node()
def insert(self, key):
cur = self.root
for i in range(len(key)):
if cur.children[ord(key[i])-ord('a')]==None:
cur.children[ord(key[i])-ord('a')]=Node()
cur = cur.children[ord(key[i])-ord('a')]
cur.isEnd = True
def search(self, key):
cur = self.root
for i in range(len(key)):
if cur.children[ord(key[i])-ord('a')]==None:
return False
cur = cur.children[ord(key[i])-ord('a')]
if cur!=None and cur.isEnd:
return True
return False
def assignWin(self, cur):
flag = True
for i in range(26):
if cur.children[i]!=None:
flag=False
self.assignWin(cur.children[i])
if flag:
cur.win=False
cur.lose=True
else:
for i in range(26):
if cur.children[i]!=None:
cur.win = cur.win or (not cur.children[i].win)
cur.lose = cur.lose or (not cur.children[i].lose)
def __starting_point():
t=Trie()
n,k=list(map(int,input().split()))
for i in range(n):
s=input()
if s[-1]=="\n":
s= s[:-1]
t.insert(s)
t.assignWin(t.root)
if not t.root.win:
print("Second")
else:
if t.root.lose:
print("First")
else:
if k%2==1:
print("First")
else:
print("Second")
__starting_point() | import math
import sys
from itertools import permutations
input = sys.stdin.readline
class Node:
def __init__(self):
self.children = [None]*26
self.isEnd = False
self.win = False
self.lose = False
class Trie:
def __init__(self):
self.root = Node()
def insert(self, key):
cur = self.root
for i in range(len(key)):
if cur.children[ord(key[i])-ord('a')]==None:
cur.children[ord(key[i])-ord('a')]=Node()
cur = cur.children[ord(key[i])-ord('a')]
cur.isEnd = True
def search(self, key):
cur = self.root
for i in range(len(key)):
if cur.children[ord(key[i])-ord('a')]==None:
return False
cur = cur.children[ord(key[i])-ord('a')]
if cur!=None and cur.isEnd:
return True
return False
def assignWin(self, cur):
flag = True
for i in range(26):
if cur.children[i]!=None:
flag=False
self.assignWin(cur.children[i])
if flag:
cur.win=False
cur.lose=True
else:
for i in range(26):
if cur.children[i]!=None:
cur.win = cur.win or (not cur.children[i].win)
cur.lose = cur.lose or (not cur.children[i].lose)
def __starting_point():
t=Trie()
n,k=list(map(int,input().split()))
for i in range(n):
s=input()
if s[-1]=="\n":
s= s[:-1]
t.insert(s)
t.assignWin(t.root)
if not t.root.win:
print("Second")
else:
if t.root.lose:
print("First")
else:
if k%2==1:
print("First")
else:
print("Second")
__starting_point() | train | APPS_structured |
Given a 2D array A, each cell is 0 (representing sea) or 1 (representing land)
A move consists of walking from one land square 4-directionally to another land square, or off the boundary of the grid.
Return the number of land squares in the grid for which we cannot walk off the boundary of the grid in any number of moves.
Example 1:
Input: [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
Output: 3
Explanation:
There are three 1s that are enclosed by 0s, and one 1 that isn't enclosed because its on the boundary.
Example 2:
Input: [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]
Output: 0
Explanation:
All 1s are either on the boundary or can reach the boundary.
Note:
1 <= A.length <= 500
1 <= A[i].length <= 500
0 <= A[i][j] <= 1
All rows have the same size. | class Solution:
def numEnclaves(self, A: List[List[int]]) -> int:
def dfs(i, j):
if not (0<=i<len(A) and 0<=j<len(A[i])):
return
if A[i][j]==0:
return
A[i][j]=0
dfs(i-1, j)
dfs(i+1, j)
dfs(i, j-1)
dfs(i, j+1)
for i in range(len(A)):
for j in range(len(A[i])):
if A[i][j]==0:
continue
if (i==0 or j==0 or i==len(A)-1 or j==len(A[i])-1):
dfs(i, j)
res = sum([sum(row) for row in A])
return res | class Solution:
def numEnclaves(self, A: List[List[int]]) -> int:
def dfs(i, j):
if not (0<=i<len(A) and 0<=j<len(A[i])):
return
if A[i][j]==0:
return
A[i][j]=0
dfs(i-1, j)
dfs(i+1, j)
dfs(i, j-1)
dfs(i, j+1)
for i in range(len(A)):
for j in range(len(A[i])):
if A[i][j]==0:
continue
if (i==0 or j==0 or i==len(A)-1 or j==len(A[i])-1):
dfs(i, j)
res = sum([sum(row) for row in A])
return res | train | APPS_structured |
We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11).
Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero.
Example 1:
Input:
bits = [1, 0, 0]
Output: True
Explanation:
The only way to decode it is two-bit character and one-bit character. So the last character is one-bit character.
Example 2:
Input:
bits = [1, 1, 1, 0]
Output: False
Explanation:
The only way to decode it is two-bit character and two-bit character. So the last character is NOT one-bit character.
Note:
1 .
bits[i] is always 0 or 1. | class Solution:
def isOneBitCharacter(self, bits):
"""
:type bits: List[int]
:rtype: bool
"""
i = 0
while i < (len(bits)-1):
if bits[i] == 1:
i += 2
else:
i += 1
if i == len(bits):
return False
else:
return True | class Solution:
def isOneBitCharacter(self, bits):
"""
:type bits: List[int]
:rtype: bool
"""
i = 0
while i < (len(bits)-1):
if bits[i] == 1:
i += 2
else:
i += 1
if i == len(bits):
return False
else:
return True | train | APPS_structured |
=====Function Descriptions=====
poly
The poly tool returns the coefficients of a polynomial with the given sequence of roots.
print numpy.poly([-1, 1, 1, 10]) #Output : [ 1 -11 9 11 -10]
roots
The roots tool returns the roots of a polynomial with the given coefficients.
print numpy.roots([1, 0, -1]) #Output : [-1. 1.]
polyint
The polyint tool returns an antiderivative (indefinite integral) of a polynomial.
print numpy.polyint([1, 1, 1]) #Output : [ 0.33333333 0.5 1. 0. ]
polyder
The polyder tool returns the derivative of the specified order of a polynomial.
print numpy.polyder([1, 1, 1, 1]) #Output : [3 2 1]
polyval
The polyval tool evaluates the polynomial at specific value.
print numpy.polyval([1, -2, 0, 2], 4) #Output : 34
polyfit
The polyfit tool fits a polynomial of a specified order to a set of data using a least-squares approach.
print numpy.polyfit([0,1,-1, 2, -2], [0,1,1, 4, 4], 2)
#Output : [ 1.00000000e+00 0.00000000e+00 -3.97205465e-16]
The functions polyadd, polysub, polymul, and polydiv also handle proper addition, subtraction, multiplication, and division of polynomial coefficients, respectively.
=====Problem Statement=====
You are given the coefficients of a polynomial P.
Your task is to find the value of P at point x.
=====Input Format=====
The first line contains the space separated value of the coefficients in P.
The second line contains the value of x.
=====Output Format=====
Print the desired value. | import numpy as np
array = np.array(list(map(float, input().strip().split())))
x = float(input().strip())
print((np.polyval(array, x)))
| import numpy as np
array = np.array(list(map(float, input().strip().split())))
x = float(input().strip())
print((np.polyval(array, x)))
| train | APPS_structured |
A password is considered strong if below conditions are all met:
It has at least 6 characters and at most 20 characters.
It must contain at least one lowercase letter, at least one uppercase letter, and at least one digit.
It must NOT contain three repeating characters in a row ("...aaa..." is weak, but "...aa...a..." is strong, assuming other conditions are met).
Write a function strongPasswordChecker(s), that takes a string s as input, and return the MINIMUM change required to make s a strong password. If s is already strong, return 0.
Insertion, deletion or replace of any one character are all considered as one change. | class Solution:
def strongPasswordChecker(self, s):
"""
:type s: str
:rtype: int
"""
def length_requirement(password):
length = len(password)
# positive means addition, negative means deletion
if length < 6:
return 6 - length
elif length > 20:
return 20 - length
else:
return 0
def category_requirement(password):
# input
string = set(password)
lowercase = set('qwertyuiopasdfghjklzxcvbnm')
uppercase = set('QWERTYUIOPASDFGHJKLZXCVBNM')
digit = set('1234567890')
condition = [lowercase, uppercase, digit]
# output positive for addition
missing = 0
for s in condition:
if not s & string:
missing += 1
return missing
def repeat_requirement(password):
# store the repeated character and counts its occurrence
count = 1
repeat = None
weak_pair = []
for c in password:
if c == repeat:
# the same character
count += 1
else:
# new character
if count >= 3:
weak_pair.append([repeat, count])
count = 1
repeat = c
# add last pair
if count >= 3:
weak_pair.append([repeat, count])
# length of 'aaaaaa' divide by 3 returns the time of change
change = 0
one = 0
two = 0
for _, length in weak_pair:
change += length // 3
if length % 3 == 0:
one += 1
elif length % 3 == 1:
two += 1
return change, one, two
def minimum_change(password):
print(password, end=' ')
length = length_requirement(password)
category = category_requirement(password)
repeat, one, two = repeat_requirement(password)
# length: delete or insert
# category: insert or replace
# repeat: delete or replace, or insert
print(length, category, repeat, one, two, end=' * ')
# insert or replace is effective
if length >= 0:
return max(length, category, repeat)
else:
# delete required
repeat -= min(-length, one)
repeat -= min(max(-length - one, 0), two * 2) // 2
repeat -= max(-length - one - 2 * two, 0) // 3
return -length + max(category, repeat)
return minimum_change(s)
| class Solution:
def strongPasswordChecker(self, s):
"""
:type s: str
:rtype: int
"""
def length_requirement(password):
length = len(password)
# positive means addition, negative means deletion
if length < 6:
return 6 - length
elif length > 20:
return 20 - length
else:
return 0
def category_requirement(password):
# input
string = set(password)
lowercase = set('qwertyuiopasdfghjklzxcvbnm')
uppercase = set('QWERTYUIOPASDFGHJKLZXCVBNM')
digit = set('1234567890')
condition = [lowercase, uppercase, digit]
# output positive for addition
missing = 0
for s in condition:
if not s & string:
missing += 1
return missing
def repeat_requirement(password):
# store the repeated character and counts its occurrence
count = 1
repeat = None
weak_pair = []
for c in password:
if c == repeat:
# the same character
count += 1
else:
# new character
if count >= 3:
weak_pair.append([repeat, count])
count = 1
repeat = c
# add last pair
if count >= 3:
weak_pair.append([repeat, count])
# length of 'aaaaaa' divide by 3 returns the time of change
change = 0
one = 0
two = 0
for _, length in weak_pair:
change += length // 3
if length % 3 == 0:
one += 1
elif length % 3 == 1:
two += 1
return change, one, two
def minimum_change(password):
print(password, end=' ')
length = length_requirement(password)
category = category_requirement(password)
repeat, one, two = repeat_requirement(password)
# length: delete or insert
# category: insert or replace
# repeat: delete or replace, or insert
print(length, category, repeat, one, two, end=' * ')
# insert or replace is effective
if length >= 0:
return max(length, category, repeat)
else:
# delete required
repeat -= min(-length, one)
repeat -= min(max(-length - one, 0), two * 2) // 2
repeat -= max(-length - one - 2 * two, 0) // 3
return -length + max(category, repeat)
return minimum_change(s)
| train | APPS_structured |
Probably everyone has experienced an awkward situation due to shared armrests between seats in cinemas. A highly accomplished cinema manager named "Chef" decided to solve this problem.
When a customer wants to buy a ticket, the clerk at the ticket window asks the visitor if they need the armrests, and if so, which of them: left, right, or both. We know that out of the audience expected to show up, L of them only need the left armrest, R of them need just the right one, Z need none and B need both. Your task is to calculate the maximum number of people that can attend the show. In the cinema hall there are N rows with M seats each. There is only one armrest between two adjacent seats. Seats at the beginning and at the end of the row have two armrests
-----Input-----
Input begins with an integer T: the number of test cases.
Each test case consists of a single line with 6 space-separated integers: N, M, Z, L, R, B.
-----Output-----
For each test case, output a line containing the answer for the task.
-----Constraints and Subtasks-----
- 1 ≤ T ≤ 105
Subtask 1 : 10 points
- 1 ≤ N, M ≤ 3
- 0 ≤ Z, L, R, B ≤ 3
Subtask 2 : 20 points
- 1 ≤ N, M ≤ 30
- 0 ≤ Z, L, R ≤ 30
- 0 ≤ B ≤ 109
Subtask 3 : 30 points
- 1 ≤ N, M ≤ 106
- 0 ≤ Z, L, R ≤ 106
- 0 ≤ B ≤ 1016
Subtask 4 : 40 points
- 1 ≤ N, M ≤ 108
- 0 ≤ Z, L, R, B ≤ 1016
-----Example-----
Input:2
2 2 3 2 1 1
3 3 1 2 0 9
Output:4
8
-----Explanation-----
'L' - needs left
'R - needs right
'Z' - doesn't need any
'B' - needs both
'-' - empty place
Example case 1.
ZZ
ZB
Example case 2.
LLB
BZB
B-B | def func(n,m,z,l,r,b):
l=l+r
if(l>=n*(m-1)):
return min(n*m,l+z+b)
x=l/(m-1)
ans=x*(m-1)
x=min(b,x)
ans=ans+x
b=b-x
x=l%(m-1)
ans=ans+x
x=m-x
x=min((x/2)+(x%2),b)
ans=ans+x
b=b-x
x=n-(l/(m-1))
x=x-1
x=min(b,x*((m/2)+(m%2)))
ans=ans+x
z=min(z,n*m-ans)
ans=ans+z
return ans
def func2(n,m,z,l,r,b):
l=l+r
if(l>=n*(m-1)):
return min(n*m,l+z+b)
x=l/(m-1)
ans=x*(m-1)
n2=n-x
x=min(b,x)
ans=ans+x
b=b-x
l=l%(m-1)
x=l/n2
ans=ans+x*n2
m=m-x
l=l%n2
ans1=ans+func(n2,m,z,l,0,b)
ans2=0
ans3=0
if(l>0):
ans2=ans+l
x=min(z,n2-l)
ans2=ans2+x
z=z-x
m=m-1
ans2=ans2+func(n2,m,z,0,0,b)
z=z+x
m=m+1
ans3=ans+l
x=min(b,n2-l)
ans3=ans3+x
b=b-x
m=m-2
ans3=ans3+func(n2,m,z,0,0,b)
return max(ans1,ans2,ans3)
t=eval(input())
for _ in range(0,t):
n,m,z,l,r,b=list(map(int,input().split()))
a=func(n,m,z,l,r,b)
a=max(a,func2(n,m,z,l,r,b))
print(a) | def func(n,m,z,l,r,b):
l=l+r
if(l>=n*(m-1)):
return min(n*m,l+z+b)
x=l/(m-1)
ans=x*(m-1)
x=min(b,x)
ans=ans+x
b=b-x
x=l%(m-1)
ans=ans+x
x=m-x
x=min((x/2)+(x%2),b)
ans=ans+x
b=b-x
x=n-(l/(m-1))
x=x-1
x=min(b,x*((m/2)+(m%2)))
ans=ans+x
z=min(z,n*m-ans)
ans=ans+z
return ans
def func2(n,m,z,l,r,b):
l=l+r
if(l>=n*(m-1)):
return min(n*m,l+z+b)
x=l/(m-1)
ans=x*(m-1)
n2=n-x
x=min(b,x)
ans=ans+x
b=b-x
l=l%(m-1)
x=l/n2
ans=ans+x*n2
m=m-x
l=l%n2
ans1=ans+func(n2,m,z,l,0,b)
ans2=0
ans3=0
if(l>0):
ans2=ans+l
x=min(z,n2-l)
ans2=ans2+x
z=z-x
m=m-1
ans2=ans2+func(n2,m,z,0,0,b)
z=z+x
m=m+1
ans3=ans+l
x=min(b,n2-l)
ans3=ans3+x
b=b-x
m=m-2
ans3=ans3+func(n2,m,z,0,0,b)
return max(ans1,ans2,ans3)
t=eval(input())
for _ in range(0,t):
n,m,z,l,r,b=list(map(int,input().split()))
a=func(n,m,z,l,r,b)
a=max(a,func2(n,m,z,l,r,b))
print(a) | train | APPS_structured |
#Find the missing letter
Write a method that takes an array of consecutive (increasing) letters as input and that returns the missing letter in the array.
You will always get an valid array. And it will be always exactly one letter be missing. The length of the array will always be at least 2.
The array will always contain letters in only one case.
Example:
```if-not:swift
['a','b','c','d','f'] -> 'e'
['O','Q','R','S'] -> 'P'
```
(Use the English alphabet with 26 letters!)
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have also created other katas. Take a look if you enjoyed this kata! | def find_missing_letter(chars):
n = 0
while ord(chars[n]) == ord(chars[n+1]) - 1:
n += 1
return chr(1+ord(chars[n]))
| def find_missing_letter(chars):
n = 0
while ord(chars[n]) == ord(chars[n+1]) - 1:
n += 1
return chr(1+ord(chars[n]))
| train | APPS_structured |
The sports centre needs repair. Vandals have been kicking balls so hard into the roof that some of the tiles have started sticking up. The roof is represented by r.
As a quick fix, the committee have decided to place another old roof over the top, if they can find one that fits. This is your job.
A 'new' roof (f) will fit if it currently has a hole in it at the location where the old roof has a tile sticking up.
Sticking up tiles are represented by either '\\' or '/'. Holes in the 'new' roof are represented by spaces (' '). Any other character can not go over a sticking up tile.
Return true if the new roof fits, false if it does not. | def roof_fix(f,r):
for i in range(len(r)):
if r[i] in "/\\" and f[i] != ' ':
return False
return True | def roof_fix(f,r):
for i in range(len(r)):
if r[i] in "/\\" and f[i] != ' ':
return False
return True | train | APPS_structured |
Polly is 8 years old. She is eagerly awaiting Christmas as she has a bone to pick with Santa Claus. Last year she asked for a horse, and he brought her a dolls house. Understandably she is livid.
The days seem to drag and drag so Polly asks her friend to help her keep count of how long it is until Christmas, in days. She will start counting from the first of December.
Your function should take 1 argument (a Date object) which will be the day of the year it is currently. The function should then work out how many days it is until Christmas.
Watch out for leap years! | import datetime
def days_until_christmas(today):
noel = datetime.date(today.year, 12, 25)
result = (noel-today).days
return result if result >= 0 else (datetime.date(noel.year+1,noel.month,noel.day)-today).days | import datetime
def days_until_christmas(today):
noel = datetime.date(today.year, 12, 25)
result = (noel-today).days
return result if result >= 0 else (datetime.date(noel.year+1,noel.month,noel.day)-today).days | train | APPS_structured |
There are three squares, each with side length a placed on the x-axis. The coordinates of centers of these squares are (x1, a/2), (x2, a/2) and (x3, a/2) respectively. All of them are placed with one of their sides resting on the x-axis.
You are allowed to move the centers of each of these squares along the x-axis (either to the left or to the right) by a distance of at most K. Find the maximum possible area of intersections of all these three squares that you can achieve. That is, the maximum area of the region which is part of all the three squares in the final configuration.
-----Input-----
- The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
- The first line of each test case contains two space-separated integers a, K denoting side length of the squares, and the maximum distance that you can move the center of any square.
- The second line contains three space separated integers x1, x2, x3
-----Output-----
For each test case, output a real number corresponding to the maximum area of the intersection of the three squares that you can obtain. Your answer will be considered correct if it has an absolute error of less than or equal to 10-2.
-----Constraints-----
- 1 ≤ T ≤ 105
- 1 ≤ a ≤ 105
- 0 ≤ K ≤ 106
- -106 ≤ x1, x2, x3 ≤ 106
-----Example-----
Input
3
1 0
1 2 3
1 1
1 2 3
1 1
1 4 6
Output
0.000000
1.0000
0.0
-----Explanation-----
Testcase 1: The figure below shows the three squares:
Since K = 0, they cannot be moved, and since there is no region which belongs to all three squares, the answer is 0.
Testcase 2: The starting configuration is the same as above, but now each of the squares can move 1 unit. So we can move the first square 1 unit to the right and the third square one unit to the left, and have all the three squares at x-coordinate = 2. Thus the entire square is part of all three squares, and the answer is 1. | t=int(input())
for o in range(t):
n,k=list(map(int,input().split()))
x,y,z=list(map(int,input().split()))
x1,y1=x-n/2,x+n/2
x2,y2=y-n/2,y+n/2
x3,y3=z-n/2,z+n/2
a=[(x1-k,y1+k),(x2-k,y2+k),(x3-k,y3+k)]
a.sort()
x1,y1=a[0]
x2,y2=a[1]
x3,y3=a[2]
f1,f2=max(x1,x2),min(y1,y2)
ans=0.0
flag=False
if(f1>=f2):
flag=True
else:
f1=max(f1,x3)
f2=min(f2,y3)
if(f1>=f2):
flag=True
if(flag):
print(0*1.0)
continue
if(f2-f1>n):
print(n*n*1.0)
else:
print((f2-f1)*n*1.0)
| t=int(input())
for o in range(t):
n,k=list(map(int,input().split()))
x,y,z=list(map(int,input().split()))
x1,y1=x-n/2,x+n/2
x2,y2=y-n/2,y+n/2
x3,y3=z-n/2,z+n/2
a=[(x1-k,y1+k),(x2-k,y2+k),(x3-k,y3+k)]
a.sort()
x1,y1=a[0]
x2,y2=a[1]
x3,y3=a[2]
f1,f2=max(x1,x2),min(y1,y2)
ans=0.0
flag=False
if(f1>=f2):
flag=True
else:
f1=max(f1,x3)
f2=min(f2,y3)
if(f1>=f2):
flag=True
if(flag):
print(0*1.0)
continue
if(f2-f1>n):
print(n*n*1.0)
else:
print((f2-f1)*n*1.0)
| train | APPS_structured |
Given a directed, acyclic graph of N nodes. Find all possible paths from node 0 to node N-1, and return them in any order.
The graph is given as follows: the nodes are 0, 1, ..., graph.length - 1. graph[i] is a list of all nodes j for which the edge (i, j) exists.
Example:
Input: [[1,2], [3], [3], []]
Output: [[0,1,3],[0,2,3]]
Explanation: The graph looks like this:
0--->1
| |
v v
2--->3
There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.
Note:
The number of nodes in the graph will be in the range [2, 15].
You can print different paths in any order, but you should keep the order of nodes inside one path. | class Solution:
def numRabbits(self, answers):
"""
:type answers: List[int]
:rtype: int
"""
total = 0
d = collections.defaultdict(int)
for ans in answers:
d[ans] += 1
for k, v in d.items():
total += math.ceil(v/(k+1)) * (k+1)
return total | class Solution:
def numRabbits(self, answers):
"""
:type answers: List[int]
:rtype: int
"""
total = 0
d = collections.defaultdict(int)
for ans in answers:
d[ans] += 1
for k, v in d.items():
total += math.ceil(v/(k+1)) * (k+1)
return total | train | APPS_structured |
# Kata Task
I have a cat and a dog.
I got them at the same time as kitten/puppy. That was `humanYears` years ago.
Return their respective ages now as [`humanYears`,`catYears`,`dogYears`]
NOTES:
* humanYears >= 1
* humanYears are whole numbers only
## Cat Years
* `15` cat years for first year
* `+9` cat years for second year
* `+4` cat years for each year after that
## Dog Years
* `15` dog years for first year
* `+9` dog years for second year
* `+5` dog years for each year after that
**References**
* http://www.catster.com/cats-101/calculate-cat-age-in-cat-years
* http://www.slate.com/articles/news_and_politics/explainer/2009/05/a_dogs_life.html
If you liked this Kata there is another related one here | def human_years_cat_years_dog_years(human_years):
catYears = 0
dogYears = 0
humanYears = human_years
for i in range(human_years):
if i == 0:
catYears = catYears + 15
dogYears = dogYears + 15
if i == 1:
catYears = catYears + 9
dogYears = dogYears + 9
if i > 1:
catYears = catYears + 4
dogYears = dogYears + 5
return [humanYears,catYears,dogYears]
| def human_years_cat_years_dog_years(human_years):
catYears = 0
dogYears = 0
humanYears = human_years
for i in range(human_years):
if i == 0:
catYears = catYears + 15
dogYears = dogYears + 15
if i == 1:
catYears = catYears + 9
dogYears = dogYears + 9
if i > 1:
catYears = catYears + 4
dogYears = dogYears + 5
return [humanYears,catYears,dogYears]
| train | APPS_structured |
Chef has a string of size $N$ which consists only lowercase English alphabet. The chef doesn't like the consonant alphabet at all. So he is thinking of changing every single consonant alphabet to any vowel alphabet. There is some cost for performing this operation.
- Number all alphabet [a,b,c,……,z] as [1,2,3,…..,26]
- So if you want to change c to e then cost will be |e-c| = |5-3| = 2
You need the answer at what minimum cost chef can change every single consonant alphabet to any vowel alphabet.
-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains of a single line of input, a string of lowercase alphabet.
-----Output:-----
For each test case, output in a single line answer.
-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq |s| \leq 10^2$
-----Sample Input:-----
2
aeiou
dbcc
-----Sample Output:-----
0
6
-----EXPLANATION:-----
In the first test case, all characters are already vowel so we don't need to change.
In the second tect case
|e-d|=|5-4|=1
|a-b|=|1-2|=1
|a-c|=|1-3|=2
|a-c|=|1-3|=2
1+1+2+2=6 | def isVowel(char):
return char in 'aeiou'
n=int(input())
for _ in range(n):
s=input()
p=0
q=0
for i in s:
if(isVowel(i)):
p=p+1
elif i>'a' and i<'e':
if i=='c':
q=q+2
else:
q=q+1
elif i>'e' and i<'i':
if i=='g':
q=q+2
else:
q=q+1
elif i>'i' and i<'o':
if i=='l':
q=q+3
elif i=='k' or i=='m':
q=q+2
else:
q=q+1;
elif i>'o' and i<'u':
if i=='r':
q=q+3
elif i=='q' or i=='s':
q=q+2
else:
q=q+1;
elif i>'u':
if i=='x':
q=q+3
elif i=='y':
q=q+4
elif i=='z':
q=q+5
elif i=='w':
q=q+2
else:
q=q+1;
else:
p=p+1
print(q) | def isVowel(char):
return char in 'aeiou'
n=int(input())
for _ in range(n):
s=input()
p=0
q=0
for i in s:
if(isVowel(i)):
p=p+1
elif i>'a' and i<'e':
if i=='c':
q=q+2
else:
q=q+1
elif i>'e' and i<'i':
if i=='g':
q=q+2
else:
q=q+1
elif i>'i' and i<'o':
if i=='l':
q=q+3
elif i=='k' or i=='m':
q=q+2
else:
q=q+1;
elif i>'o' and i<'u':
if i=='r':
q=q+3
elif i=='q' or i=='s':
q=q+2
else:
q=q+1;
elif i>'u':
if i=='x':
q=q+3
elif i=='y':
q=q+4
elif i=='z':
q=q+5
elif i=='w':
q=q+2
else:
q=q+1;
else:
p=p+1
print(q) | train | APPS_structured |
There are 8 prison cells in a row, and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
Otherwise, it becomes vacant.
(Note that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.)
We describe the current state of the prison in the following way: cells[i] == 1 if the i-th cell is occupied, else cells[i] == 0.
Given the initial state of the prison, return the state of the prison after N days (and N such changes described above.)
Example 1:
Input: cells = [0,1,0,1,1,0,0,1], N = 7
Output: [0,0,1,1,0,0,0,0]
Explanation:
The following table summarizes the state of the prison on each day:
Day 0: [0, 1, 0, 1, 1, 0, 0, 1]
Day 1: [0, 1, 1, 0, 0, 0, 0, 0]
Day 2: [0, 0, 0, 0, 1, 1, 1, 0]
Day 3: [0, 1, 1, 0, 0, 1, 0, 0]
Day 4: [0, 0, 0, 0, 0, 1, 0, 0]
Day 5: [0, 1, 1, 1, 0, 1, 0, 0]
Day 6: [0, 0, 1, 0, 1, 1, 0, 0]
Day 7: [0, 0, 1, 1, 0, 0, 0, 0]
Example 2:
Input: cells = [1,0,0,1,0,0,1,0], N = 1000000000
Output: [0,0,1,1,1,1,1,0]
Note:
cells.length == 8
cells[i] is in {0, 1}
1 <= N <= 10^9 | class Solution:
def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]:
visited = {str(cells) : N}
cycle = 0
hascycle = False
def get_next(cells) -> List[int]:
'''return next cell'''
tmp = [0] + [cells[i-1] ^ cells[i+1] ^ 1 for i in range(1,7)] + [0]
return tmp
while N > 0:
visited[str(cells)] = N
N -= 1
cells = get_next(cells.copy())
if str(cells) in visited:
hascycle = True
cycle = visited[str(cells)] - N
break
if hascycle:
N = N % cycle
while N > 0:
N -= 1
cells = get_next(cells)
return cells | class Solution:
def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]:
visited = {str(cells) : N}
cycle = 0
hascycle = False
def get_next(cells) -> List[int]:
'''return next cell'''
tmp = [0] + [cells[i-1] ^ cells[i+1] ^ 1 for i in range(1,7)] + [0]
return tmp
while N > 0:
visited[str(cells)] = N
N -= 1
cells = get_next(cells.copy())
if str(cells) in visited:
hascycle = True
cycle = visited[str(cells)] - N
break
if hascycle:
N = N % cycle
while N > 0:
N -= 1
cells = get_next(cells)
return cells | train | APPS_structured |
=====Function Descriptions=====
The eval() expression is a very powerful built-in function of Python. It helps in evaluating an expression. The expression can be a Python statement, or a code object.
For example:
>>> eval("9 + 5")
14
>>> x = 2
>>> eval("x + 3")
5
Here, eval() can also be used to work with Python keywords or defined functions and variables. These would normally be stored as strings.
For example:
>>> type(eval("len"))
<type 'builtin_function_or_method'>
Without eval()
>>> type("len")
<type 'str'>
=====Problem Statement=====
You are given an expression in a line. Read that line as a string variable, such as var, and print the result using eval(var).
NOTE: Python2 users, please import from __future__ import print_function.
=====Constraints=====
Input string is less than 100 characters. | #!/usr/bin/env python3
def __starting_point():
input().strip()
__starting_point() | #!/usr/bin/env python3
def __starting_point():
input().strip()
__starting_point() | train | APPS_structured |