input
stringlengths 50
13.9k
| output_program
stringlengths 5
655k
| output_answer
stringlengths 5
655k
| split
stringclasses 1
value | dataset
stringclasses 1
value |
---|---|---|---|---|
#SKRZAT
Geek Challenge [SKRZAT] is an old, old game from Poland that uses a game console with two buttons plus a joy stick. As is true to its name, the game communicates in binary, so that one button represents a zero and the other a one. Even more true to its name, the game chooses to communicate so that the base of the number system is minus two, not plus two, so we'll call this representation "Weird Binary". Thus the bit positions label the powers of minus two, as seen in the following five-bit tables:
| ------------------------------------------------------------------------- |
| Bits | Value | Bits | Value | Bits | Value | Bits | Value |
| ------ | ------- | ------ | ------- | ------ | ------- | ------ | ------- |
| 00000 | 0 | 01000 | -8 | 10000 | 16 | 11000 | 8 |
| 00001 | 1 | 01001 | -7 | 10001 | 17 | 11001 | 9 |
| 00010 | -2 | 01010 | -10 | 10010 | 14 | 11010 | 6 |
| 00011 | -1 | 01011 | -9 | 10011 | 15 | 11011 | 7 |
| 00100 | 4 | 01100 | -4 | 10100 | 20 | 11100 | 12 |
| 00101 | 5 | 01101 | -3 | 10101 | 21 | 11101 | 13 |
| 00110 | 2 | 01110 | -6 | 10110 | 18 | 11110 | 10 |
| 00111 | 3 | 01111 | -5 | 10111 | 19 | 11111 | 11 |
| ------------------------------------------------------------------------- |
| ------------------------------------------------------------------------- |
| Bits | Value | Bits | Value | Bits | Value | Bits | Value |
| ------ | ------- | ------ | ------- | ------ | ------- | ------ | ------- |
| 01010 | -10 | 00010 | -2 | 11010 | 6 | 10010 | 14 |
| 01011 | -9 | 00011 | -1 | 11011 | 7 | 10011 | 15 |
| 01000 | -8 | 00000 | 0 | 11000 | 8 | 10000 | 16 |
| 01001 | -7 | 00001 | 1 | 11001 | 9 | 10001 | 17 |
| 01110 | -6 | 00110 | 2 | 11110 | 10 | 10110 | 18 |
| 01111 | -5 | 00111 | 3 | 11111 | 11 | 10111 | 19 |
| 01100 | -4 | 00100 | 4 | 11100 | 12 | 10100 | 20 |
| 01101 | -3 | 00101 | 5 | 11101 | 13 | 10101 | 21 |
| ------------------------------------------------------------------------- |
Numbers are presented on the screen in Weird Binary, and then numbers are accepted in response from the console as a stream of zeroes and ones, terminated by a five-second pause. You are writing a computer program to support the novice geek in playing the game by translating numbers between decimal and Weird Binary.
#Input
The `skrzat` function will either convert into Weird Binary or out of Weird Binary: The first parameter will be either the letter `"b"`, which indicates that the second parameter is written in Weird Binary and needs to be converted to decimal; the letter `"d"` indicates that the second parameter is a decimal and needs to be converted to Weird Binary. The second parameter will be in the range to fit within a 15-bit Weird Binary number, which represents the decimal number range -10922 to 21845, inclusive.
#Output
For each conversion problem, return the type of problem, its input string, and the converted result in the format shown below, replicating even the spacing exactly as shown. Leading zeroes are not allowed.
return format: `'From {binary || decimal}: {non-converted value} is {converted value}'`
#Sample Input
skrzat('b', '1001101')
skrzat('b', '0111111')
skrzat('b', '101001000100001')
skrzat('b', '010010001000010')
skrzat('b', '100110100110100')
skrzat('d', -137)
skrzat('d', 137)
skrzat('d', 8191)
skrzat('d', -10000)
skrzat('d', 21000)
#Sample Output
'From binary: 1001101 is 61'
'From binary: 0111111 is -21'
'From binary: 101001000100001 is 19937'
'From binary: 010010001000010 is -7106'
'From binary: 100110100110100 is 15604'
'From decimal: -137 is 10001011'
'From decimal: 137 is 110011001'
'From decimal: 8191 is 110000000000011'
'From decimal: -10000 is 10100100110000'
'From decimal: 21000 is 101011000011000'
|
def skrzat(base, n):
if base == "b" : return 'From binary: {} is {}'.format(n,sum([int(j)*((-2)**i)for i,j in enumerate(n[::-1])]))
else:
def do(n1):
li = []
while n1 != 0:
li.append(str(abs(n1 % (-2)))) ; n1 //= -2
return li[::-1]
return 'From decimal: {} is {}'.format(n,"".join([do(abs(n)),do(-n)][n>0]) or 0)
|
def skrzat(base, n):
if base == "b" : return 'From binary: {} is {}'.format(n,sum([int(j)*((-2)**i)for i,j in enumerate(n[::-1])]))
else:
def do(n1):
li = []
while n1 != 0:
li.append(str(abs(n1 % (-2)))) ; n1 //= -2
return li[::-1]
return 'From decimal: {} is {}'.format(n,"".join([do(abs(n)),do(-n)][n>0]) or 0)
|
train
|
APPS_structured
|
### Preface
You are currently working together with a local community to build a school teaching children how to code. First plans have been made and the community wants to decide on the best location for the coding school.
In order to make this decision data about the location of students and potential locations is collected.
### Problem
In order to be able to attract and teach as many students as possible we want to minimize the total traveling distance for potential students. The streets system is organized in a traditional grid system and students can only travel horizontally or vertically (not diagonal).
The locations of interested students is given as an array with the first value of each entry presenting the x coordinate and the second value presenting the y coordinate:
```python
students = [[3,7],[2,2],[14,1], ...];
```
Potential locations are passed as an array of objects with an unique id, a x and y coordinate:
```python
locations = [{"id": 1, "x": 3, "y": 4}, {"id": 2, "x": 8, "y": 2}, ...];
```
Your task is now to evaluate which of the school locations would be best to minimize the distance for all potential students to the school.
The desired output should consist of a string indicating the ID of the best suitable location and the x and y coordinates in the following form:
```
"The best location is number 1 with the coordinates x = 3 and y = 4"
```
|
def optimum_location(students, locations, optimal = (float('inf'),)):
for loc in locations:
distance = sum(abs(x - loc['x']) + abs(y - loc['y']) for x, y in students)
if distance < optimal[0]:
optimal = distance, loc['id'], loc['x'], loc['y']
return 'The best location is number %s with the coordinates x = %s and y = %s' % optimal[1:]
|
def optimum_location(students, locations, optimal = (float('inf'),)):
for loc in locations:
distance = sum(abs(x - loc['x']) + abs(y - loc['y']) for x, y in students)
if distance < optimal[0]:
optimal = distance, loc['id'], loc['x'], loc['y']
return 'The best location is number %s with the coordinates x = %s and y = %s' % optimal[1:]
|
train
|
APPS_structured
|
Meliodas and Ban are fighting over chocolates. Meliodas has $X$ chocolates, while Ban has $Y$. Whoever has lesser number of chocolates eats as many chocolates as he has from the other's collection. This eatfest war continues till either they have the same number of chocolates, or atleast one of them is left with no chocolates.
Can you help Elizabeth predict the total no of chocolates they'll be left with at the end of their war?
-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, which contains two integers $X, Y$, the no of chocolates Meliodas and Ban have, respectively.
-----Output:-----
For each testcase, output in a single line the no of chocolates that remain after Ban and Meliodas stop fighting.
-----Constraints-----
- $1 \leq T \leq 100000$
- $0 \leq X,Y \leq 10^9$
-----Sample Input:-----
3
5 3
10 10
4 8
-----Sample Output:-----
2
20
8
-----EXPLANATION:-----
Denoting Meliodas as $M$, Ban as $B$.
Testcase 1:
$M$=5, $B$=3
Ban eates 3 chocolates of Meliodas.
$M$=2, $B$=3
Meliodas eats 2 chocolates of Ban.
$M$=2, $B$=1
Ban eates 1 chocolate of Meliodas.
$M$=1, $B$=1
Since they have the same no of candies, they stop quarreling.
Total candies left: 2
Testcase 2:
$M$=10, $B$=10
Since both of them had the same candies to begin with, there was no point in fighting.
Total candies left: 20
Testcase 3:
$M$=4, $B$=8
Meliodas eats 4 chocolates of Ban.
$M$=4, $B$=4
Since they have the same no of candies, they stop quarreling.
Total candies left: 8
|
# cook your dish here
from math import gcd
for _ in range(int(input())):
x,y= map(int,input().split())
if x==y:
print(x+y)
else:
print(2*gcd(x,y))
|
# cook your dish here
from math import gcd
for _ in range(int(input())):
x,y= map(int,input().split())
if x==y:
print(x+y)
else:
print(2*gcd(x,y))
|
train
|
APPS_structured
|
Given a binary string S (a string consisting only of '0' and '1's) and a positive integer N, return true if and only if for every integer X from 1 to N, the binary representation of X is a substring of S.
Example 1:
Input: S = "0110", N = 3
Output: true
Example 2:
Input: S = "0110", N = 4
Output: false
Note:
1 <= S.length <= 1000
1 <= N <= 10^9
|
class Solution:
def queryString(self, S: str, N: int) -> bool:
st = set()
for size in range(1, len(S)+1):
for i in range(len(S) - size +1):
st.add(S[i:i+size])
#print(st)
for i in range(1,N+1):
#print(bin(i)[2:])
if not bin(i)[2:] in st:
return False
return True
|
class Solution:
def queryString(self, S: str, N: int) -> bool:
st = set()
for size in range(1, len(S)+1):
for i in range(len(S) - size +1):
st.add(S[i:i+size])
#print(st)
for i in range(1,N+1):
#print(bin(i)[2:])
if not bin(i)[2:] in st:
return False
return True
|
train
|
APPS_structured
|
Implement `String#parse_mana_cost`, which parses [Magic: the Gathering mana costs](http://mtgsalvation.gamepedia.com/Mana_cost) expressed as a string and returns a `Hash` with keys being kinds of mana, and values being the numbers.
Don't include any mana types equal to zero.
Format is:
* optionally natural number representing total amount of generic mana (use key `*`)
* optionally followed by any combination of `w`, `u`, `b`, `r`, `g` (case insensitive in input, return lower case in output), each representing one mana of specific color.
If case of Strings not following specified format, return `nil/null/None`.
|
import re
def parse_mana_cost(mana):
n={c:mana.lower().count(c) for c in 'wubrg' if mana.lower().count(c)>0}
m=re.split(r'\D',mana)
if sum(n.values())+sum([len(c) for c in m]) != len(mana): return None
p = sum([int(c) for c in m if c!=''])
if p>0: n['*']=p
return n
|
import re
def parse_mana_cost(mana):
n={c:mana.lower().count(c) for c in 'wubrg' if mana.lower().count(c)>0}
m=re.split(r'\D',mana)
if sum(n.values())+sum([len(c) for c in m]) != len(mana): return None
p = sum([int(c) for c in m if c!=''])
if p>0: n['*']=p
return n
|
train
|
APPS_structured
|
You are given an array $a$ consisting of $n$ integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from $a$ to make it a good array. Recall that the prefix of the array $a=[a_1, a_2, \dots, a_n]$ is a subarray consisting several first elements: the prefix of the array $a$ of length $k$ is the array $[a_1, a_2, \dots, a_k]$ ($0 \le k \le n$).
The array $b$ of length $m$ is called good, if you can obtain a non-decreasing array $c$ ($c_1 \le c_2 \le \dots \le c_{m}$) from it, repeating the following operation $m$ times (initially, $c$ is empty): select either the first or the last element of $b$, remove it from $b$, and append it to the end of the array $c$.
For example, if we do $4$ operations: take $b_1$, then $b_{m}$, then $b_{m-1}$ and at last $b_2$, then $b$ becomes $[b_3, b_4, \dots, b_{m-3}]$ and $c =[b_1, b_{m}, b_{m-1}, b_2]$.
Consider the following example: $b = [1, 2, 3, 4, 4, 2, 1]$. This array is good because we can obtain non-decreasing array $c$ from it by the following sequence of operations: take the first element of $b$, so $b = [2, 3, 4, 4, 2, 1]$, $c = [1]$; take the last element of $b$, so $b = [2, 3, 4, 4, 2]$, $c = [1, 1]$; take the last element of $b$, so $b = [2, 3, 4, 4]$, $c = [1, 1, 2]$; take the first element of $b$, so $b = [3, 4, 4]$, $c = [1, 1, 2, 2]$; take the first element of $b$, so $b = [4, 4]$, $c = [1, 1, 2, 2, 3]$; take the last element of $b$, so $b = [4]$, $c = [1, 1, 2, 2, 3, 4]$; take the only element of $b$, so $b = []$, $c = [1, 1, 2, 2, 3, 4, 4]$ — $c$ is non-decreasing.
Note that the array consisting of one element is good.
Print the length of the shortest prefix of $a$ to delete (erase), to make $a$ to be a good array. Note that the required length can be $0$.
You have to answer $t$ independent test cases.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 2 \cdot 10^4$) — the number of test cases. Then $t$ test cases follow.
The first line of the test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of $a$. The second line of the test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 2 \cdot 10^5$), where $a_i$ is the $i$-th element of $a$.
It is guaranteed that the sum of $n$ does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$).
-----Output-----
For each test case, print the answer: the length of the shortest prefix of elements you need to erase from $a$ to make it a good array.
-----Example-----
Input
5
4
1 2 3 4
7
4 3 3 8 4 5 2
3
1 1 1
7
1 3 1 4 5 3 2
5
5 4 3 2 3
Output
0
4
0
2
3
-----Note-----
In the first test case of the example, the array $a$ is already good, so we don't need to erase any prefix.
In the second test case of the example, the initial array $a$ is not good. Let's erase first $4$ elements of $a$, the result is $[4, 5, 2]$. The resulting array is good. You can prove that if you erase fewer number of first elements, the result will not be good.
|
for __ in range(int(input())):
n = int(input())
ar = list(map(int, input().split()))
ar.reverse()
ans = n - 1
flag = False
for i in range(1, n):
if ar[i] < ar[i - 1]:
flag = True
if flag:
if ar[i] > ar[i - 1]:
break
ans -= 1
print(ans)
|
for __ in range(int(input())):
n = int(input())
ar = list(map(int, input().split()))
ar.reverse()
ans = n - 1
flag = False
for i in range(1, n):
if ar[i] < ar[i - 1]:
flag = True
if flag:
if ar[i] > ar[i - 1]:
break
ans -= 1
print(ans)
|
train
|
APPS_structured
|
Starting with a positive integer N, we reorder the digits in any order (including the original order) such that the leading digit is not zero.
Return true if and only if we can do this in a way such that the resulting number is a power of 2.
Example 1:
Input: 1
Output: true
Example 2:
Input: 10
Output: false
Example 3:
Input: 16
Output: true
Example 4:
Input: 24
Output: false
Example 5:
Input: 46
Output: true
Note:
1 <= N <= 10^9
|
class Solution:
pow2 = set()
for i in range(30):
pow2.add(''.join(sorted(str(1 << i))))
def reorderedPowerOf2(self, N: int) -> bool:
return ''.join(sorted(str(N))) in self.pow2
|
class Solution:
pow2 = set()
for i in range(30):
pow2.add(''.join(sorted(str(1 << i))))
def reorderedPowerOf2(self, N: int) -> bool:
return ''.join(sorted(str(N))) in self.pow2
|
train
|
APPS_structured
|
Your task is to find the first element of an array that is not consecutive.
By not consecutive we mean not exactly 1 larger than the previous element of the array.
E.g. If we have an array `[1,2,3,4,6,7,8]` then `1` then `2` then `3` then `4` are all consecutive but `6` is not, so that's the first non-consecutive number.
```if:c
If a non consecutive number is found then return `true` and set the passed in pointer to the number found.
If the whole array is consecutive then return `false`.
```
```if-not:c
If the whole array is consecutive then return `null`^(2).
```
The array will always have at least `2` elements^(1) and all elements will be numbers. The numbers will also all be unique and in ascending order. The numbers could be positive or negative and the first non-consecutive could be either too!
If you like this Kata, maybe try this one next: https://www.codewars.com/kata/represent-array-of-numbers-as-ranges
```if:c
^(1) Can you write a solution that will return `false` for both `[]` and `[ x ]` (an empty array and one with a single number) though? (This is an empty array and one with a single number and is not tested for, but you can write your own example test. )
```
```if-not:c
^(1) Can you write a solution that will return `null`^(2) for both `[]` and `[ x ]` though? (This is an empty array and one with a single number and is not tested for, but you can write your own example test. )
^(2)
Swift, Ruby and Crystal: `nil`
Haskell: `Nothing`
Python, Rust: `None`
Julia: `nothing`
Nim: `none(int)` (See [options](https://nim-lang.org/docs/options.html))
```
|
def first_non_consecutive(a):
i = a[0]
for e in a:
if e != i:
return e
i += 1
return None
|
def first_non_consecutive(a):
i = a[0]
for e in a:
if e != i:
return e
i += 1
return None
|
train
|
APPS_structured
|
Chef would like go shopping to buy ingredients for his special dish. The local grocery store has some special discount offers. If you want to buy some set of ingredients you will pay for all ingredients except the cheapest one. Chef would like to spend as little money as possible. You have to help him. :)
The store is pretty small and stocks only one unit of each ingredients. Opposite each ingredient is a hanging price tag corresponding to it. The salesman walked away for a minute, giving Chef an opportunity to swap some price tags. He would like to swap some tags to minimize his purchase cost.
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N denoting the number of ingredients Chef needs to buy. The second line contains N space-separated integers A1, A2, ... , AN denoting the value written on the price tags opposite the needed ingredients. The third line contains a single integer M denoting the number of special offers. The following M lines lists inventory of special offers, one offer per line. Each line contains an integer Ci followed by Ci integers denoting the indices of ingredients constituting the ith discount offer.
-----Output-----
For each test case, output a single line containing the minimal purchase cost.
-----Constraints-----
- T ≤ 5
- 1 ≤ N ≤ 15
- 1 ≤ Ai ≤ 106
- 0 ≤ M ≤ 2N-1
- 2 ≤ Ci ≤ N
- Subtask 1 (15 points): 1 ≤ N ≤ 5
- Subtask 2 (25 points): 1 ≤ N ≤ 10
- Subtask 3 (60 points): 1 ≤ N ≤ 15
-----Example-----
Input:
1
4
1 2 3 4
3
2 1 2
2 3 4
3 1 2 3
Output:
6
|
from itertools import permutations as p
def disc(a,b):
for ai in a:
for bi in b:
if ai==bi:
return False
return True
for i in range(eval(input())):
n = eval(input())
arr = list(map(int,input().split()))
perms = list(p(arr))
m = eval(input())
offer = {}
for i in range(m):
dup = list(map(int,input().split()))
try:
offer[dup[0]].append(dup[1:])
except:
offer[dup[0]] = [dup[1:]]
ans = sum(arr)
if n==1:
print(ans)
elif n==2:
try:
if len(offer[2])>=1:
ans -= min(arr)
except:
pass
print(ans)
elif n==3:
try:
if len(offer[3])>=1:
ans -= min(arr)
except:
pass
try:
if len(offer[2])>=1:
value = 9999999999
for item in perms:
cur = 0
cur += item[0]
cur += max(item[1],item[2])
if cur<value:
value = cur
if value<ans:
ans = value
except:
pass
print(ans)
elif n==4:
try:
if len(offer[4])>=1:
ans -= min(arr)
except:
pass
#print ans
try:
if len(offer[3])>=1:
value = 9999999999
for item in perms:
cur = 0
cur = sum(item)
cur -= min(item[1],item[2],item[3])
if cur<value:
value = cur
if value<ans:
ans = value
except:
pass
#print ans
try:
if len(offer[2])>=1:
value = 9999999999
for item in perms:
cur = 0
cur = sum(item)
cur -= min(item[1],item[2])
if cur<value:
value = cur
if value<ans:
ans = value
#print ans
#print offer[2]
if len(offer[2])>=2:
flg = False
end = len(offer[2])
for i in range(end):
for j in range(i+1,end):
if disc(offer[2][i],offer[2][j]):
flg = True
break
#print flg
if flg:
value = 9999999999
for item in perms:
cur = 0
cur = sum(item)
cur -= min(item[1],item[0])
cur -= min(item[2],item[3])
if cur<value:
value = cur
if value<ans:
ans = value
except:
pass
print(ans)
elif n==5:
try:
if len(offer[5])>=1:
ans -= min(arr)
except:
pass
try:
if len(offer[4])>=1:
value = 9999999999
for item in perms:
cur = 0
cur = sum(item)
cur -= min(item[1],item[2],item[3],item[4])
if cur<value:
value = cur
if value<ans:
ans = value
except:
pass
try:
if len(offer[2])>=1:
value = 9999999999
for item in perms:
cur = 0
cur = sum(item)
cur -= min(item[1],item[2])
if cur<value:
value = cur
if value<ans:
ans = value
if len(offer[2])>=2:
flg = False
end = len(offer[2])
for i in range(end):
for j in range(i+1,end):
if disc(offer[2][i],offer[2][j]):
flg = True
break
if flg:
value = 9999999999
for item in perms:
cur = 0
cur = sum(item)
cur -= min(item[1],item[0])
cur -= min(item[2],item[3])
if cur<value:
value = cur
if value<ans:
ans = value
except:
pass
try:
if len(offer[3])>=1:
value = 9999999999
for item in perms:
cur = 0
cur = sum(item)
cur -= min(item[1],item[2],item[3])
if cur<value:
value = cur
if value<ans:
ans = value
except:
pass
try:
if len(offer[3])>=1 and len(offer[2])>=1:
flg = False
for i in offer[3]:
for j in offer[2]:
if disc(i,j):
flg = True
break
if flg:
value = 9999999999
for item in perms:
cur = 0
cur = sum(item)
cur -= min(item[1],item[0])
cur -= min(item[2],item[3],item[4])
if cur<value:
value = cur
if value<ans:
ans = value
except:
pass
print(ans)
|
from itertools import permutations as p
def disc(a,b):
for ai in a:
for bi in b:
if ai==bi:
return False
return True
for i in range(eval(input())):
n = eval(input())
arr = list(map(int,input().split()))
perms = list(p(arr))
m = eval(input())
offer = {}
for i in range(m):
dup = list(map(int,input().split()))
try:
offer[dup[0]].append(dup[1:])
except:
offer[dup[0]] = [dup[1:]]
ans = sum(arr)
if n==1:
print(ans)
elif n==2:
try:
if len(offer[2])>=1:
ans -= min(arr)
except:
pass
print(ans)
elif n==3:
try:
if len(offer[3])>=1:
ans -= min(arr)
except:
pass
try:
if len(offer[2])>=1:
value = 9999999999
for item in perms:
cur = 0
cur += item[0]
cur += max(item[1],item[2])
if cur<value:
value = cur
if value<ans:
ans = value
except:
pass
print(ans)
elif n==4:
try:
if len(offer[4])>=1:
ans -= min(arr)
except:
pass
#print ans
try:
if len(offer[3])>=1:
value = 9999999999
for item in perms:
cur = 0
cur = sum(item)
cur -= min(item[1],item[2],item[3])
if cur<value:
value = cur
if value<ans:
ans = value
except:
pass
#print ans
try:
if len(offer[2])>=1:
value = 9999999999
for item in perms:
cur = 0
cur = sum(item)
cur -= min(item[1],item[2])
if cur<value:
value = cur
if value<ans:
ans = value
#print ans
#print offer[2]
if len(offer[2])>=2:
flg = False
end = len(offer[2])
for i in range(end):
for j in range(i+1,end):
if disc(offer[2][i],offer[2][j]):
flg = True
break
#print flg
if flg:
value = 9999999999
for item in perms:
cur = 0
cur = sum(item)
cur -= min(item[1],item[0])
cur -= min(item[2],item[3])
if cur<value:
value = cur
if value<ans:
ans = value
except:
pass
print(ans)
elif n==5:
try:
if len(offer[5])>=1:
ans -= min(arr)
except:
pass
try:
if len(offer[4])>=1:
value = 9999999999
for item in perms:
cur = 0
cur = sum(item)
cur -= min(item[1],item[2],item[3],item[4])
if cur<value:
value = cur
if value<ans:
ans = value
except:
pass
try:
if len(offer[2])>=1:
value = 9999999999
for item in perms:
cur = 0
cur = sum(item)
cur -= min(item[1],item[2])
if cur<value:
value = cur
if value<ans:
ans = value
if len(offer[2])>=2:
flg = False
end = len(offer[2])
for i in range(end):
for j in range(i+1,end):
if disc(offer[2][i],offer[2][j]):
flg = True
break
if flg:
value = 9999999999
for item in perms:
cur = 0
cur = sum(item)
cur -= min(item[1],item[0])
cur -= min(item[2],item[3])
if cur<value:
value = cur
if value<ans:
ans = value
except:
pass
try:
if len(offer[3])>=1:
value = 9999999999
for item in perms:
cur = 0
cur = sum(item)
cur -= min(item[1],item[2],item[3])
if cur<value:
value = cur
if value<ans:
ans = value
except:
pass
try:
if len(offer[3])>=1 and len(offer[2])>=1:
flg = False
for i in offer[3]:
for j in offer[2]:
if disc(i,j):
flg = True
break
if flg:
value = 9999999999
for item in perms:
cur = 0
cur = sum(item)
cur -= min(item[1],item[0])
cur -= min(item[2],item[3],item[4])
if cur<value:
value = cur
if value<ans:
ans = value
except:
pass
print(ans)
|
train
|
APPS_structured
|
The local transport authority is organizing an online picture contest.
Participants must take pictures of transport means in an original way, and then post the picture on Instagram using a specific ```hashtag```.
The local transport authority needs your help. They want you to take out the ```hashtag``` from the posted message. Your task is to implement the function
```python
def omit_hashtag(message, hashtag):
```
## Examples
```
* ("Sunny day! #lta #vvv", "#lta") -> "Sunny day! #vvv" (notice the double space)
* ("#lta #picture_contest", "#lta") -> " #picture_contest"
```
## Notes
* When multiple occurences of the hashtag are found, delete only the first one.
* In C, you should modify the ```message```, as the function returns a void type. In Python, you should return the answer.
* There can be erroneous messages where the hashtag isn't present. The message should in this case stay untouched.
* The hashtag only consists of alphanumeric characters.
|
def omit_hashtag(message, hashtag):
return message.replace(hashtag, '' , 1) if hashtag in message else message
|
def omit_hashtag(message, hashtag):
return message.replace(hashtag, '' , 1) if hashtag in message else message
|
train
|
APPS_structured
|
Arkady plays Gardenscapes a lot. Arkady wants to build two new fountains. There are n available fountains, for each fountain its beauty and cost are known. There are two types of money in the game: coins and diamonds, so each fountain cost can be either in coins or diamonds. No money changes between the types are allowed.
Help Arkady to find two fountains with maximum total beauty so that he can buy both at the same time.
-----Input-----
The first line contains three integers n, c and d (2 ≤ n ≤ 100 000, 0 ≤ c, d ≤ 100 000) — the number of fountains, the number of coins and diamonds Arkady has.
The next n lines describe fountains. Each of these lines contain two integers b_{i} and p_{i} (1 ≤ b_{i}, p_{i} ≤ 100 000) — the beauty and the cost of the i-th fountain, and then a letter "C" or "D", describing in which type of money is the cost of fountain i: in coins or in diamonds, respectively.
-----Output-----
Print the maximum total beauty of exactly two fountains Arkady can build. If he can't build two fountains, print 0.
-----Examples-----
Input
3 7 6
10 8 C
4 3 C
5 6 D
Output
9
Input
2 4 5
2 5 C
2 1 D
Output
0
Input
3 10 10
5 5 C
5 5 C
10 11 D
Output
10
-----Note-----
In the first example Arkady should build the second fountain with beauty 4, which costs 3 coins. The first fountain he can't build because he don't have enough coins. Also Arkady should build the third fountain with beauty 5 which costs 6 diamonds. Thus the total beauty of built fountains is 9.
In the second example there are two fountains, but Arkady can't build both of them, because he needs 5 coins for the first fountain, and Arkady has only 4 coins.
|
from bisect import *
n, tc, td = [int(i) for i in input().split()]
fc = []
fd = []
mbc = 0
mbd = 0
for _ in range(n):
b, p, ft = input().split()
b, p = int(b), int(p)
f = (p, b)
if ft == 'C':
if p <= tc:
fc.append(f)
mbc = max(mbc, b)
else:
if p <= td:
fd.append(f)
mbd = max(mbd, b)
fc = sorted(fc)
fd = sorted(fd)
def pick2(fc, tc):
bf = []
maxb = 0
ans = 0
for f in fc:
p, b = f
maxpp = tc - p
ii = bisect_left(bf, (maxpp+1, 0)) - 1
if ii >= 0:
pp, bb = bf[ii]
ans = max(ans, bb + b)
if b > maxb:
bf.append(f)
maxb = b
return ans
ans = mbc + mbd if mbc > 0 and mbd > 0 else 0
ans = max(ans, pick2(fc, tc))
ans = max(ans, pick2(fd, td))
print(ans)
|
from bisect import *
n, tc, td = [int(i) for i in input().split()]
fc = []
fd = []
mbc = 0
mbd = 0
for _ in range(n):
b, p, ft = input().split()
b, p = int(b), int(p)
f = (p, b)
if ft == 'C':
if p <= tc:
fc.append(f)
mbc = max(mbc, b)
else:
if p <= td:
fd.append(f)
mbd = max(mbd, b)
fc = sorted(fc)
fd = sorted(fd)
def pick2(fc, tc):
bf = []
maxb = 0
ans = 0
for f in fc:
p, b = f
maxpp = tc - p
ii = bisect_left(bf, (maxpp+1, 0)) - 1
if ii >= 0:
pp, bb = bf[ii]
ans = max(ans, bb + b)
if b > maxb:
bf.append(f)
maxb = b
return ans
ans = mbc + mbd if mbc > 0 and mbd > 0 else 0
ans = max(ans, pick2(fc, tc))
ans = max(ans, pick2(fd, td))
print(ans)
|
train
|
APPS_structured
|
A happy string is a string that:
consists only of letters of the set ['a', 'b', 'c'].
s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed).
For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy strings and strings "aa", "baa" and "ababbc" are not happy strings.
Given two integers n and k, consider a list of all happy strings of length n sorted in lexicographical order.
Return the kth string of this list or return an empty string if there are less than k happy strings of length n.
Example 1:
Input: n = 1, k = 3
Output: "c"
Explanation: The list ["a", "b", "c"] contains all happy strings of length 1. The third string is "c".
Example 2:
Input: n = 1, k = 4
Output: ""
Explanation: There are only 3 happy strings of length 1.
Example 3:
Input: n = 3, k = 9
Output: "cab"
Explanation: There are 12 different happy string of length 3 ["aba", "abc", "aca", "acb", "bab", "bac", "bca", "bcb", "cab", "cac", "cba", "cbc"]. You will find the 9th string = "cab"
Example 4:
Input: n = 2, k = 7
Output: ""
Example 5:
Input: n = 10, k = 100
Output: "abacbabacb"
Constraints:
1 <= n <= 10
1 <= k <= 100
|
class Solution:
def getHappyString(self, n: int, k: int) -> str:
N = 3 << (n - 1)
res = ''
if k > N:
return res
k -= 1
letters = ('a', 'b', 'c')
res += letters[k * 3 // N]
N //= 3
k %= N
for i in range(1, n):
prev = res[i - 1]
index = k * 2 // N
offset = int(prev <= letters[index])
res += letters[index + offset]
N >>= 1
k %= N
return res
|
class Solution:
def getHappyString(self, n: int, k: int) -> str:
N = 3 << (n - 1)
res = ''
if k > N:
return res
k -= 1
letters = ('a', 'b', 'c')
res += letters[k * 3 // N]
N //= 3
k %= N
for i in range(1, n):
prev = res[i - 1]
index = k * 2 // N
offset = int(prev <= letters[index])
res += letters[index + offset]
N >>= 1
k %= N
return res
|
train
|
APPS_structured
|
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example:
Given a = 1 and b = 2, return 3.
Credits:Special thanks to @fujiaozhu for adding this problem and creating all test cases.
|
class Solution:
def getSum(self, a, b):
max = 0x7FFFFFFF
mask = 0xFFFFFFFF
while b != 0:
a, b = (a ^ b) & mask, ((a & b) << 1) & mask
return a if a <= max else ~(a ^ mask)
|
class Solution:
def getSum(self, a, b):
max = 0x7FFFFFFF
mask = 0xFFFFFFFF
while b != 0:
a, b = (a ^ b) & mask, ((a & b) << 1) & mask
return a if a <= max else ~(a ^ mask)
|
train
|
APPS_structured
|
# Introduction
You are the developer working on a website which features a large counter on its homepage, proudly displaying the number of happy customers who have downloaded your companies software.
You have been tasked with adding an effect to this counter to make it more interesting.
Instead of just displaying the count value immediatley when the page loads, we want to create the effect of each digit cycling through its preceding numbers before stopping on the actual value.
# Task
As a step towards achieving this; you have decided to create a function that will produce a multi-dimensional array out of the hit count value. Each inner dimension of the array represents an individual digit in the hit count, and will include all numbers that come before it, going back to 0.
## Rules
* The function will take one argument which will be a four character `string` representing hit count
* The function must return a multi-dimensional array containing four inner arrays
* The final value in each inner array must be the actual value to be displayed
* Values returned in the array must be of the type `number`
**Examples**
|
def counter_effect(hit_count):
return [[i for i in range(int(hit_count[x]) + 1)] for x in range(4)]
|
def counter_effect(hit_count):
return [[i for i in range(int(hit_count[x]) + 1)] for x in range(4)]
|
train
|
APPS_structured
|
You are given a binary string $s$ (recall that a string is binary if each character is either $0$ or $1$).
Let $f(t)$ be the decimal representation of integer $t$ written in binary form (possibly with leading zeroes). For example $f(011) = 3, f(00101) = 5, f(00001) = 1, f(10) = 2, f(000) = 0$ and $f(000100) = 4$.
The substring $s_{l}, s_{l+1}, \dots , s_{r}$ is good if $r - l + 1 = f(s_l \dots s_r)$.
For example string $s = 1011$ has $5$ good substrings: $s_1 \dots s_1 = 1$, $s_3 \dots s_3 = 1$, $s_4 \dots s_4 = 1$, $s_1 \dots s_2 = 10$ and $s_2 \dots s_4 = 011$.
Your task is to calculate the number of good substrings of string $s$.
You have to answer $t$ independent queries.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 1000$) — the number of queries.
The only line of each query contains string $s$ ($1 \le |s| \le 2 \cdot 10^5$), consisting of only digits $0$ and $1$.
It is guaranteed that $\sum\limits_{i=1}^{t} |s_i| \le 2 \cdot 10^5$.
-----Output-----
For each query print one integer — the number of good substrings of string $s$.
-----Example-----
Input
4
0110
0101
00001000
0001000
Output
4
3
4
3
|
t=int(input())
for i in range(t):
a=[int(x) for x in list(input())]
n=len(a)
zero=0
arr=0
for i in range(n):
if a[i]==1:
size=2
num=1
arr+=1
if i!=n-1:
j=i+1
if a[j]==1:
num*=2+1
else:
num*=2
while num<=size+zero and num>=size:
arr+=1
if j==n-1:
break
j+=1
if a[j]==1:
num=num*2+1
else:
num*=2
size+=1
zero=0
else:
zero+=1
print(arr)
|
t=int(input())
for i in range(t):
a=[int(x) for x in list(input())]
n=len(a)
zero=0
arr=0
for i in range(n):
if a[i]==1:
size=2
num=1
arr+=1
if i!=n-1:
j=i+1
if a[j]==1:
num*=2+1
else:
num*=2
while num<=size+zero and num>=size:
arr+=1
if j==n-1:
break
j+=1
if a[j]==1:
num=num*2+1
else:
num*=2
size+=1
zero=0
else:
zero+=1
print(arr)
|
train
|
APPS_structured
|
Tomya is a girl. She loves Chef Ciel very much.
Tomya like a positive integer p, and now she wants to get a receipt of Ciel's restaurant whose total price is exactly p.
The current menus of Ciel's restaurant are shown the following table.
Name of Menupriceeel flavored water1deep-fried eel bones2clear soup made with eel livers4grilled eel livers served with grated radish8savory egg custard with eel16eel fried rice (S)32eel fried rice (L)64grilled eel wrapped in cooked egg128eel curry rice256grilled eel over rice512deluxe grilled eel over rice1024eel full-course2048
Note that the i-th menu has the price 2i-1 (1 ≤ i ≤ 12).
Since Tomya is a pretty girl, she cannot eat a lot.
So please find the minimum number of menus whose total price is exactly p.
Note that if she orders the same menu twice, then it is considered as two menus are ordered. (See Explanations for details)
-----Input-----
The first line contains an integer T, the number of test cases.
Then T test cases follow.
Each test case contains an integer p.
-----Output-----
For each test case, print the minimum number of menus whose total price is exactly p.
-----Constraints-----
1 ≤ T ≤ 5
1 ≤ p ≤ 100000 (105)
There exists combinations of menus whose total price is exactly p.
-----Sample Input-----
4
10
256
255
4096
-----Sample Output-----
2
1
8
2
-----Explanations-----
In the first sample, examples of the menus whose total price is 10 are the following:
1+1+1+1+1+1+1+1+1+1 = 10 (10 menus)
1+1+1+1+1+1+1+1+2 = 10 (9 menus)
2+2+2+2+2 = 10 (5 menus)
2+4+4 = 10 (3 menus)
2+8 = 10 (2 menus)
Here the minimum number of menus is 2.
In the last sample, the optimal way is 2048+2048=4096 (2 menus).
Note that there is no menu whose price is 4096.
|
N=int(input())
for i in range(N):
p=[2048,1024,512,256,128,64,32,16,8,4,2,1]
a=int(input())
count=0
for i in p:
if(a>=i):
count=count+a//i
a=a%i
print(count)
|
N=int(input())
for i in range(N):
p=[2048,1024,512,256,128,64,32,16,8,4,2,1]
a=int(input())
count=0
for i in p:
if(a>=i):
count=count+a//i
a=a%i
print(count)
|
train
|
APPS_structured
|
You have an initial power P, an initial score of 0 points, and a bag of tokens.
Each token can be used at most once, has a value token[i], and has potentially two ways to use it.
If we have at least token[i] power, we may play the token face up, losing token[i] power, and gaining 1 point.
If we have at least 1 point, we may play the token face down, gaining token[i] power, and losing 1 point.
Return the largest number of points we can have after playing any number of tokens.
Example 1:
Input: tokens = [100], P = 50
Output: 0
Example 2:
Input: tokens = [100,200], P = 150
Output: 1
Example 3:
Input: tokens = [100,200,300,400], P = 200
Output: 2
Note:
tokens.length <= 1000
0 <= tokens[i] < 10000
0 <= P < 10000
|
class Solution:
def bagOfTokensScore(self, tokens: List[int], P: int) -> int:
tokens = sorted(tokens)
left = 0
right = len(tokens) - 1
points = 0
if len(tokens) == 1:
if tokens[0] <= P:
return 1
if len(tokens) == 0:
return 0
while left < right:
if tokens[left] <= P:
P -= tokens[left]
left += 1
points += 1
elif tokens[left] > P and points > 0:
P += tokens[right]
points -= 1
right -= 1
elif points == 0 and tokens[left] > P:
break
if P >= tokens[left]:
points += 1
return points
|
class Solution:
def bagOfTokensScore(self, tokens: List[int], P: int) -> int:
tokens = sorted(tokens)
left = 0
right = len(tokens) - 1
points = 0
if len(tokens) == 1:
if tokens[0] <= P:
return 1
if len(tokens) == 0:
return 0
while left < right:
if tokens[left] <= P:
P -= tokens[left]
left += 1
points += 1
elif tokens[left] > P and points > 0:
P += tokens[right]
points -= 1
right -= 1
elif points == 0 and tokens[left] > P:
break
if P >= tokens[left]:
points += 1
return points
|
train
|
APPS_structured
|
Chef is good at making pancakes. Generally he gets requests to serve N pancakes at once.
He serves them in the form of a stack.
A pancake can be treated as a circular disk with some radius.
Chef needs to take care that when he places a pancake on the top of the stack the radius of the pancake should not exceed the radius of the largest pancake in the stack by more than 1.
Additionally all radii should be positive integers, and the bottom most pancake should have its radius as 1.
Chef wants you to find out in how many ways can he create a stack containing N pancakes.
Input
First line of the input contains T (T <= 1000) denoting the number of test cases.
T lines follow each containing a single integer N (1 <= N <= 1000) denoting the size of the required stack.
Output
For each case the output should be a single integer representing the number of ways a stack of size N can be created. As the answer can be large print it modulo 1000000007.
Example
Input
2
1
2
Output
1
2
|
#!/usr/bin/env python
BELL = []
for i in range(1000): BELL.append([0] * 1000)
BELL[0][0] = 1
for r in range(1, 1000):
BELL[r][0] = BELL[r-1][r-1]
for c in range(1, r + 1):
BELL[r][c] = (BELL[r-1][c-1] + BELL[r][c-1]) % 1000000007
def main():
T = int(input())
for t in range(T):
N = int(input())
print(BELL[N-1][N-1])
main()
|
#!/usr/bin/env python
BELL = []
for i in range(1000): BELL.append([0] * 1000)
BELL[0][0] = 1
for r in range(1, 1000):
BELL[r][0] = BELL[r-1][r-1]
for c in range(1, r + 1):
BELL[r][c] = (BELL[r-1][c-1] + BELL[r][c-1]) % 1000000007
def main():
T = int(input())
for t in range(T):
N = int(input())
print(BELL[N-1][N-1])
main()
|
train
|
APPS_structured
|
The four bases found in DNA are adenine (A), cytosine (C), guanine (G) and thymine (T).
In genetics, GC-content is the percentage of Guanine (G) and Cytosine (C) bases on a DNA molecule that are either guanine or cytosine.
Given a DNA sequence (a string) return the GC-content in percent, rounded up to 2 decimal digits for Python, not rounded in all other languages.
For more information about GC-content you can take a look to [wikipedia GC-content](https://en.wikipedia.org/wiki/GC-content).
**For example**: the GC-content of the following DNA sequence is 50%:
"AAATTTCCCGGG".
**Note**: You can take a look to my others bio-info kata [here](http://www.codewars.com/users/nbeck/authored)
|
def gc_content(seq):
return round(sum(c in 'GC' for c in seq) / len(seq) * 100, 2) if len(seq) else 0.0
|
def gc_content(seq):
return round(sum(c in 'GC' for c in seq) / len(seq) * 100, 2) if len(seq) else 0.0
|
train
|
APPS_structured
|
With one die of 6 sides we will have six different possible results:``` 1, 2, 3, 4, 5, 6``` .
With 2 dice of six sides, we will have 36 different possible results:
```
(1,1),(1,2),(2,1),(1,3),(3,1),(1,4),(4,1),(1,5),
(5,1), (1,6),(6,1),(2,2),(2,3),(3,2),(2,4),(4,2),
(2,5),(5,2)(2,6),(6,2),(3,3),(3,4),(4,3),(3,5),(5,3),
(3,6),(6,3),(4,4),(4,5),(5,4),(4,6),(6,4),(5,5),
(5,6),(6,5),(6,6)
```
So, with 2 dice of 6 sides we get 36 different events.
```
([6,6] ---> 36)
```
But with 2 different dice we can get for this case, the same number of events.
One die of ```4 sides``` and another of ```9 sides``` will produce the exact amount of events.
```
([4,9] ---> 36)
```
We say that the dice set ```[4,9]``` is equivalent to ```[6,6]``` because both produce the same number of events.
Also we may have an amount of three dice producing the same amount of events. It will be for:
```
[4,3,3] ---> 36
```
(One die of 4 sides and two dice of 3 sides each)
Perhaps you may think that the following set is equivalent: ```[6,3,2]``` but unfortunately dice have a **minimum of three sides** (well, really a
tetrahedron with one empty side)
The task for this kata is to get the amount of equivalent dice sets, having **2 dice at least**,for a given set.
For example, for the previous case: [6,6] we will have 3 equivalent sets that are: ``` [4, 3, 3], [12, 3], [9, 4]``` .
You may assume that dice are available from 3 and above for any value up to an icosahedral die (20 sides).
```
[5,6,4] ---> 5 (they are [10, 4, 3], [8, 5, 3], [20, 6], [15, 8], [12, 10])
```
For the cases we cannot get any equivalent set the result will be `0`.
For example for the set `[3,3]` we will not have equivalent dice.
Range of inputs for Random Tests:
```
3 <= sides <= 15
2 <= dices <= 7
```
See examples in the corresponding box.
Enjoy it!!
|
from itertools import combinations_with_replacement
from numpy import prod
def eq_dice(set_):
lst = sorted(set_)
eq, dice, count = 0, [], prod(lst)
for sides in range(3, 21):
if count % sides == 0: dice.append(sides)
for num_dice in range(2, 8):
for c in combinations_with_replacement(dice, num_dice):
if prod(c) == count and sorted(c) != lst: eq += 1
return eq
|
from itertools import combinations_with_replacement
from numpy import prod
def eq_dice(set_):
lst = sorted(set_)
eq, dice, count = 0, [], prod(lst)
for sides in range(3, 21):
if count % sides == 0: dice.append(sides)
for num_dice in range(2, 8):
for c in combinations_with_replacement(dice, num_dice):
if prod(c) == count and sorted(c) != lst: eq += 1
return eq
|
train
|
APPS_structured
|
OK, my warriors! Now that you beat the big BOSS, you can unlock three new skills. (Does it sound like we're playing an RPG? ;-)
## The Arrow Function (JS only)
The first skill is the arrow function. Let's look at some examples to see how it works:
```python
#ignore this part, it is just for JS
```
As you can see, its syntax is:
```python
#ignore this part, it is just for JS
```
If only one parameter exists on the left side of the arrow, the bracket can be omitted. If only one expression exists on the right side of the arrow, the curly braces can also be omitted. The example below shows a function with the () and {} omitted.
```python
#ignore this part, it is just for JS
```
If the right side of the arrow is a complex statement, you must use curly braces:
```python
#ignore this part, it is just for JS
```
So far, our examples have used function assignment. However, an arrow function can also be used as a parameter to a function call, as well. When used as a parameter, the arrow function does not require a name. Let's rewrite the string.replace() example we saw from a previous training using our new skill:
```python
#ignore this part, it is just for JS
```
String.replace takes a regular expression and a function. The function is invoked on each substring matching the regex, and return the string replacement of that match. In this case, the arrow function takes the matched string as the parameter ```x```, and returns the upper cased value of ```x```.
In the soon to learn the arrayObject and its methods, there are many applications on the arrow function, which is the reason we first learn the arrow function. The arrow function has more complex usage and usage restrictions, but we don't need to learn to be so deep, so we only learn the contents of the above.
## The Spread Operator
The second skill is the ```spread operator```. The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
It looks like this: ...obj. It can be used in three places:
1\. In function calls:
```python
def plus(a,b,c,d,e): return a+b+c+d+e
arg1=[1,2,3,4,5]
arg2=[2,3]
print plus(...arg1) #output is 15
print plus(...arg2) #output is 5
```
```...arg1``` spreads all the elements in arg1 into individual parameters to plus().
In Javascript, it's also possible to use the spread operator in the middle of a parameter list, as was done with ```...arg2```.
2\. Creating array literals (JS and Ruby):
```python
#ignore this part, it is just for JS and Ruby
```
```...a``` spreads out the array's elements, making them individual elements in b.
3\. Used for ```deconstruction```. destructuring is also a new member of ES6. It is the third skill we learn in this training.
First, let's look at a simple example of destructuring:
```python
a,b=[1,2] #or [a,b]=[1,2]
print a #output is 1
print b #output is 2
```
Destructuring allows us to assign variables in a sentence-like form. Here's a slightly more complicated example:
```python
a,b=[1,2] #or [a,b]=[1,2]
#old way to swap them:
#c=a; a=b; c=b
b,a=[a,b] #or [b,a]=[a,b]
print a #output is 2
print b #output is 1
```
With destructuring, we don't need a temporary variable to help us exchange the two values.
You can use the spread operator for destructuring like this:
```python
#ignore this part, it is just for JS
```
Please note: the spread operator must be the last variable: ```[...a,b]=[1,2,3,4,5]``` does not work.
```a``` was assigned to the first element of the array, and``` b ```was initialized with the remaining elements in the array.
Javascript note: If you see an ellipse ... in the argument list in a function declaration, it is not a spread operator, it is a structure called rest parameters. The rest parameter syntax allows us to represent an indefinite number of arguments as an array, like this:
```python
def plus(*num):
rs=0
for x in num: rs+=x
return rs
print plus(1,2) #output is 3
print plus(3,4,5) #output is 12
```
The rest paramater must be the last argument in the function definition argument list.
In the next example, we use a rest parameter to collect all the values passed to mul() after the first into an array. We then multiply each of them by the first parameter and return that array:
```python
def mul(a,*b):
b=list(b) #default type would be tuple
for i in xrange(len(b)): b[i]*=a
return b
print mul(2,1,1,1) #output is [2,2,2]
print mul(2,1,2,3,4) #output is [2,4,6,8]
```
Ok, the lesson is over. Did you get it all? Let's do a task, now.
## Task
Create a function ```shuffleIt```. The function accepts two or more parameters. The first parameter arr is an array of numbers, followed by an arbitrary number of numeric arrays. Each numeric array contains two numbers, which are indices for elements in arr (the numbers will always be within bounds). For every such array, swap the elements. Try to use all your new skills: arrow functions, the spread operator, destructuring, and rest parameters.
Example:
```
shuffleIt([1,2,3,4,5],[1,2]) should return [1,3,2,4,5]
shuffleIt([1,2,3,4,5],[1,2],[3,4]) should return [1,3,2,5,4]
shuffleIt([1,2,3,4,5],[1,2],[3,4],[2,3]) should return [1,3,5,2,4]
```
[Next training (#23 Array Methods) >>](http://www.codewars.com/kata/572af273a3af3836660014a1)
## [Series](http://github.com/myjinxin2015/Katas-list-of-Training-JS-series)
( ↑↑↑ Click the link above can get my newest kata list, Please add it to your favorites)
- [#1: create your first JS function helloWorld](http://www.codewars.com/kata/571ec274b1c8d4a61c0000c8)
- [#2: Basic data types--Number](http://www.codewars.com/kata/571edd157e8954bab500032d)
- [#3: Basic data types--String](http://www.codewars.com/kata/571edea4b625edcb51000d8e)
- [#4: Basic data types--Array](http://www.codewars.com/kata/571effabb625ed9b0600107a)
- [#5: Basic data types--Object](http://www.codewars.com/kata/571f1eb77e8954a812000837)
- [#6: Basic data types--Boolean and conditional statements if..else](http://www.codewars.com/kata/571f832f07363d295d001ba8)
- [#7: if..else and ternary operator](http://www.codewars.com/kata/57202aefe8d6c514300001fd)
- [#8: Conditional statement--switch](http://www.codewars.com/kata/572059afc2f4612825000d8a)
- [#9: loop statement --while and do..while](http://www.codewars.com/kata/57216d4bcdd71175d6000560)
- [#10: loop statement --for](http://www.codewars.com/kata/5721a78c283129e416000999)
- [#11: loop statement --break,continue](http://www.codewars.com/kata/5721c189cdd71194c1000b9b)
- [#12: loop statement --for..in and for..of](http://www.codewars.com/kata/5722b3f0bd5583cf44001000)
- [#13: Number object and its properties](http://www.codewars.com/kata/5722fd3ab7162a3a4500031f)
- [#14: Methods of Number object--toString() and toLocaleString()](http://www.codewars.com/kata/57238ceaef9008adc7000603)
- [#15: Methods of Number object--toFixed(), toExponential() and toPrecision()](http://www.codewars.com/kata/57256064856584bc47000611)
- [#16: Methods of String object--slice(), substring() and substr()](http://www.codewars.com/kata/57274562c8dcebe77e001012)
- [#17: Methods of String object--indexOf(), lastIndexOf() and search()](http://www.codewars.com/kata/57277a31e5e51450a4000010)
- [#18: Methods of String object--concat() split() and its good friend join()](http://www.codewars.com/kata/57280481e8118511f7000ffa)
- [#19: Methods of String object--toUpperCase() toLowerCase() and replace()](http://www.codewars.com/kata/5728203b7fc662a4c4000ef3)
- [#20: Methods of String object--charAt() charCodeAt() and fromCharCode()](http://www.codewars.com/kata/57284d23e81185ae6200162a)
- [#21: Methods of String object--trim() and the string template](http://www.codewars.com/kata/5729b103dd8bac11a900119e)
- [#22: Unlock new skills--Arrow function,spread operator and deconstruction](http://www.codewars.com/kata/572ab0cfa3af384df7000ff8)
- [#23: methods of arrayObject---push(), pop(), shift() and unshift()](http://www.codewars.com/kata/572af273a3af3836660014a1)
- [#24: methods of arrayObject---splice() and slice()](http://www.codewars.com/kata/572cb264362806af46000793)
- [#25: methods of arrayObject---reverse() and sort()](http://www.codewars.com/kata/572df796914b5ba27c000c90)
- [#26: methods of arrayObject---map()](http://www.codewars.com/kata/572fdeb4380bb703fc00002c)
- [#27: methods of arrayObject---filter()](http://www.codewars.com/kata/573023c81add650b84000429)
- [#28: methods of arrayObject---every() and some()](http://www.codewars.com/kata/57308546bd9f0987c2000d07)
- [#29: methods of arrayObject---concat() and join()](http://www.codewars.com/kata/5731861d05d14d6f50000626)
- [#30: methods of arrayObject---reduce() and reduceRight()](http://www.codewars.com/kata/573156709a231dcec9000ee8)
- [#31: methods of arrayObject---isArray() indexOf() and toString()](http://www.codewars.com/kata/5732b0351eb838d03300101d)
- [#32: methods of Math---round() ceil() and floor()](http://www.codewars.com/kata/5732d3c9791aafb0e4001236)
- [#33: methods of Math---max() min() and abs()](http://www.codewars.com/kata/5733d6c2d780e20173000baa)
- [#34: methods of Math---pow() sqrt() and cbrt()](http://www.codewars.com/kata/5733f948d780e27df6000e33)
- [#35: methods of Math---log() and its family](http://www.codewars.com/kata/57353de879ccaeb9f8000564)
- [#36: methods of Math---kata author's lover:random()](http://www.codewars.com/kata/5735956413c2054a680009ec)
- [#37: Unlock new weapon---RegExp Object](http://www.codewars.com/kata/5735e39313c205fe39001173)
- [#38: Regular Expression--"^","$", "." and test()](http://www.codewars.com/kata/573975d3ac3eec695b0013e0)
- [#39: Regular Expression--"?", "*", "+" and "{}"](http://www.codewars.com/kata/573bca07dffc1aa693000139)
- [#40: Regular Expression--"|", "[]" and "()"](http://www.codewars.com/kata/573d11c48b97c0ad970002d4)
- [#41: Regular Expression--"\"](http://www.codewars.com/kata/573e6831e3201f6a9b000971)
- [#42: Regular Expression--(?:), (?=) and (?!)](http://www.codewars.com/kata/573fb9223f9793e485000453)
|
def shuffle_it(xs, *nss):
for i, j in nss:
xs[i], xs[j] = xs[j], xs[i]
return xs
|
def shuffle_it(xs, *nss):
for i, j in nss:
xs[i], xs[j] = xs[j], xs[i]
return xs
|
train
|
APPS_structured
|
Mandarin chinese
, Russian and Vietnamese as well.
Chef is organising a contest with $P$ problems (numbered $1$ through $P$). Each problem has $S$ subtasks (numbered $1$ through $S$).
The difficulty of a problem can be calculated as follows:
- Let's denote the score of the $k$-th subtask of this problem by $SC_k$ and the number of contestants who solved it by $NS_k$.
- Consider the subtasks sorted in the order of increasing score.
- Calculate the number $n$ of valid indices $k$ such that $NS_k > NS_{k + 1}$.
- For problem $i$, the difficulty is a pair of integers $(n, i)$.
You should sort the problems in the increasing order of difficulty levels. Since difficulty level is a pair, problem $a$ is more difficult than problem $b$ if the number $n$ is greater for problem $a$ than for problem $b$, or if $a > b$ and $n$ is the same for problems $a$ and $b$.
-----Input-----
- The first line of the input contains two space-separated integers $P$ and $S$ denoting the number of problems and the number of subtasks in each problem.
- $2P$ lines follow. For each valid $i$, the $2i-1$-th of these lines contains $S$ space-separated integers $SC_1, SC_2, \dots, SC_S$ denoting the scores of the $i$-th problem's subtasks, and the $2i$-th of these lines contains $S$ space-separated integers $NS_1, NS_2, \dots, NS_S$ denoting the number of contestants who solved the $i$-th problem's subtasks.
-----Output-----
Print $P$ lines containing one integer each — the indices of the problems in the increasing order of difficulty.
-----Constraints-----
- $1 \le P \le 100,000$
- $2 \le S \le 30$
- $1 \le SC_i \le 100$ for each valid $i$
- $1 \le NS_i \le 1,000$ for each valid $i$
- in each problem, the scores of all subtasks are unique
-----Subtasks-----
Subtask #1 (25 points): $S = 2$
Subtask #2 (75 points): original constraints
-----Example Input-----
3 3
16 24 60
498 861 589
14 24 62
72 557 819
16 15 69
435 779 232
-----Example Output-----
2
1
3
|
from collections import defaultdict
from operator import itemgetter
p, s = list(map(int, input().split()))
diff = []
for _ in range(p):
sc = list(map(int, input().split()))
nk = list(map(int, input().split()))
arr = list(zip(sc, nk))
arr_sort = sorted(arr, key = itemgetter(0))
# print(arr)
temp = 0
for i in range(s-1):
if arr_sort[i][1] > arr_sort[i+1][1]:
temp += 1
a = [temp, _+1]
diff.append(a)
temp = diff[:]
# temp = [(1, 2),(1, 1),(2, 1),(2, 3)]
temp.sort(key=lambda x: (x[0], x[1]))
# print(temp)
'''
t = 1
d = defaultdict
for i in temp:
d[i] = t
t += 1
'''
diff = sorted(diff, key = lambda x: x[0])
for i in diff:
print(i[1])
'''
v1=sorted(diff,key = itemgetter(0))
for i in v1:
print(i[1])
'''
|
from collections import defaultdict
from operator import itemgetter
p, s = list(map(int, input().split()))
diff = []
for _ in range(p):
sc = list(map(int, input().split()))
nk = list(map(int, input().split()))
arr = list(zip(sc, nk))
arr_sort = sorted(arr, key = itemgetter(0))
# print(arr)
temp = 0
for i in range(s-1):
if arr_sort[i][1] > arr_sort[i+1][1]:
temp += 1
a = [temp, _+1]
diff.append(a)
temp = diff[:]
# temp = [(1, 2),(1, 1),(2, 1),(2, 3)]
temp.sort(key=lambda x: (x[0], x[1]))
# print(temp)
'''
t = 1
d = defaultdict
for i in temp:
d[i] = t
t += 1
'''
diff = sorted(diff, key = lambda x: x[0])
for i in diff:
print(i[1])
'''
v1=sorted(diff,key = itemgetter(0))
for i in v1:
print(i[1])
'''
|
train
|
APPS_structured
|
Welcome young Jedi! In this Kata you must create a function that takes an amount of US currency in `cents`, and returns a dictionary/hash which shows the least amount of coins used to make up that amount. The only coin denominations considered in this exercise are: `Pennies (1¢), Nickels (5¢), Dimes (10¢) and Quarters (25¢)`.
Therefor the dictionary returned should contain exactly 4 key/value pairs.
Notes:
* If the function is passed either 0 or a negative number, the function should return the dictionary with all values equal to 0.
* If a float is passed into the function, its value should be be rounded down, and the resulting dictionary should never contain fractions of a coin.
## Examples
```
loose_change(56) ==> {'Nickels': 1, 'Pennies': 1, 'Dimes': 0, 'Quarters': 2}
loose_change(-435) ==> {'Nickels': 0, 'Pennies': 0, 'Dimes': 0, 'Quarters': 0}
loose_change(4.935) ==> {'Nickels': 0, 'Pennies': 4, 'Dimes': 0, 'Quarters': 0}
```
|
def loose_change(cents):
cents = max(int(cents), 0)
changes = {}
for i, n in enumerate((25, 10, 5, 1)):
units = ['Quarters', 'Dimes', 'Nickels', 'Pennies']
changes[ units[i] ] = cents // n
cents = cents % n
return changes
|
def loose_change(cents):
cents = max(int(cents), 0)
changes = {}
for i, n in enumerate((25, 10, 5, 1)):
units = ['Quarters', 'Dimes', 'Nickels', 'Pennies']
changes[ units[i] ] = cents // n
cents = cents % n
return changes
|
train
|
APPS_structured
|
There are n people that are split into some unknown number of groups. Each person is labeled with a unique ID from 0 to n - 1.
You are given an integer array groupSizes, where groupSizes[i] is the size of the group that person i is in. For example, if groupSizes[1] = 3, then person 1 must be in a group of size 3.
Return a list of groups such that each person i is in a group of size groupSizes[i].
Each person should appear in exactly one group, and every person must be in a group. If there are multiple answers, return any of them. It is guaranteed that there will be at least one valid solution for the given input.
Example 1:
Input: groupSizes = [3,3,3,3,3,1,3]
Output: [[5],[0,1,2],[3,4,6]]
Explanation:
The first group is [5]. The size is 1, and groupSizes[5] = 1.
The second group is [0,1,2]. The size is 3, and groupSizes[0] = groupSizes[1] = groupSizes[2] = 3.
The third group is [3,4,6]. The size is 3, and groupSizes[3] = groupSizes[4] = groupSizes[6] = 3.
Other possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].
Example 2:
Input: groupSizes = [2,1,3,3,3,2]
Output: [[1],[0,5],[2,3,4]]
Constraints:
groupSizes.length == n
1 <= n <= 500
1 <= groupSizes[i] <= n
|
class Solution:
def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
output = []
subgroup = []
count = 0
leng = len(groupSizes)
subsize = 0
while count < leng:
size = min(groupSizes)
while size in groupSizes:
ind = groupSizes.index(size)
subgroup.append(ind)
groupSizes[ind] = 501
count += 1
subsize += 1
if subsize % size == 0:
output.append(subgroup)
subgroup = []
subsize = 0
subgroup = []
return output
|
class Solution:
def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
output = []
subgroup = []
count = 0
leng = len(groupSizes)
subsize = 0
while count < leng:
size = min(groupSizes)
while size in groupSizes:
ind = groupSizes.index(size)
subgroup.append(ind)
groupSizes[ind] = 501
count += 1
subsize += 1
if subsize % size == 0:
output.append(subgroup)
subgroup = []
subsize = 0
subgroup = []
return output
|
train
|
APPS_structured
|
**This Kata is intended as a small challenge for my students**
All Star Code Challenge #19
You work for an ad agency and your boss, Bob, loves a catchy slogan. He's always jumbling together "buzz" words until he gets one he likes. You're looking to impress Boss Bob with a function that can do his job for him.
Create a function called sloganMaker() that accepts an array of string "buzz" words. The function returns an array of all possible UNIQUE string permutations of the buzz words (concatonated and separated by spaces).
Your boss is not very bright, so anticipate him using the same "buzz" word more than once, by accident. The function should ignore these duplicate string inputs.
```
sloganMaker(["super", "hot", "guacamole"]);
//[ 'super hot guacamole',
// 'super guacamole hot',
// 'hot super guacamole',
// 'hot guacamole super',
// 'guacamole super hot',
// 'guacamole hot super' ]
sloganMaker(["cool", "pizza", "cool"]); // => [ 'cool pizza', 'pizza cool' ]
```
Note:
There should be NO duplicate strings in the output array
The input array MAY contain duplicate strings, which should STILL result in an output array with all unique strings
An empty string is valid input
```if-not:python,crystal
The order of the permutations in the output array does not matter
```
```if:python,crystal
The order of the output array must match those rules:
1. Generate the permutations in lexicographic order of the original array.
2. keep only the first occurence of a permutation, when duplicates are found.
```
|
def slogan_maker(array):
print(array)
from itertools import permutations
array = remove_duplicate(array)
return [' '.join(element) for element in list(permutations(array, len(array)))]
def remove_duplicate(old_list):
final_list = []
for num in old_list:
if num not in final_list:
final_list.append(num)
return final_list
|
def slogan_maker(array):
print(array)
from itertools import permutations
array = remove_duplicate(array)
return [' '.join(element) for element in list(permutations(array, len(array)))]
def remove_duplicate(old_list):
final_list = []
for num in old_list:
if num not in final_list:
final_list.append(num)
return final_list
|
train
|
APPS_structured
|
There is a rectangular grid of size $n \times m$. Each cell of the grid is colored black ('0') or white ('1'). The color of the cell $(i, j)$ is $c_{i, j}$. You are also given a map of directions: for each cell, there is a direction $s_{i, j}$ which is one of the four characters 'U', 'R', 'D' and 'L'.
If $s_{i, j}$ is 'U' then there is a transition from the cell $(i, j)$ to the cell $(i - 1, j)$; if $s_{i, j}$ is 'R' then there is a transition from the cell $(i, j)$ to the cell $(i, j + 1)$; if $s_{i, j}$ is 'D' then there is a transition from the cell $(i, j)$ to the cell $(i + 1, j)$; if $s_{i, j}$ is 'L' then there is a transition from the cell $(i, j)$ to the cell $(i, j - 1)$.
It is guaranteed that the top row doesn't contain characters 'U', the bottom row doesn't contain characters 'D', the leftmost column doesn't contain characters 'L' and the rightmost column doesn't contain characters 'R'.
You want to place some robots in this field (at most one robot in a cell). The following conditions should be satisfied.
Firstly, each robot should move every time (i.e. it cannot skip the move). During one move each robot goes to the adjacent cell depending on the current direction. Secondly, you have to place robots in such a way that there is no move before which two different robots occupy the same cell (it also means that you cannot place two robots in the same cell). I.e. if the grid is "RL" (one row, two columns, colors does not matter there) then you can place two robots in cells $(1, 1)$ and $(1, 2)$, but if the grid is "RLL" then you cannot place robots in cells $(1, 1)$ and $(1, 3)$ because during the first second both robots will occupy the cell $(1, 2)$.
The robots make an infinite number of moves.
Your task is to place the maximum number of robots to satisfy all the conditions described above and among all such ways, you have to choose one where the number of black cells occupied by robots before all movements is the maximum possible. Note that you can place robots only before all movements.
You have to answer $t$ independent test cases.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 5 \cdot 10^4$) — the number of test cases. Then $t$ test cases follow.
The first line of the test case contains two integers $n$ and $m$ ($1 < nm \le 10^6$) — the number of rows and the number of columns correspondingly.
The next $n$ lines contain $m$ characters each, where the $j$-th character of the $i$-th line is $c_{i, j}$ ($c_{i, j}$ is either '0' if the cell $(i, j)$ is black or '1' if the cell $(i, j)$ is white).
The next $n$ lines also contain $m$ characters each, where the $j$-th character of the $i$-th line is $s_{i, j}$ ($s_{i, j}$ is 'U', 'R', 'D' or 'L' and describes the direction of the cell $(i, j)$).
It is guaranteed that the sum of the sizes of fields does not exceed $10^6$ ($\sum nm \le 10^6$).
-----Output-----
For each test case, print two integers — the maximum number of robots you can place to satisfy all the conditions described in the problem statement and the maximum number of black cells occupied by robots before all movements if the number of robots placed is maximized. Note that you can place robots only before all movements.
-----Example-----
Input
3
1 2
01
RL
3 3
001
101
110
RLL
DLD
ULL
3 3
000
000
000
RRD
RLD
ULL
Output
2 1
4 3
2 2
|
import sys
from collections import deque
input = sys.stdin.readline
t = int(input())
for _ in range(t):
n, m = map(int, input().split())
s = [input() for i in range(n)]
grid = [input() for i in range(n)]
robot_cnt = 0
black_cnt = 0
graph = [-1] * (n * m)
rev_graph = [[] for i in range(n * m)]
for i in range(n):
for j in range(m):
if grid[i][j] == "U":
graph[i * m + j] = (i - 1) * m + j
rev_graph[(i - 1) * m + j].append(i * m + j)
elif grid[i][j] == "R":
graph[i * m + j] = i * m + (j + 1)
rev_graph[i * m + (j + 1)].append(i * m + j)
elif grid[i][j] == "D":
graph[i * m + j] = (i + 1) * m + j
rev_graph[(i + 1) * m + j].append(i * m + j)
elif grid[i][j] == "L":
graph[i * m + j] = i * m + (j - 1)
rev_graph[i * m + (j - 1)].append(i * m + j)
is_start = [True] * (n * m)
for i in graph:
is_start[i] = False
is_cycle = [False] * (n * m)
period = [0] * (n * m)
for i in range(n * m):
if not is_start[i]:
continue
st = i
period[i] = 1
while True:
nxt_i = graph[i]
if period[nxt_i] < 0:
tmp = period[nxt_i]
break
if period[nxt_i] > 0:
tmp = -(period[i] - period[nxt_i] + 1)
is_cycle[nxt_i] = True
break
period[graph[i]] = period[i] + 1
i = graph[i]
i = st
period[i] = tmp
while True:
nxt_i = graph[i]
if period[nxt_i] < 0:
break
period[graph[i]] = tmp
i = graph[i]
# cycle without side road
for i in range(n * m):
if period[i] == 0:
robot_cnt += 1
if s[i // m][i % m] == "0":
black_cnt += 1
# cycle with road
for i in range(n * m):
if not is_cycle[i]:
continue
MOD = - period[i]
period[i] = 0
is_black = [False] * MOD
if s[i // m][i % m] == "0":
is_black[0] = True
q = deque([i])
while q:
v = q.pop()
for nxt_v in rev_graph[v]:
if period[nxt_v] >= 0:
continue
period[nxt_v] = (period[v] + 1) % MOD
if s[nxt_v // m][nxt_v % m] == "0":
is_black[period[nxt_v]] = True
q.append(nxt_v)
robot_cnt += MOD
black_cnt += sum(is_black)
print(robot_cnt, black_cnt)
|
import sys
from collections import deque
input = sys.stdin.readline
t = int(input())
for _ in range(t):
n, m = map(int, input().split())
s = [input() for i in range(n)]
grid = [input() for i in range(n)]
robot_cnt = 0
black_cnt = 0
graph = [-1] * (n * m)
rev_graph = [[] for i in range(n * m)]
for i in range(n):
for j in range(m):
if grid[i][j] == "U":
graph[i * m + j] = (i - 1) * m + j
rev_graph[(i - 1) * m + j].append(i * m + j)
elif grid[i][j] == "R":
graph[i * m + j] = i * m + (j + 1)
rev_graph[i * m + (j + 1)].append(i * m + j)
elif grid[i][j] == "D":
graph[i * m + j] = (i + 1) * m + j
rev_graph[(i + 1) * m + j].append(i * m + j)
elif grid[i][j] == "L":
graph[i * m + j] = i * m + (j - 1)
rev_graph[i * m + (j - 1)].append(i * m + j)
is_start = [True] * (n * m)
for i in graph:
is_start[i] = False
is_cycle = [False] * (n * m)
period = [0] * (n * m)
for i in range(n * m):
if not is_start[i]:
continue
st = i
period[i] = 1
while True:
nxt_i = graph[i]
if period[nxt_i] < 0:
tmp = period[nxt_i]
break
if period[nxt_i] > 0:
tmp = -(period[i] - period[nxt_i] + 1)
is_cycle[nxt_i] = True
break
period[graph[i]] = period[i] + 1
i = graph[i]
i = st
period[i] = tmp
while True:
nxt_i = graph[i]
if period[nxt_i] < 0:
break
period[graph[i]] = tmp
i = graph[i]
# cycle without side road
for i in range(n * m):
if period[i] == 0:
robot_cnt += 1
if s[i // m][i % m] == "0":
black_cnt += 1
# cycle with road
for i in range(n * m):
if not is_cycle[i]:
continue
MOD = - period[i]
period[i] = 0
is_black = [False] * MOD
if s[i // m][i % m] == "0":
is_black[0] = True
q = deque([i])
while q:
v = q.pop()
for nxt_v in rev_graph[v]:
if period[nxt_v] >= 0:
continue
period[nxt_v] = (period[v] + 1) % MOD
if s[nxt_v // m][nxt_v % m] == "0":
is_black[period[nxt_v]] = True
q.append(nxt_v)
robot_cnt += MOD
black_cnt += sum(is_black)
print(robot_cnt, black_cnt)
|
train
|
APPS_structured
|
A valid parentheses sequence is a non-empty string where each character is either '(' or ')', which satisfies the following constraint:
You can find a way to repeat erasing adjacent pairs of parentheses '()' until it becomes empty.
For example, '(())' and '()((()()))' are valid parentheses sequences, but ')()(' and '(()' are not.
Mike has a valid parentheses sequence. He really likes everything about his sequence, except the fact that it is quite long. So Mike has recently decided that he will replace his parentheses sequence with a new one in the near future. But not every valid parentheses sequence will satisfy him. To help you understand his requirements we'll introduce the pseudocode of function F(S):
FUNCTION F( S - a valid parentheses sequence )
BEGIN
balance = 0
max_balance = 0
FOR index FROM 1 TO LENGTH(S)
BEGIN
if S[index] == '(' then balance = balance + 1
if S[index] == ')' then balance = balance - 1
max_balance = max( max_balance, balance )
END
RETURN max_balance
END
In other words, F(S) is equal to the maximal balance over all prefixes of S.
Let's denote A as Mike's current parentheses sequence, and B as a candidate for a new one. Mike is willing to replace A with B if F(A) is equal to F(B). He would also like to choose B with the minimal possible length amongst ones satisfying the previous condition. If there are several such strings with the minimal possible length, then Mike will choose the least one lexicographically, considering '(' to be less than ')'.
Help Mike!
-----Input-----
The first line of the input contains one integer T denoting the number of testcases to process.
The only line of each testcase contains one string A denoting Mike's parentheses sequence. It is guaranteed that A only consists of the characters '(' and ')'. It is also guaranteed that A is a valid parentheses sequence.
-----Output-----
The output should contain exactly T lines, one line per each testcase in the order of their appearance. The only line of each testcase should contain one string B denoting the valid parentheses sequence that should be chosen by Mike to replace A.
-----Constraints-----
1 ≤ T ≤ 5;
1 ≤ |A| ≤ 100000(105).
-----Example-----
Input:
1
()((()()))
Output:
((()))
|
# cook your dish here
def fun(s):
bal=0
maxbal=0
for i in range(len(s)):
if s[i]=='(':
bal+=1
else:
bal-=1
maxbal=max(maxbal,bal)
return maxbal
t=int(input())
while t>0:
s=input()
maxbal=fun(s)
print('('*maxbal+')'*maxbal)
t-=1
|
# cook your dish here
def fun(s):
bal=0
maxbal=0
for i in range(len(s)):
if s[i]=='(':
bal+=1
else:
bal-=1
maxbal=max(maxbal,bal)
return maxbal
t=int(input())
while t>0:
s=input()
maxbal=fun(s)
print('('*maxbal+')'*maxbal)
t-=1
|
train
|
APPS_structured
|
#Permutation position
In this kata you will have to permutate through a string of lowercase letters, each permutation will start at ```a``` and you must calculate how many iterations it takes to reach the current permutation.
##examples
```
input: 'a'
result: 1
input: 'c'
result: 3
input: 'z'
result: 26
input: 'foo'
result: 3759
input: 'aba'
result: 27
input: 'abb'
result: 28
```
|
permutation_position=lambda p:sum(26**i*(ord(c)-97)for i,c in enumerate(p[::-1]))+1
|
permutation_position=lambda p:sum(26**i*(ord(c)-97)for i,c in enumerate(p[::-1]))+1
|
train
|
APPS_structured
|
To almost all of us solving sets of linear equations is quite obviously the most exciting bit of linear algebra. Benny does not agree though and wants to write a quick program to solve his homework problems for him. Unfortunately Benny's lack of interest in linear algebra means he has no real clue on how to go about this. Fortunately, you can help him!
Write a method ```solve``` that accepts a list of linear equations that your method will have to solve. The output should be a map (a `Map` object in JavaScript) with a value for each variable in the equations. If the system does not have a unique solution (has infinitely many solutions or is unsolvable), return ```null``` (`None` in python).
For example :
"2x + 4y + 6z = 18"
"3y + 3z = 6"
"x + 2y = z - 3"
should result in a map :
x = 2
y = -1
z = 3
Possible input equations have the following rules:
- Only the plus and minus operators are used on both the left and right hand side of the equation.
- Both sides of the equation can have variables; One variable can appear in multiple terms, on both sides.
- Variable names are strings of arbitrary length.
- All coefficients are integers and generally fall within the range of -150 to 150, with a few ranging from -1000 to 1000. Free terms are integers in range -20000 to 20000.
- Equations do not necessarily have variables.
- Equations have exactly one operator (+ or -) between terms.
Comparisons are performed with accuracy of `1e-6`.
**Note on numerical stability:**
There are many possible ways to solve a system of linear equations. One group of such algorithms is based on reduction and elimination methods. If you are going to use any of these, remember that such algorithms are in general *numerically unstable*, i.e. division operations repeated over and over introduce inaccuracies which accumulate from row to row. As a result it might occur that some value which is expected to be zero is actually larger, for example, `2.5e-10`. Such inaccuracies tend to be bigger in large equation systems, and random tests check systems of up to 26 equations. If it happens that small tests pass for you, and large tests fail, it probably means that you did not account for inaccuracies correctly.
Also note that tests do not depend on any reference solution, so the way how test cases are generated _is numrically stable_ - the only source of inaccuracies is your solution, and you need to account for it.
```if:python
___Note for python users:___
`numpy` module has been disabled, so that the task matches the one of the other languages. There is an anti-cheat measure about that, so you won't be able to import some other modules too (either way, you shouldn't need any module to solve this kata...)
```
|
def decode_eq_side(eq_side):
result = {}
sign, factor, var_name = 1, "", ""
def add_variable():
nonlocal factor, var_name, result
if var_name:
result[var_name] = result.get(var_name, 0) + sign * int(factor) if factor else result.get(var_name, 0) + sign
elif factor:
result[""] = result.get(var_name, 0) + sign * int(factor) if factor else result.get(var_name, 0) + sign
factor, var_name = "", ""
for i, s in enumerate(eq_side.replace(" ", "")):
if s == "+":
add_variable()
sign = 1
elif s == "-":
add_variable()
sign = -1
elif s.isdigit():
factor += s
else:
var_name += s
else:
add_variable()
return result
def decode_equation(equation):
variables, variables2 = [decode_eq_side(side) for side in equation.split("=")]
for var, factor in variables2.items():
variables[var] = variables.get(var, 0) - factor
variables[""] = -1*variables.get("", 0)
return variables
def solve(*equations):
# get equation variables and matrix
equations_variables = [decode_equation(equation) for equation in equations]
variable_names = {var_name for eq_vars in equations_variables for var_name in eq_vars}
variable_names.discard("")
variable_names = list(variable_names)
if len(variable_names) > len(equations_variables):
return None
equations_matrix = [[variables.get(var_name, 0) for var_name in variable_names] + [variables.get("", 0)] for variables in equations_variables]
del equations_variables
# gauss elimination
gauss_matrix = []
for i in range(len(variable_names)):
chosen_row = max(equations_matrix, key=lambda row: abs(row[i]))
# check if solution is indeterminate
if abs(chosen_row[i]) < 1e-10:
return None
equations_matrix.remove(chosen_row)
gauss_matrix.append([0]*i + [param/chosen_row[i] for param in chosen_row[i:]])
for row_i, row in enumerate(equations_matrix):
equations_matrix[row_i] = [0]*(i+1) + [param - row[i]*gauss_matrix[-1][i+j+1] for j, param in enumerate(row[i+1:])]
# check if there are no solution
if any(abs(row[-1]) > 1e-10 for row in equations_matrix):
return None
solution = []
for equation in reversed(gauss_matrix):
solution.append(equation[-1] - sum([equation[-(2+i)]*param for i, param in enumerate(solution)]))
return dict(zip(variable_names, reversed(solution)))
|
def decode_eq_side(eq_side):
result = {}
sign, factor, var_name = 1, "", ""
def add_variable():
nonlocal factor, var_name, result
if var_name:
result[var_name] = result.get(var_name, 0) + sign * int(factor) if factor else result.get(var_name, 0) + sign
elif factor:
result[""] = result.get(var_name, 0) + sign * int(factor) if factor else result.get(var_name, 0) + sign
factor, var_name = "", ""
for i, s in enumerate(eq_side.replace(" ", "")):
if s == "+":
add_variable()
sign = 1
elif s == "-":
add_variable()
sign = -1
elif s.isdigit():
factor += s
else:
var_name += s
else:
add_variable()
return result
def decode_equation(equation):
variables, variables2 = [decode_eq_side(side) for side in equation.split("=")]
for var, factor in variables2.items():
variables[var] = variables.get(var, 0) - factor
variables[""] = -1*variables.get("", 0)
return variables
def solve(*equations):
# get equation variables and matrix
equations_variables = [decode_equation(equation) for equation in equations]
variable_names = {var_name for eq_vars in equations_variables for var_name in eq_vars}
variable_names.discard("")
variable_names = list(variable_names)
if len(variable_names) > len(equations_variables):
return None
equations_matrix = [[variables.get(var_name, 0) for var_name in variable_names] + [variables.get("", 0)] for variables in equations_variables]
del equations_variables
# gauss elimination
gauss_matrix = []
for i in range(len(variable_names)):
chosen_row = max(equations_matrix, key=lambda row: abs(row[i]))
# check if solution is indeterminate
if abs(chosen_row[i]) < 1e-10:
return None
equations_matrix.remove(chosen_row)
gauss_matrix.append([0]*i + [param/chosen_row[i] for param in chosen_row[i:]])
for row_i, row in enumerate(equations_matrix):
equations_matrix[row_i] = [0]*(i+1) + [param - row[i]*gauss_matrix[-1][i+j+1] for j, param in enumerate(row[i+1:])]
# check if there are no solution
if any(abs(row[-1]) > 1e-10 for row in equations_matrix):
return None
solution = []
for equation in reversed(gauss_matrix):
solution.append(equation[-1] - sum([equation[-(2+i)]*param for i, param in enumerate(solution)]))
return dict(zip(variable_names, reversed(solution)))
|
train
|
APPS_structured
|
### Tongues
Gandalf's writings have long been available for study, but no one has yet figured out what language they are written in. Recently, due to programming work by a hacker known only by the code name ROT13, it has been discovered that Gandalf used nothing but a simple letter substitution scheme, and further, that it is its own inverse|the same operation scrambles the message as unscrambles it.
This operation is performed by replacing vowels in the sequence `'a' 'i' 'y' 'e' 'o' 'u'` with the vowel three advanced, cyclicly, while preserving case (i.e., lower or upper).
Similarly, consonants are replaced from the sequence `'b' 'k' 'x' 'z' 'n' 'h' 'd' 'c' 'w' 'g' 'p' 'v' 'j' 'q' 't' 's' 'r' 'l' 'm' 'f'` by advancing ten letters.
So for instance the phrase `'One ring to rule them all.'` translates to `'Ita dotf ni dyca nsaw ecc.'`
The fascinating thing about this transformation is that the resulting language yields pronounceable words. For this problem, you will write code to translate Gandalf's manuscripts into plain text.
Your job is to write a function that decodes Gandalf's writings.
### Input
The function will be passed a string for the function to decode. Each string will contain up to 100 characters, representing some text written by Gandalf. All characters will be plain ASCII, in the range space (32) to tilde (126).
### Output
For each string passed to the decode function return its translation.
|
def tongues(code):
map1 = 'aiyeoubkxznhdcwgpvjqtsrlmf'
map2 = 'eouaiypvjqtsrlmfbkxznhdcwg'
return code.translate(str.maketrans(map1+map1.upper(), map2+map2.upper()))
|
def tongues(code):
map1 = 'aiyeoubkxznhdcwgpvjqtsrlmf'
map2 = 'eouaiypvjqtsrlmfbkxznhdcwg'
return code.translate(str.maketrans(map1+map1.upper(), map2+map2.upper()))
|
train
|
APPS_structured
|
```if-not:swift
Create a method that takes an array/list as an input, and outputs the index at which the sole odd number is located.
This method should work with arrays with negative numbers. If there are no odd numbers in the array, then the method should output `-1`.
```
```if:swift
reate a function `oddOne` that takes an `[Int]` as input and outputs the index at which the sole odd number is located.
This method should work with arrays with negative numbers. If there are no odd numbers in the array, then the method should output `nil`.
```
Examples:
```python
odd_one([2,4,6,7,10]) # => 3
odd_one([2,16,98,10,13,78]) # => 4
odd_one([4,-8,98,-12,-7,90,100]) # => 4
odd_one([2,4,6,8]) # => -1
```
|
def odd_one(arr):
arr = list(map(lambda x: x % 2 == 0, arr))
if arr.count(True) == 1:
return arr.index(True)
elif arr.count(False) == 1:
return arr.index(False)
else:
return -1
|
def odd_one(arr):
arr = list(map(lambda x: x % 2 == 0, arr))
if arr.count(True) == 1:
return arr.index(True)
elif arr.count(False) == 1:
return arr.index(False)
else:
return -1
|
train
|
APPS_structured
|
We like parsed SQL or PL/SQL blocks...
You need to write function that return list of literals indices from source block, excluding "in" comments, OR return empty list if no literals found.
input:
some fragment of sql or pl/sql code
output:
list of literals indices [(start, end), ...] OR empty list
Sample:
```
get_textliterals("'this' is sample") -> [(0,6)]
get_textliterals("'this' is sample 'too'") -> [(0, 6), (15, 20)]
```
Text literal: any text between single quotes
Sample:
```
s := 'i am literal'
```
Single-line comment: any text started with "--"
Sample:
```
a := 1;
-- this is single-line comment
```
Multy-line comment: any text between /* */
```
a := 1;
/*
this is long multy-line comment
*/
```
Note:
1) handle single quote inside literal
```
s := 'we can use quote '' in literal'
```
2) multy-line literal
```
s := '
this is literal too
';
```
3) skip literal inside comment
```
s := 'test'; --when comment started - this is not 'literal'
```
4) any unclosed literal should be closed with last symbol of the source fragment
```
s := 'test
```
There is one literal in this code: "'test"
|
def comm_check(l, p_l, comm_started):
if (l == '/' and p_l == '*' and comm_started == 2):
return 0
if (comm_started == 1 and l == '\n'):
return 0
if (l == '-' and p_l == '-'):
return 1
elif (l == '*' and p_l == '/'):
return 2
else:
return comm_started
def get_textliterals(pv_code):
indices = []
open_i = -1
comm_start = 0
for i in range(0, len(pv_code)):
comm_start = comm_check(pv_code[i], pv_code[i-1], comm_start)
if pv_code[i] == '\'' and comm_start == 0:
if open_i == -1:
open_i = i
else:
if (i + 1 < len(pv_code) and i - 1 >= 0):
if (pv_code[i+1] == '\'' or pv_code[i-1] == '\''): continue
indices.append((open_i, i + 1))
open_i = -1
if open_i != -1: indices.append((open_i, len(pv_code)))
return indices
|
def comm_check(l, p_l, comm_started):
if (l == '/' and p_l == '*' and comm_started == 2):
return 0
if (comm_started == 1 and l == '\n'):
return 0
if (l == '-' and p_l == '-'):
return 1
elif (l == '*' and p_l == '/'):
return 2
else:
return comm_started
def get_textliterals(pv_code):
indices = []
open_i = -1
comm_start = 0
for i in range(0, len(pv_code)):
comm_start = comm_check(pv_code[i], pv_code[i-1], comm_start)
if pv_code[i] == '\'' and comm_start == 0:
if open_i == -1:
open_i = i
else:
if (i + 1 < len(pv_code) and i - 1 >= 0):
if (pv_code[i+1] == '\'' or pv_code[i-1] == '\''): continue
indices.append((open_i, i + 1))
open_i = -1
if open_i != -1: indices.append((open_i, len(pv_code)))
return indices
|
train
|
APPS_structured
|
The Petrozavodsk camp takes place in about one month. Jafar wants to participate in the camp, but guess what? His coach is Yalalovichik.
Yalalovichik is a legendary coach, famous in the history of competitive programming. However, he is only willing to send to the camp students who solve really hard problems on Timus. The deadline that Yalalovichik set before has passed and he refuses to send Jafar to the camp.
Jafar decided to make Yalalovichik happy in hopes of changing his decision, so he invented a new sequence of numbers and named them Yalalovichik numbers. Jafar is writing a research paper about their properties and wants to publish it in the Science Eagle yearly journal.
A Yalalovichik number is created in the following way:
- Consider an integer $N$ in decimal notation; let's call it the base of the Yalalovichik number $Y_N$. $N$ may not contain the digit $0$.
- Treat $N$ as a decimal string. Compute all left shifts of this string $N_0, N_1, \ldots, N_{|N|-1}$ ($|N|$ denotes the number of digits of $N$); specifically, $N_k$ denotes the string formed by moving the first $k$ digits of $N$ to the end in the same order.
- Concatenate the strings $N_0, N_1, \ldots, N_{|N|-1}$. The resulting string is the decimal notation of $Y_N$.
For example, if $N = 123$, the left shifts are $123, 231, 312$ and thus $Y_N = 123231312$.
You are given the base $N$. Calculate the value of $Y_N$ modulo $10^9+7$.
-----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 a single decimal integer $N$.
-----Output-----
For each test case, print a single line containing one integer — the value of the Yalalovichik number $Y_N$ modulo $10^9+7$.
-----Constraints-----
- $1 \le T \le 200$
- $|N| \le 10^5$
- $N$ does not contain the digit $0$
- the sum of $|N|$ over all test cases does not exceed $10^6$
-----Example Input-----
1
123
-----Example Output-----
123231312
|
from bisect import bisect_right as br
from bisect import bisect_left as bl
from collections import defaultdict
from itertools import combinations
import functools
import sys
import math
MAX = sys.maxsize
MAXN = 10**6+10
MOD = 10**9+7
def isprime(n):
n = abs(int(n))
if n < 2:
return False
if n == 2:
return True
if not n & 1:
return False
for x in range(3, int(n**0.5) + 1, 2):
if n % x == 0:
return False
return True
def mhd(a,b,x,y):
return abs(a-x)+abs(b-y)
def numIN():
return(map(int,sys.stdin.readline().strip().split()))
def charIN():
return(sys.stdin.readline().strip().split())
t = [0]*1000010
def create(a,n):
global t
for i in range(n,2*n):
t[i] = a[i-n]
for i in range(n-1,0,-1):
t[i] = t[2*i]+t[2*i+1]
def cal(n,k):
res = 1
c = [0]*(k+1)
c[0]=1
for i in range(1,n+1):
for j in range(min(i,k),0,-1):
c[j] = (c[j]+c[j-1])%MOD
return c[k]
for i in range(int(input())):
n = int(input())
a = str(n)
l = len(a)
ans = n
p1 = pow(10,l,MOD)
p2 = pow(10,l-1,MOD)
for j in range(l-1):
n-=(int(a[j])*p2)
n%=MOD
n*=10
n%=MOD
n+=int(a[j])
n%=MOD
ans*=p1
ans%=MOD
ans+=n
ans%=MOD
print(ans)
|
from bisect import bisect_right as br
from bisect import bisect_left as bl
from collections import defaultdict
from itertools import combinations
import functools
import sys
import math
MAX = sys.maxsize
MAXN = 10**6+10
MOD = 10**9+7
def isprime(n):
n = abs(int(n))
if n < 2:
return False
if n == 2:
return True
if not n & 1:
return False
for x in range(3, int(n**0.5) + 1, 2):
if n % x == 0:
return False
return True
def mhd(a,b,x,y):
return abs(a-x)+abs(b-y)
def numIN():
return(map(int,sys.stdin.readline().strip().split()))
def charIN():
return(sys.stdin.readline().strip().split())
t = [0]*1000010
def create(a,n):
global t
for i in range(n,2*n):
t[i] = a[i-n]
for i in range(n-1,0,-1):
t[i] = t[2*i]+t[2*i+1]
def cal(n,k):
res = 1
c = [0]*(k+1)
c[0]=1
for i in range(1,n+1):
for j in range(min(i,k),0,-1):
c[j] = (c[j]+c[j-1])%MOD
return c[k]
for i in range(int(input())):
n = int(input())
a = str(n)
l = len(a)
ans = n
p1 = pow(10,l,MOD)
p2 = pow(10,l-1,MOD)
for j in range(l-1):
n-=(int(a[j])*p2)
n%=MOD
n*=10
n%=MOD
n+=int(a[j])
n%=MOD
ans*=p1
ans%=MOD
ans+=n
ans%=MOD
print(ans)
|
train
|
APPS_structured
|
Given a C++ program, remove comments from it. The program source is an array where source[i] is the i-th line of the source code. This represents the result of splitting the original source code string by the newline character \n.
In C++, there are two types of comments, line comments, and block comments.
The string // denotes a line comment, which represents that it and rest of the characters to the right of it in the same line should be ignored.
The string /* denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of */ should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string /*/ does not yet end the block comment, as the ending would be overlapping the beginning.
The first effective comment takes precedence over others: if the string // occurs in a block comment, it is ignored. Similarly, if the string /* occurs in a line or block comment, it is also ignored.
If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty.
There will be no control characters, single quote, or double quote characters. For example, source = "string s = "/* Not a comment. */";" will not be a test case. (Also, nothing else such as defines or macros will interfere with the comments.)
It is guaranteed that every open block comment will eventually be closed, so /* outside of a line or block comment always starts a new comment.
Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details.
After removing the comments from the source code, return the source code in the same format.
Example 1:
Input:
source = ["/*Test program */", "int main()", "{ ", " // variable declaration ", "int a, b, c;", "/* This is a test", " multiline ", " comment for ", " testing */", "a = b + c;", "}"]
The line by line code is visualized as below:
/*Test program */
int main()
{
// variable declaration
int a, b, c;
/* This is a test
multiline
comment for
testing */
a = b + c;
}
Output: ["int main()","{ "," ","int a, b, c;","a = b + c;","}"]
The line by line code is visualized as below:
int main()
{
int a, b, c;
a = b + c;
}
Explanation:
The string /* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.
Example 2:
Input:
source = ["a/*comment", "line", "more_comment*/b"]
Output: ["ab"]
Explanation: The original source string is "a/*comment\nline\nmore_comment*/b", where we have bolded the newline characters. After deletion, the implicit newline characters are deleted, leaving the string "ab", which when delimited by newline characters becomes ["ab"].
Note:
The length of source is in the range [1, 100].
The length of source[i] is in the range [0, 80].
Every open block comment is eventually closed.
There are no single-quote, double-quote, or control characters in the source code.
|
class Solution:
def removeComments(self, source):
"""
:type source: List[str]
:rtype: List[str]
"""
t = '\n'.join(source)
p = re.compile(r'//.*|/\*(.|\n)*?\*/')
t = p.sub('', t)
return list(filter(None, t.split('\n')))
|
class Solution:
def removeComments(self, source):
"""
:type source: List[str]
:rtype: List[str]
"""
t = '\n'.join(source)
p = re.compile(r'//.*|/\*(.|\n)*?\*/')
t = p.sub('', t)
return list(filter(None, t.split('\n')))
|
train
|
APPS_structured
|
Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element.
We define an array is non-decreasing if array[i] holds for every i (1
Example 1:
Input: [4,2,3]
Output: True
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.
Example 2:
Input: [4,2,1]
Output: False
Explanation: You can't get a non-decreasing array by modify at most one element.
Note:
The n belongs to [1, 10,000].
|
class Solution:
def checkPossibility(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
possibility_flag = False
for i in range(1, len(nums)):
if nums[i] < nums[i-1]:
if possibility_flag:
return False
possibility_flag = True
if (i-2 < 0 or i-2 >= 0 and nums[i-2] < nums[i]) or (i+1 >= len(nums) or i+1 < len(nums) and nums[i+1] > nums[i-1]):
pass
else:
return False
return True
|
class Solution:
def checkPossibility(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
possibility_flag = False
for i in range(1, len(nums)):
if nums[i] < nums[i-1]:
if possibility_flag:
return False
possibility_flag = True
if (i-2 < 0 or i-2 >= 0 and nums[i-2] < nums[i]) or (i+1 >= len(nums) or i+1 < len(nums) and nums[i+1] > nums[i-1]):
pass
else:
return False
return True
|
train
|
APPS_structured
|
Create a function that takes a number as an argument and returns a grade based on that number.
Score | Grade
-----------------------------------------|-----
Anything greater than 1 or less than 0.6 | "F"
0.9 or greater | "A"
0.8 or greater | "B"
0.7 or greater | "C"
0.6 or greater | "D"
Examples:
```
grader(0) should be "F"
grader(1.1) should be "F"
grader(0.9) should be "A"
grader(0.8) should be "B"
grader(0.7) should be "C"
grader(0.6) should be "D"
```
|
grader=lambda s:"FDCBAA"[.5<s<=1and int(10*s)-5]
|
grader=lambda s:"FDCBAA"[.5<s<=1and int(10*s)-5]
|
train
|
APPS_structured
|
In this Kata, you will be given an array of numbers in which two numbers occur once and the rest occur only twice. Your task will be to return the sum of the numbers that occur only once.
For example, `repeats([4,5,7,5,4,8]) = 15` because only the numbers `7` and `8` occur once, and their sum is `15`.
More examples in the test cases.
```if:csharp
Documentation:
Kata.Repeats Method (List<Int32>)
Takes a list where all ints are repeated twice, except two ints, and returns the sum of the ints of a list where those ints only occur once.
Syntax
public
static
int Repeats(
List<int> source
)
Parameters
source
Type: System.Collections.Generic.List<Int32>
The list to process.
Return Value
Type: System.Int32
The sum of the elements of the list where those elements have no duplicates.
```
Good luck!
If you like this Kata, please try:
[Sum of prime-indexed elements](https://www.codewars.com/kata/59f38b033640ce9fc700015b)
[Sum of integer combinations](https://www.codewars.com/kata/59f3178e3640cef6d90000d5)
|
repeats=lambda a:2*sum(set(a))-sum(a)
|
repeats=lambda a:2*sum(set(a))-sum(a)
|
train
|
APPS_structured
|
# Find the gatecrashers on CocoBongo parties
CocoBongo is a club with very nice parties. However, you only can get inside if you know at least one other guest. Unfortunately, some gatecrashers can appear at those parties. The gatecrashers do not know any other party member and should not be at our amazing party!
We will give to you a collection with all party members and a collection with some guests and their invitations. Your mission is to find out those gatecrashers and give us a sorted array of them.
Note that invitations are undirectional relations, so if guest `A` invites `B`, we can consider that `B` also knows `A`. Once the relation `(A, {B})` appears on the invitations collection, the reverse relation `(B, {A})` may or may not appear in the input. You need to take care of that.
## Example
```python
party_members = [0,1,2,3,4]
invitations = [ (0, [1,2]), (2, [3]) ]
gatecrashers = [4]
```
## Explanation
We have `invitations = [ (0, [1,2]), (2, [3]) ]`.
Guest `0` has invited guests `1` and `2`; also, guest `2` has invited guest `3`.
However, noone has invited guest `4`, so he is a gatecrasher.
|
def find_gatecrashers(people, invitations):
ok = set()
for i in invitations:
a, b = i
ok.add(a)
for ii in b:
ok.add(ii)
return sorted(list(set(people) - ok))
|
def find_gatecrashers(people, invitations):
ok = set()
for i in invitations:
a, b = i
ok.add(a)
for ii in b:
ok.add(ii)
return sorted(list(set(people) - ok))
|
train
|
APPS_structured
|
There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the i-th round, you toggle every i bulb. For the n-th round, you only toggle the last bulb. Find how many bulbs are on after n rounds.
Example:
Input: 3
Output: 1
Explanation:
At first, the three bulbs are [off, off, off].
After first round, the three bulbs are [on, on, on].
After second round, the three bulbs are [on, off, on].
After third round, the three bulbs are [on, off, off].
So you should return 1, because there is only one bulb is on.
|
class Solution:
def bulbSwitch(self, n):
"""
:type n: int
:rtype: int
"""
# bulbs = [False] * n;
# for i in range(0,int(n/2)+1):
# j = i+1;
# for j in range(i,n,j):
# bulbs[j] = True if bulbs[j] is False else False;
# print(bulbs,j)
# return bulbs.count(True)
return int(n**(1/2))
|
class Solution:
def bulbSwitch(self, n):
"""
:type n: int
:rtype: int
"""
# bulbs = [False] * n;
# for i in range(0,int(n/2)+1):
# j = i+1;
# for j in range(i,n,j):
# bulbs[j] = True if bulbs[j] is False else False;
# print(bulbs,j)
# return bulbs.count(True)
return int(n**(1/2))
|
train
|
APPS_structured
|
Three candidates take part in a TV show.
In order to decide who will take part in the final game and probably become rich, they have to roll the Wheel of Fortune!
The Wheel of Fortune is divided into 20 sections, each with a number from 5 to 100 (only mulitples of 5).
Each candidate can roll the wheel once or twice and sum up the score of each roll.
The winner one that is closest to 100 (while still being lower or equal to 100).
In case of a tie, the candidate that rolled the wheel first wins.
You receive the information about each candidate as an array of objects: each object should have a `name` and a `scores` array with the candidate roll values.
Your solution should return the name of the winner or `false` if there is no winner (all scored more than 100).
__Example:__
```python
c1 = {"name": "Bob", "scores": [10, 65]}
c2 = {"name": "Bill", "scores": [90, 5]}
c3 = {"name": "Charlie", "scores": [40, 55]}
winner([c1, c2, c3]) #Returns "Bill"
```
Please note that inputs may be invalid: in this case, the function should return false.
Potential errors derived from the specifications are:
- More or less than three candidates take part in the game.
- A candidate did not roll the wheel or rolled it more than twice.
- Scores are not valid.
- Invalid user entry (no name or no score).
|
def winner(cs):
if not (len(cs)==3 and all('name' in c and 'scores' in c and len(c['scores']) in (1,2) and all(5<=s<=100 and not s%5 for s in c['scores']) for c in cs)): return False
cs={c['name']:(sum(c['scores']),-i) for i,c in enumerate(cs)}
try: return max((c for c in cs.items() if c[1][0]<=100),key=lambda c:c[1])[0]
except: return False
|
def winner(cs):
if not (len(cs)==3 and all('name' in c and 'scores' in c and len(c['scores']) in (1,2) and all(5<=s<=100 and not s%5 for s in c['scores']) for c in cs)): return False
cs={c['name']:(sum(c['scores']),-i) for i,c in enumerate(cs)}
try: return max((c for c in cs.items() if c[1][0]<=100),key=lambda c:c[1])[0]
except: return False
|
train
|
APPS_structured
|
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type: + a_{i} — add non-negative integer a_{i} to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer. - a_{i} — delete a single occurrence of non-negative integer a_{i} from the multiset. It's guaranteed, that there is at least one a_{i} in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left.
For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
-----Input-----
The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform.
Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character c_{i} — the type of the corresponding operation. If c_{i} is equal to '+' or '-' then it's followed by a space and an integer a_{i} (0 ≤ a_{i} < 10^18) given without leading zeroes (unless it's 0). If c_{i} equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18.
It's guaranteed that there will be at least one query of type '?'.
It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
-----Output-----
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
-----Examples-----
Input
12
+ 1
+ 241
? 1
+ 361
- 241
? 0101
+ 101
? 101
- 101
? 101
+ 4000
? 0
Output
2
1
2
1
1
Input
4
+ 200
+ 200
- 200
? 0
Output
1
-----Note-----
Consider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000.
|
LVL = 18
from collections import defaultdict
def pattern_repr(x):
rep = [1 if int(x) % 2 else 0 for x in x]
return [0] * (LVL - len(rep)) + rep
class Node:
def __init__(self, key, node_id=0):
self.key = key
self.node_id = node_id
self.left = None
self.right = None
class CodeforcesTask713ASolution:
def __init__(self):
self.result = ''
self.t = 0
self.queries = []
def read_input(self):
self.t = int(input())
for _ in range(self.t):
self.queries.append(input().split(" "))
def process_task(self):
res = []
root = Node(0, 1)
node_id = 2
treesol = False
if treesol:
for query in self.queries:
if query[0] in "+-":
pattern = pattern_repr(query[1])
#print(pattern)
current = root
while pattern:
#print(current.node_id)
if pattern[0]:
# going right
if current.right:
current = current.right
else:
current.right = Node(0, node_id)
current = current.right
node_id += 1
else:
# going left
if current.left:
current = current.left
else:
current.left = Node(0, node_id)
current = current.left
node_id += 1
pattern = pattern[1:]
current.key += 1 if query[0] == "+" else -1
#print(current.key, current.node_id)
else:
pattern = [int(x) for x in "0" * (LVL - len(query[1])) + query[1]]
current = root
#print(pattern)
while pattern:
if pattern[0]:
# going right
if current.right:
current = current.right
else:
current = Node(0)
pattern = []
else:
# going left
if current.left:
current = current.left
else:
current = Node(0)
pattern = []
pattern = pattern[1:]
res.append(current.key)
else:
counts = defaultdict(int)
for query in self.queries:
if query[0] in "+-":
pattern = "0" * (LVL - len(query[1])) + "".join(("1" if int(x) % 2 else "0" for x in query[1]))
counts[pattern] += 1 if query[0] == "+" else -1
else:
pattern = "0" * (LVL - len(query[1])) + query[1]
res.append(counts[pattern])
self.result = "\n".join([str(x) for x in res])
def get_result(self):
return self.result
def __starting_point():
Solution = CodeforcesTask713ASolution()
Solution.read_input()
Solution.process_task()
print(Solution.get_result())
__starting_point()
|
LVL = 18
from collections import defaultdict
def pattern_repr(x):
rep = [1 if int(x) % 2 else 0 for x in x]
return [0] * (LVL - len(rep)) + rep
class Node:
def __init__(self, key, node_id=0):
self.key = key
self.node_id = node_id
self.left = None
self.right = None
class CodeforcesTask713ASolution:
def __init__(self):
self.result = ''
self.t = 0
self.queries = []
def read_input(self):
self.t = int(input())
for _ in range(self.t):
self.queries.append(input().split(" "))
def process_task(self):
res = []
root = Node(0, 1)
node_id = 2
treesol = False
if treesol:
for query in self.queries:
if query[0] in "+-":
pattern = pattern_repr(query[1])
#print(pattern)
current = root
while pattern:
#print(current.node_id)
if pattern[0]:
# going right
if current.right:
current = current.right
else:
current.right = Node(0, node_id)
current = current.right
node_id += 1
else:
# going left
if current.left:
current = current.left
else:
current.left = Node(0, node_id)
current = current.left
node_id += 1
pattern = pattern[1:]
current.key += 1 if query[0] == "+" else -1
#print(current.key, current.node_id)
else:
pattern = [int(x) for x in "0" * (LVL - len(query[1])) + query[1]]
current = root
#print(pattern)
while pattern:
if pattern[0]:
# going right
if current.right:
current = current.right
else:
current = Node(0)
pattern = []
else:
# going left
if current.left:
current = current.left
else:
current = Node(0)
pattern = []
pattern = pattern[1:]
res.append(current.key)
else:
counts = defaultdict(int)
for query in self.queries:
if query[0] in "+-":
pattern = "0" * (LVL - len(query[1])) + "".join(("1" if int(x) % 2 else "0" for x in query[1]))
counts[pattern] += 1 if query[0] == "+" else -1
else:
pattern = "0" * (LVL - len(query[1])) + query[1]
res.append(counts[pattern])
self.result = "\n".join([str(x) for x in res])
def get_result(self):
return self.result
def __starting_point():
Solution = CodeforcesTask713ASolution()
Solution.read_input()
Solution.process_task()
print(Solution.get_result())
__starting_point()
|
train
|
APPS_structured
|
Write a function that takes a piece of text in the form of a string and returns the letter frequency count for the text. This count excludes numbers, spaces and all punctuation marks. Upper and lower case versions of a character are equivalent and the result should all be in lowercase.
The function should return a list of tuples (in Python and Haskell) or arrays (in other languages) sorted by the most frequent letters first. The Rust implementation should return an ordered BTreeMap.
Letters with the same frequency are ordered alphabetically.
For example:
```python
letter_frequency('aaAabb dddDD hhcc')
```
```C++
letter_frequency("aaAabb dddDD hhcc")
```
will return
```python
[('d',5), ('a',4), ('b',2), ('c',2), ('h',2)]
```
```C++
std::vector>{{'d',5}, {'a',4}, {'b',2}, {'c',2}, {'h',2}}
```
Letter frequency analysis is often used to analyse simple substitution cipher texts like those created by the Caesar cipher.
|
import re
from collections import Counter
def letter_frequency(text):
letters = re.findall('[a-z]', text.lower())
freqs = Counter(letters).most_common()
return sorted(freqs, lambda a, b: cmp(b[1], a[1]) or cmp(a[0], b[0]))
|
import re
from collections import Counter
def letter_frequency(text):
letters = re.findall('[a-z]', text.lower())
freqs = Counter(letters).most_common()
return sorted(freqs, lambda a, b: cmp(b[1], a[1]) or cmp(a[0], b[0]))
|
train
|
APPS_structured
|
You're given a string containing a sequence of words separated with whitespaces. Let's say it is a sequence of patterns: a name and a corresponding number - like this:
```"red 1 yellow 2 black 3 white 4"```
You want to turn it into a different **string** of objects you plan to work with later on - like this:
```"[{name : 'red', id : '1'}, {name : 'yellow', id : '2'}, {name : 'black', id : '3'}, {name : 'white', id : '4'}]"```
Doing this manually is a pain. So you've decided to write a short function that would make the computer do the job for you. Keep in mind, the pattern isn't necessarily a word and a number. Consider anything separeted by a whitespace, just don't forget: an array of objects with two elements: name and id.
As a result you'll have a string you may just copy-paste whenever you feel like defining a list of objects - now without the need to put in names, IDs, curly brackets, colon signs, screw up everything, fail searching for a typo and begin anew. This might come in handy with large lists.
|
def words_to_object(s):
s = s.split()
arr = [{'name':i,'id':j} for i,j in zip(s[::2], s[1::2])]
return str(arr).replace("'name':",'name :').replace("'id':",'id :')
|
def words_to_object(s):
s = s.split()
arr = [{'name':i,'id':j} for i,j in zip(s[::2], s[1::2])]
return str(arr).replace("'name':",'name :').replace("'id':",'id :')
|
train
|
APPS_structured
|
Monocarp had a tree which consisted of $n$ vertices and was rooted at vertex $1$. He decided to study BFS (Breadth-first search), so he ran BFS on his tree, starting from the root. BFS can be described by the following pseudocode:a = [] # the order in which vertices were processed
q = Queue()
q.put(1) # place the root at the end of the queue
while not q.empty():
k = q.pop() # retrieve the first vertex from the queue
a.append(k) # append k to the end of the sequence in which vertices were visited
for y in g[k]: # g[k] is the list of all children of vertex k, sorted in ascending order
q.put(y)
Monocarp was fascinated by BFS so much that, in the end, he lost his tree. Fortunately, he still has a sequence of vertices, in which order vertices were visited by the BFS algorithm (the array a from the pseudocode). Monocarp knows that each vertex was visited exactly once (since they were put and taken from the queue exactly once). Also, he knows that all children of each vertex were viewed in ascending order.
Monocarp knows that there are many trees (in the general case) with the same visiting order $a$, so he doesn't hope to restore his tree. Monocarp is okay with any tree that has minimum height.
The height of a tree is the maximum depth of the tree's vertices, and the depth of a vertex is the number of edges in the path from the root to it. For example, the depth of vertex $1$ is $0$, since it's the root, and the depth of all root's children are $1$.
Help Monocarp to find any tree with given visiting order $a$ and minimum height.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases.
The first line of each test case contains a single integer $n$ ($2 \le n \le 2 \cdot 10^5$) — the number of vertices in the tree.
The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$; $a_i \neq a_j$; $a_1 = 1$) — the order in which the vertices were visited by the BFS algorithm.
It's guaranteed that the total sum of $n$ over test cases doesn't exceed $2 \cdot 10^5$.
-----Output-----
For each test case print the minimum possible height of a tree with the given visiting order $a$.
-----Example-----
Input
3
4
1 4 3 2
2
1 2
3
1 2 3
Output
3
1
1
-----Note-----
In the first test case, there is only one tree with the given visiting order: [Image]
In the second test case, there is only one tree with the given visiting order as well: [Image]
In the third test case, an optimal tree with the given visiting order is shown below: [Image]
|
for _ in range(int(input())):
N = int(input())
A = [int(x) for x in input().split()]
last = i = j = 1
ans = nxt = cur = 0
while j < N:
while j < N-1 and A[j+1] > A[j]:
j += 1
if cur == 0:
ans += 1
nxt += j - i + 1
j += 1
i = j
cur += 1
if cur == last:
last = nxt
nxt = cur = 0
print(ans)
|
for _ in range(int(input())):
N = int(input())
A = [int(x) for x in input().split()]
last = i = j = 1
ans = nxt = cur = 0
while j < N:
while j < N-1 and A[j+1] > A[j]:
j += 1
if cur == 0:
ans += 1
nxt += j - i + 1
j += 1
i = j
cur += 1
if cur == last:
last = nxt
nxt = cur = 0
print(ans)
|
train
|
APPS_structured
|
A palindrome is a series of characters that read the same forwards as backwards such as "hannah", "racecar" and "lol".
For this Kata you need to write a function that takes a string of characters and returns the length, as an integer value, of longest alphanumeric palindrome that could be made by combining the characters in any order but using each character only once. The function should not be case sensitive.
For example if passed "Hannah" it should return 6 and if passed "aabbcc_yYx_" it should return 9 because one possible palindrome would be "abcyxycba".
|
from collections import Counter
def longest_palindrome(s):
freq = Counter(c for c in s.lower() if c.isalnum())
even, odd = [], []
for k, v in freq.items():
if v % 2: odd.append(v-1)
else: even.append(v)
return sum(even) + (sum(odd) + 1 if odd else 0)
|
from collections import Counter
def longest_palindrome(s):
freq = Counter(c for c in s.lower() if c.isalnum())
even, odd = [], []
for k, v in freq.items():
if v % 2: odd.append(v-1)
else: even.append(v)
return sum(even) + (sum(odd) + 1 if odd else 0)
|
train
|
APPS_structured
|
Given a string S of digits, such as S = "123456579", we can split it into a Fibonacci-like sequence [123, 456, 579].
Formally, a Fibonacci-like sequence is a list F of non-negative integers such that:
0 <= F[i] <= 2^31 - 1, (that is, each integer fits a 32-bit signed integer type);
F.length >= 3;
and F[i] + F[i+1] = F[i+2] for all 0 <= i < F.length - 2.
Also, note that when splitting the string into pieces, each piece must not have extra leading zeroes, except if the piece is the number 0 itself.
Return any Fibonacci-like sequence split from S, or return [] if it cannot be done.
Example 1:
Input: "123456579"
Output: [123,456,579]
Example 2:
Input: "11235813"
Output: [1,1,2,3,5,8,13]
Example 3:
Input: "112358130"
Output: []
Explanation: The task is impossible.
Example 4:
Input: "0123"
Output: []
Explanation: Leading zeroes are not allowed, so "01", "2", "3" is not valid.
Example 5:
Input: "1101111"
Output: [110, 1, 111]
Explanation: The output [11, 0, 11, 11] would also be accepted.
Note:
1 <= S.length <= 200
S contains only digits.
|
class Solution:
def splitIntoFibonacci(self, S: str):
self.res = []
self.dfs(S, [], 0)
return self.res
def dfs(self, S, temp, count):
if not S and count >= 3:
self.res = temp[:]
return
for step in range(1, min(len(S)+1, 11)):
val = S[:step]
if str(int(val)) == val and 0 <= int(val) <= pow(2, 31) - 1: # 防止前导 0 的出现
if count < 2:
temp.append(int(val))
self.dfs(S[step:], temp, count+1)
temp.pop()
elif temp[count-2] + temp[count-1] == int(val):
temp.append(int(val))
self.dfs(S[step:], temp, count+1)
temp.pop()
|
class Solution:
def splitIntoFibonacci(self, S: str):
self.res = []
self.dfs(S, [], 0)
return self.res
def dfs(self, S, temp, count):
if not S and count >= 3:
self.res = temp[:]
return
for step in range(1, min(len(S)+1, 11)):
val = S[:step]
if str(int(val)) == val and 0 <= int(val) <= pow(2, 31) - 1: # 防止前导 0 的出现
if count < 2:
temp.append(int(val))
self.dfs(S[step:], temp, count+1)
temp.pop()
elif temp[count-2] + temp[count-1] == int(val):
temp.append(int(val))
self.dfs(S[step:], temp, count+1)
temp.pop()
|
train
|
APPS_structured
|
Chef Vivek is good in mathematics and likes solving problems on prime numbers. One day his friend Jatin told him about Victory numbers. Victory number can be defined as a number formed after summing up all the prime numbers till given number n. Now, chef Vivek who is very fond of solving questions on prime numbers got busy in some other tasks. Your task is to help him finding victory number.
-----Input:-----
- First line will contain $T$, number of test cases. Then the test cases follow.
- Each test case contains of a single line of input $N$ till which sum of all prime numbers between 1 to n has to be calculated.
-----Output:-----
For each test case, output in a single line answer to the victory number.
-----Constraints-----
- $1 <= T <= 1000$
- $1 <= N <= 10^6$
-----Sample Input:-----
3
22
13
10
-----Sample Output:-----
77
41
17
|
def isPrime(n) :
if (n <= 1) :
return False
if (n <= 3) :
return True
if (n % 2 == 0 or n % 3 == 0) :
return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
def printPrime(n):
s=0
for i in range(2, n + 1):
if isPrime(i):
s=s+i
print(s)
t=int(input())
for i in range(t):
n = int(input())
printPrime(n)
|
def isPrime(n) :
if (n <= 1) :
return False
if (n <= 3) :
return True
if (n % 2 == 0 or n % 3 == 0) :
return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
def printPrime(n):
s=0
for i in range(2, n + 1):
if isPrime(i):
s=s+i
print(s)
t=int(input())
for i in range(t):
n = int(input())
printPrime(n)
|
train
|
APPS_structured
|
Ever heard about Dijkstra's shallowest path algorithm? Me neither. But I can imagine what it would be.
You're hiking in the wilderness of Northern Canada and you must cross a large river. You have a map of one of the safer places to cross the river showing the depths of the water on a rectangular grid. When crossing the river you can only move from a cell to one of the (up to 8) neighboring cells. You can start anywhere along the left river bank, but you have to stay on the map.
An example of the depths provided on the map is
```
[[2, 3, 2],
[1, 1, 4],
[9, 5, 2],
[1, 4, 4],
[1, 5, 4],
[2, 1, 4],
[5, 1, 2],
[5, 5, 5],
[8, 1, 9]]
```
If you study these numbers, you'll see that there is a path accross the river (from left to right) where the depth never exceeds 2. This path can be described by the list of pairs `[(1, 0), (1, 1), (2, 2)]`. There are also other paths of equal maximum depth, e.g., `[(1, 0), (1, 1), (0, 2)]`. The pairs denote the cells on the path where the first element in each pair is the row and the second element is the column of a cell on the path.
Your job is to write a function `shallowest_path(river)` that takes a list of lists of positive ints (or array of arrays, depending on language) showing the depths of the river as shown in the example above and returns a shallowest path (i.e., the maximum depth is minimal) as a list of coordinate pairs (represented as tuples, Pairs, or arrays, depending on language) as described above. If there are several paths that are equally shallow, the function shall return a shortest such path. All depths are given as positive integers.
|
from heapq import *
from collections import defaultdict
MOVES = ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1))
def shallowest_path(river):
q = [(river[x][0], 0, (x,0)) for x in range(len(river))]
path = {}
stored_steps = defaultdict(lambda : float('inf'))
heapify(q)
while q:
cost, step, (x,y) = heappop(q)
if (x,y) == (x,len(river[0])-1):
end = (x,y)
break
for dx,dy in MOVES:
xx = dx + x
yy = dy + y
if 0<=xx<len(river) and 0<=yy<len(river[0]):
new_step = step + 1
if new_step < stored_steps[(xx,yy)]:
stored_steps[(xx,yy)] = new_step
new_cost = max(cost, river[xx][yy])
path[(xx,yy)] = (x,y)
heappush(q, (new_cost, new_step, (xx,yy)))
coords = [end]
while coords[-1][1] != 0:
coords.append(path[end])
end = path[end]
return coords[::-1]
|
from heapq import *
from collections import defaultdict
MOVES = ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1))
def shallowest_path(river):
q = [(river[x][0], 0, (x,0)) for x in range(len(river))]
path = {}
stored_steps = defaultdict(lambda : float('inf'))
heapify(q)
while q:
cost, step, (x,y) = heappop(q)
if (x,y) == (x,len(river[0])-1):
end = (x,y)
break
for dx,dy in MOVES:
xx = dx + x
yy = dy + y
if 0<=xx<len(river) and 0<=yy<len(river[0]):
new_step = step + 1
if new_step < stored_steps[(xx,yy)]:
stored_steps[(xx,yy)] = new_step
new_cost = max(cost, river[xx][yy])
path[(xx,yy)] = (x,y)
heappush(q, (new_cost, new_step, (xx,yy)))
coords = [end]
while coords[-1][1] != 0:
coords.append(path[end])
end = path[end]
return coords[::-1]
|
train
|
APPS_structured
|
# Task
Mr.Odd is my friend. Some of his common dialogues are “Am I looking odd?” , “It’s looking very odd” etc. Actually “odd” is his favorite word.
In this valentine when he went to meet his girlfriend. But he forgot to take gift. Because of this he told his gf that he did an odd thing. His gf became angry and gave him punishment.
His gf gave him a string str of contain only lowercase letter and told him,
“You have to take 3 index `i,j,k` such that `i ".u..dbo"(no more odd)`
For `str="ooudddbd"`, the result should be `2`.
`"ooudddbd"(cut 1st odd)--> ".ou..dbd"(cut 2nd odd) --> "..u...b."`
# Input/Output
- `[input]` string `str`
a non-empty string that contains only lowercase letters.
`0 < str.length <= 10000`
- `[output]` an integer
the maximum number of "odd".
|
def odd(string):
li,i,string = [],0,list(string)
while i < len(string):
if string[i] == 'o':
temp,pos_to_remove = ['o'],[i]
for j in range(i + 1, len(string)):
if string[j] == 'd' : temp.append('d') ; pos_to_remove.append(j)
if len(temp) == 3 : break
if "".join(temp) == "odd":
li.append(1)
for k in pos_to_remove:
string[k] = "."
i += 1
return len(li)
|
def odd(string):
li,i,string = [],0,list(string)
while i < len(string):
if string[i] == 'o':
temp,pos_to_remove = ['o'],[i]
for j in range(i + 1, len(string)):
if string[j] == 'd' : temp.append('d') ; pos_to_remove.append(j)
if len(temp) == 3 : break
if "".join(temp) == "odd":
li.append(1)
for k in pos_to_remove:
string[k] = "."
i += 1
return len(li)
|
train
|
APPS_structured
|
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are:
2332
110011
54322345
For a given number `num`, write a function to test if it's a numerical palindrome or not and return a boolean (true if it is and false if not).
```if-not:haskell
Return "Not valid" if the input is not an integer or less than `0`.
```
```if:haskell
Return `Nothing` if the input is less than `0` and `Just True` or `Just False` otherwise.
```
Other Kata in this Series:
Numerical Palindrome #1
Numerical Palindrome #1.5
Numerical Palindrome #2
Numerical Palindrome #3
Numerical Palindrome #3.5
Numerical Palindrome #4
Numerical Palindrome #5
|
def palindrome(num):
return str(num)[::-1] == str(num) if isinstance(num, int) and num > 0 else 'Not valid'
|
def palindrome(num):
return str(num)[::-1] == str(num) if isinstance(num, int) and num > 0 else 'Not valid'
|
train
|
APPS_structured
|
Bob is a theoretical coder - he doesn't write code, but comes up with theories, formulas and algorithm ideas. You are his secretary, and he has tasked you with writing the code for his newest project - a method for making the short form of a word. Write a function ```shortForm```(C# ```ShortForm```, Python ```short_form```) that takes a string and returns it converted into short form using the rule: Remove all vowels, except for those that are the first or last letter. Do not count 'y' as a vowel, and ignore case. Also note, the string given will not have any spaces; only one word, and only Roman letters.
Example:
```
shortForm("assault");
short_form("assault")
ShortForm("assault");
// should return "asslt"
```
Also, FYI: I got all the words with no vowels from
https://en.wikipedia.org/wiki/English_words_without_vowels
|
from re import sub
def short_form(s):
return sub(r"(?!^)[aeiouAEIOU](?!$)", '', s)
|
from re import sub
def short_form(s):
return sub(r"(?!^)[aeiouAEIOU](?!$)", '', s)
|
train
|
APPS_structured
|
You are given $n$ strings $a_1, a_2, \ldots, a_n$: all of them have the same length $m$. The strings consist of lowercase English letters.
Find any string $s$ of length $m$ such that each of the given $n$ strings differs from $s$ in at most one position. Formally, for each given string $a_i$, there is no more than one position $j$ such that $a_i[j] \ne s[j]$.
Note that the desired string $s$ may be equal to one of the given strings $a_i$, or it may differ from all the given strings.
For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 100$) — the number of test cases. Then $t$ test cases follow.
Each test case starts with a line containing two positive integers $n$ ($1 \le n \le 10$) and $m$ ($1 \le m \le 10$) — the number of strings and their length.
Then follow $n$ strings $a_i$, one per line. Each of them has length $m$ and consists of lowercase English letters.
-----Output-----
Print $t$ answers to the test cases. Each answer (if it exists) is a string of length $m$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).
-----Example-----
Input
5
2 4
abac
zbab
2 4
aaaa
bbbb
3 3
baa
aaa
aab
2 2
ab
bb
3 1
a
b
c
Output
abab
-1
aaa
ab
z
-----Note-----
The first test case was explained in the statement.
In the second test case, the answer does not exist.
|
def check(a, b):
dif = 0
for i in range(len(a)):
if a[i] != b[i]:
dif += 1
if dif == 2:
return False
return True
for _ in range(int(input())):
n, m = map(int, input().split())
data = []
for i in range(n):
data.append(input())
result = False
for i in range(m):
for j in range(0, 26):
now = data[0][:i] + chr(ord('a') + j) + data[0][i + 1:]
temp = True
for k in data[1:]:
if not check(now, k):
temp = False
if temp:
print(now)
result = True
break
if result:
break
if not result:
print("-1")
|
def check(a, b):
dif = 0
for i in range(len(a)):
if a[i] != b[i]:
dif += 1
if dif == 2:
return False
return True
for _ in range(int(input())):
n, m = map(int, input().split())
data = []
for i in range(n):
data.append(input())
result = False
for i in range(m):
for j in range(0, 26):
now = data[0][:i] + chr(ord('a') + j) + data[0][i + 1:]
temp = True
for k in data[1:]:
if not check(now, k):
temp = False
if temp:
print(now)
result = True
break
if result:
break
if not result:
print("-1")
|
train
|
APPS_structured
|
You are given a grid with dimension $n$ x $m$ and two points with coordinates $X(x1,y1)$ and $Y(x2,y2)$ . Your task is to find the number of ways in which one can go from point $A(0, 0)$ to point $B (n, m)$ using the $shortest$ possible path such that the shortest path neither passes through $X$ nor through $Y$.
Consider the above 4 x 4 grid . Our shortest path can't pass through points (1,3) and (3,3) (marked by yellow dots). One of the possible shortest path is from $A$ to $C$ and then from $C$ to $B$.
-----Input:-----
- First line contains $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, six space separated integers $n, m, x1, y1, x2, y2$.
-----Output:-----
- For each testcase, output in a single line number of ways modulo $998244353$.
-----Constraints-----
- $1 \leq T \leq 10^5$
- $3 \leq n,m \leq 10^5$
- $1 \leq x1, x2 \leq n - 1$
- $1 \leq y1, y2 \leq m - 1$
- $x1 \leq x2$
- $y1 \leq y2$
- $X$ and $Y$ never coincide.
-----Sample Input:-----
1
3 3 1 1 1 2
-----Sample Output:-----
5
|
#dt = {} for i in x: dt[i] = dt.get(i,0)+1
import sys;input = sys.stdin.readline
inp,ip = lambda :int(input()),lambda :[int(w) for w in input().split()]
N = 100001
p = 998244353
factorialNumInverse = [0]*(N+1)
naturalNumInverse = [0]*(N+1)
fact = [0]*(N+1)
def InverseofNumber(p):
naturalNumInverse[0] = naturalNumInverse[1] = 1
for i in range(2,N+1):
naturalNumInverse[i] = (naturalNumInverse[p % i] * (p - (p // i)) % p)
def InverseofFactorial(p):
factorialNumInverse[0] = factorialNumInverse[1] = 1
for i in range(2,N+1):
factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p
def factorial(p):
fact[0] = 1
for i in range(1, N + 1):
fact[i] = (fact[i - 1] * i) % p
def f(num,den1,den2):
# n C r = n!*inverse(r!)*inverse((n-r)!)
#ans = ((fact[N] * factorialNumInverse[R])% p * factorialNumInverse[N-R])% p
ans = ((fact[num]*factorialNumInverse[den1])%p*factorialNumInverse[den2])%p
return ans
InverseofNumber(p)
InverseofFactorial(p)
factorial(p)
for _ in range(inp()):
n,m,x1,y1,x2,y2 = ip()
tot = f(m+n,m,n)
a = f(m-y1+n-x1,m-y1,n-x1)
aa = f(x1+y1,x1,y1)
b = f(m-y2+n-x2,m-y2,n-x2)
bb = f(x2+y2,x2,y2)
c = f(y2-y1+x2-x1,y2-y1,x2-x1)
ans = (tot - a*aa - b*bb + c*aa*b)%p
print(ans)
|
#dt = {} for i in x: dt[i] = dt.get(i,0)+1
import sys;input = sys.stdin.readline
inp,ip = lambda :int(input()),lambda :[int(w) for w in input().split()]
N = 100001
p = 998244353
factorialNumInverse = [0]*(N+1)
naturalNumInverse = [0]*(N+1)
fact = [0]*(N+1)
def InverseofNumber(p):
naturalNumInverse[0] = naturalNumInverse[1] = 1
for i in range(2,N+1):
naturalNumInverse[i] = (naturalNumInverse[p % i] * (p - (p // i)) % p)
def InverseofFactorial(p):
factorialNumInverse[0] = factorialNumInverse[1] = 1
for i in range(2,N+1):
factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p
def factorial(p):
fact[0] = 1
for i in range(1, N + 1):
fact[i] = (fact[i - 1] * i) % p
def f(num,den1,den2):
# n C r = n!*inverse(r!)*inverse((n-r)!)
#ans = ((fact[N] * factorialNumInverse[R])% p * factorialNumInverse[N-R])% p
ans = ((fact[num]*factorialNumInverse[den1])%p*factorialNumInverse[den2])%p
return ans
InverseofNumber(p)
InverseofFactorial(p)
factorial(p)
for _ in range(inp()):
n,m,x1,y1,x2,y2 = ip()
tot = f(m+n,m,n)
a = f(m-y1+n-x1,m-y1,n-x1)
aa = f(x1+y1,x1,y1)
b = f(m-y2+n-x2,m-y2,n-x2)
bb = f(x2+y2,x2,y2)
c = f(y2-y1+x2-x1,y2-y1,x2-x1)
ans = (tot - a*aa - b*bb + c*aa*b)%p
print(ans)
|
train
|
APPS_structured
|
Quite recently it happened to me to join some recruitment interview, where my first task was to write own implementation of built-in split function. It's quite simple, is it not?
However, there were the following conditions:
* the function **cannot** use, in any way, the original `split` or `rsplit` functions,
* the new function **must** be a generator,
* it should behave as the built-in `split`, so it will be tested that way -- think of `split()` and `split('')`
*This Kata will control if the new function is a generator and if it's not using the built-in split method, so you may try to hack it, but let me know if with success, or if something would go wrong!*
Enjoy!
|
import re
def my_very_own_split(string, delimiter=None):
if delimiter == '':
raise ValueError('empty separator')
delim_re = re.escape(delimiter) if delimiter is not None else r'\s+'
for s in getattr(re, 'split')(delim_re, string):
yield s
|
import re
def my_very_own_split(string, delimiter=None):
if delimiter == '':
raise ValueError('empty separator')
delim_re = re.escape(delimiter) if delimiter is not None else r'\s+'
for s in getattr(re, 'split')(delim_re, string):
yield s
|
train
|
APPS_structured
|
We have the following recursive function:
The 15-th term; ```f(14)``` is the first term in having more that 100 digits.
In fact,
```
f(14) = 2596253046576879973769082409566059879570061514363339324718953988724415850732046186170181072783243503881471037546575506836249417271830960970629933033088
It has 151 digits.
```
Make the function ```something_acci()```, that receives ```num_dig``` (number of digits of the value) as unique argument.
```something_acci()``` will output a tuple/array with the ordinal number in the sequence for the least value in having equal or more than the given number of digits.
Let's see some cases:
```python
something_acci(20) == (12, 25)
# f(11) = 1422313222839141753028416
something_acci(100) == (15, 151)
```
The number of digits given will be always more than 5. ```num_dig > 5```.
Happy coding!!!
And the name for this kata? You have three words of the same meaning in Asian Languages.
|
from functools import lru_cache
@lru_cache()
def f(n):
return (1, 1, 2, 2, 3, 3)[n] if n < 6 else (f(n-1) * f(n-2) * f(n-3)) - (f(n-4) * f(n-5) * f(n-6))
def something_acci(num_digits):
n, l = 8, 4
while l < num_digits:
n += 1
l = len(str(f(n)))
return n + 1, l
|
from functools import lru_cache
@lru_cache()
def f(n):
return (1, 1, 2, 2, 3, 3)[n] if n < 6 else (f(n-1) * f(n-2) * f(n-3)) - (f(n-4) * f(n-5) * f(n-6))
def something_acci(num_digits):
n, l = 8, 4
while l < num_digits:
n += 1
l = len(str(f(n)))
return n + 1, l
|
train
|
APPS_structured
|
You have to create a function named reverseIt.
Write your function so that in the case a string or a number is passed in as the data , you will return the data in reverse order. If the data is any other type, return it as it is.
Examples of inputs and subsequent outputs:
```
"Hello" -> "olleH"
"314159" -> "951413"
[1,2,3] -> [1,2,3]
```
|
def reverse_it(data):
return (type(data)(str(data)[::-1])) if isinstance(data, (str, int, float)) else data
|
def reverse_it(data):
return (type(data)(str(data)[::-1])) if isinstance(data, (str, int, float)) else data
|
train
|
APPS_structured
|
Who's interested in football?
Rayne Wooney has been one of the top players for his football club for the last few years. But unfortunately, he got injured during a game a few months back and has been out of play ever since.
He's got proper treatment and is eager to go out and play for his team again. Before doing that, he has to prove to his fitness to the coach and manager of the team. Rayne has been playing practice matches for the past few days. He's played N practice matches in all.
He wants to convince the coach and the manager that he's improved over time and that his injury no longer affects his game. To increase his chances of getting back into the team, he's decided to show them stats of any 2 of his practice games. The coach and manager will look into the goals scored in both the games and see how much he's improved. If the number of goals scored in the 2nd game(the game which took place later) is greater than that in 1st, then he has a chance of getting in. Tell Rayne what is the maximum improvement in terms of goal difference that he can show to maximize his chances of getting into the team. If he hasn't improved over time, he's not fit to play. Scoring equal number of goals in 2 matches will not be considered an improvement. Also, he will be declared unfit if he doesn't have enough matches to show an improvement.
-----Input:-----
The first line of the input contains a single integer T, the number of test cases.
Each test case begins with a single integer N, the number of practice matches Rayne has played.
The next line contains N integers. The ith integer, gi, on this line represents the number of goals Rayne scored in his ith practice match. The matches are given in chronological order i.e. j > i means match number j took place after match number i.
-----Output:-----
For each test case output a single line containing the maximum goal difference that Rayne can show to his coach and manager. If he's not fit yet, print "UNFIT".
-----Constraints:-----
1<=T<=10
1<=N<=100000
0<=gi<=1000000 (Well, Rayne's a legend! You can expect him to score so many goals!)
-----Example:-----Input:
3
6
3 7 1 4 2 4
5
5 4 3 2 1
5
4 3 2 2 3
Output:
4
UNFIT
1
Explanation:
In the first test case, Rayne can choose the first and second game. Thus he gets a difference of 7-3=4 goals. Any other pair would give him a lower improvement.
In the second test case, Rayne has not been improving in any match. Thus he's declared UNFIT.
Note: Large input data. Use faster I/O methods. Prefer scanf,printf over cin/cout.
|
#!/usr/bin/env python
def process(t, N, G):
Improvment = 0
CurrentMin = G[0]
CurrentMax = G[0]
for n in range(1, N):
if CurrentMax < G[n]:
CurrentMax = G[n]
Improvment = max(Improvment, CurrentMax-CurrentMin)
elif CurrentMin > G[n]:
CurrentMin = G[n]
CurrentMax = G[n]
return Improvment or 'UNFIT'
def main():
T = int(input())
for t in range(T):
N = int(input())
G = list(map(int, input().strip().split()[:N]))
print(process(t, N, G))
main()
|
#!/usr/bin/env python
def process(t, N, G):
Improvment = 0
CurrentMin = G[0]
CurrentMax = G[0]
for n in range(1, N):
if CurrentMax < G[n]:
CurrentMax = G[n]
Improvment = max(Improvment, CurrentMax-CurrentMin)
elif CurrentMin > G[n]:
CurrentMin = G[n]
CurrentMax = G[n]
return Improvment or 'UNFIT'
def main():
T = int(input())
for t in range(T):
N = int(input())
G = list(map(int, input().strip().split()[:N]))
print(process(t, N, G))
main()
|
train
|
APPS_structured
|
# Background:
You're working in a number zoo, and it seems that one of the numbers has gone missing!
Zoo workers have no idea what number is missing, and are too incompetent to figure it out, so they're hiring you to do it for them.
In case the zoo loses another number, they want your program to work regardless of how many numbers there are in total.
___
## Task:
Write a function that takes a shuffled list of unique numbers from `1` to `n` with one element missing (which can be any number including `n`). Return this missing number.
**Note**: huge lists will be tested.
## Examples:
```
[1, 3, 4] => 2
[1, 2, 3] => 4
[4, 2, 3] => 1
```
|
def find_missing_number(nums):
return sum(range(1,len(nums)+2))-sum(nums)
|
def find_missing_number(nums):
return sum(range(1,len(nums)+2))-sum(nums)
|
train
|
APPS_structured
|
Given an integer array, return the k-th smallest distance among all the pairs. The distance of a pair (A, B) is defined as the absolute difference between A and B.
Example 1:
Input:
nums = [1,3,1]
k = 1
Output: 0
Explanation:
Here are all the pairs:
(1,3) -> 2
(1,1) -> 0
(3,1) -> 2
Then the 1st smallest distance pair is (1,1), and its distance is 0.
Note:
2 .
0 .
1 .
|
class Solution:
def smallestDistancePair(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
nums.sort()
l, r = 0, nums[-1] - nums[0]
while l < r:
m = l + (r - l) // 2
count = 0
left = 0
for right in range(len(nums)):
while nums[right] - nums[left] > m: left += 1
count += (right - left)
if count < k :
l = m+1
else:
r = m
return l
|
class Solution:
def smallestDistancePair(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
nums.sort()
l, r = 0, nums[-1] - nums[0]
while l < r:
m = l + (r - l) // 2
count = 0
left = 0
for right in range(len(nums)):
while nums[right] - nums[left] > m: left += 1
count += (right - left)
if count < k :
l = m+1
else:
r = m
return l
|
train
|
APPS_structured
|
The chef is having one array of N natural numbers(numbers may be repeated). i.e. All natural numbers must be less than N. Chef wants to rearrange the array and try to place a natural number on its index of the array, i.e array[i]=i. If multiple natural numbers are found for given index place one natural number to its index and ignore others.i.e. arr[i]=i and multiple i found in array ignore all remaining i's If any index in the array is empty place 0 at that place. i.e. if for arr[i], i is not present do arr[i]=0.
-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains two lines of input.
- First-line has $N$ denoting the size of an array.
- Second-line has $N$ space-separated natural numbers.
-----Output:-----
For each test case, output in a single line with the new rearranged array.
-----Constraints-----
- $1 \leq T \leq 10^3$
- $2 \leq N \leq 10^3$
- $arr[i] \leq N-1$
-----Sample Input:-----
2
2
1 1
4
1 1 2 1
-----Sample Output:-----
0 1
0 1 2 0
-----EXPLANATION:-----
For 1) $1$ occurs twice in the array hence print 0 at 0th index and 1 at 1st index
For 2) $1$ occurs thrice and 2 once in the array hence print 0 at 0th index and 1 at 1st index, 2 at 2nd index and 0 at 3rd index.
|
# cook your dish here
t=int(input())
for _ in range(t):
n=int(input())
l=list(map(int,input().split()))
l1=[0]*n
for i in range(n):
if(i in l):
l1[i]=i
else:
l1[i]=0
print(*l1)
|
# cook your dish here
t=int(input())
for _ in range(t):
n=int(input())
l=list(map(int,input().split()))
l1=[0]*n
for i in range(n):
if(i in l):
l1[i]=i
else:
l1[i]=0
print(*l1)
|
train
|
APPS_structured
|
Make the 2D list by the sequential integers started by the ```head``` number.
See the example test cases for the expected output.
```
Note:
-10**20 < the head number <10**20
1 <= the number of rows <= 1000
0 <= the number of columms <= 1000
```
|
import numpy as np
def make_2d_list(head,row,col):
return np.arange(head, head + row * col).reshape(row, col).tolist()
|
import numpy as np
def make_2d_list(head,row,col):
return np.arange(head, head + row * col).reshape(row, col).tolist()
|
train
|
APPS_structured
|
Mutual Recursion allows us to take the fun of regular recursion (where a function calls itself until a terminating condition) and apply it to multiple functions calling each other!
Let's use the Hofstadter Female and Male sequences to demonstrate this technique. You'll want to create two functions `F` and `M` such that the following equations are true:
```
F(0) = 1
M(0) = 0
F(n) = n - M(F(n - 1))
M(n) = n - F(M(n - 1))
```
Don't worry about negative numbers, `n` will always be greater than or equal to zero.
~~~if:php,csharp
You *do* have to worry about performance though, mutual recursion uses up a lot of stack space (and is highly inefficient) so you may have to find a way to make your solution consume less stack space (and time). Good luck :)
~~~
Hofstadter Wikipedia Reference http://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Female_and_Male_sequences
|
def m(n):
if n <= 0:
return 0
else:
return (n - f(m(n-1)))
def f(n):
if n <= 0:
return 1
else:
return (n - m(f(n-1)))
|
def m(n):
if n <= 0:
return 0
else:
return (n - f(m(n-1)))
def f(n):
if n <= 0:
return 1
else:
return (n - m(f(n-1)))
|
train
|
APPS_structured
|
# One is the loneliest number
## Task
The range of vision of a digit is its own value. `1` can see one digit to the left and one digit to the right,` 2` can see two digits, and so on.
Thus, the loneliness of a digit `N` is the sum of the digits which it can see.
Given a non-negative integer, your funtion must determine if there's at least one digit `1` in this integer such that its loneliness value is minimal.
## Example
```
number = 34315
```
digit | can see on the left | can see on the right | loneliness
--- | --- | --- | ---
3 | - | 431 | 4 + 3 + 1 = 8
4 | 3 | 315 | 3 + 3 + 1 + 5 = 12
3 | 34 | 15 | 3 + 4 + 1 + 5 = 13
1 | 3 | 5 | 3 + 5 = 8
5 | 3431 | - | 3 + 4 + 3 + 1 = 11
Is there a `1` for which the loneliness is minimal? Yes.
|
def loneliest(n):
a = list(map(int, str(n)))
b = [(sum(a[max(0, i - x):i+x+1]) - x, x) for i, x in enumerate(a)]
return (min(b)[0], 1) in b
|
def loneliest(n):
a = list(map(int, str(n)))
b = [(sum(a[max(0, i - x):i+x+1]) - x, x) for i, x in enumerate(a)]
return (min(b)[0], 1) in b
|
train
|
APPS_structured
|
Jett is tired after destroying the town and she wants to have a rest. She likes high places, that's why for having a rest she wants to get high and she decided to craft staircases.
A staircase is a squared figure that consists of square cells. Each staircase consists of an arbitrary number of stairs. If a staircase has $n$ stairs, then it is made of $n$ columns, the first column is $1$ cell high, the second column is $2$ cells high, $\ldots$, the $n$-th column if $n$ cells high. The lowest cells of all stairs must be in the same row.
A staircase with $n$ stairs is called nice, if it may be covered by $n$ disjoint squares made of cells. All squares should fully consist of cells of a staircase. This is how a nice covered staircase with $7$ stairs looks like: [Image]
Find out the maximal number of different nice staircases, that can be built, using no more than $x$ cells, in total. No cell can be used more than once.
-----Input-----
The first line contains a single integer $t$ $(1 \le t \le 1000)$ — the number of test cases.
The description of each test case contains a single integer $x$ $(1 \le x \le 10^{18})$ — the number of cells for building staircases.
-----Output-----
For each test case output a single integer — the number of different nice staircases, that can be built, using not more than $x$ cells, in total.
-----Example-----
Input
4
1
8
6
1000000000000000000
Output
1
2
1
30
-----Note-----
In the first test case, it is possible to build only one staircase, that consists of $1$ stair. It's nice. That's why the answer is $1$.
In the second test case, it is possible to build two different nice staircases: one consists of $1$ stair, and another consists of $3$ stairs. This will cost $7$ cells. In this case, there is one cell left, but it is not possible to use it for building any nice staircases, that have not been built yet. That's why the answer is $2$.
In the third test case, it is possible to build only one of two nice staircases: with $1$ stair or with $3$ stairs. In the first case, there will be $5$ cells left, that may be used only to build a staircase with $2$ stairs. This staircase is not nice, and Jett only builds nice staircases. That's why in this case the answer is $1$. If Jett builds a staircase with $3$ stairs, then there are no more cells left, so the answer is $1$ again.
|
l=[]
i=1
while(i<10**18+5):
l.append((i*(i+1))//2)
i=i*2+1
t=int(input())
for you in range(t):
n=int(input())
count=0
sum=0
for i in range(len(l)):
sum+=l[i]
if(sum>n):
break
print(i)
|
l=[]
i=1
while(i<10**18+5):
l.append((i*(i+1))//2)
i=i*2+1
t=int(input())
for you in range(t):
n=int(input())
count=0
sum=0
for i in range(len(l)):
sum+=l[i]
if(sum>n):
break
print(i)
|
train
|
APPS_structured
|
Chef loves saving money and he trusts none other bank than State Bank of Chefland. Unsurprisingly, the employees like giving a hard time to their customers. But instead of asking them to stand them in long queues, they have weird way of accepting money.
Chef did his homework and found that the bank only accepts the money in coins such that the sum of the denomination with any previously deposited coin OR itself can't be obtained by summing any two coins OR double of any coin deposited before. Considering it all, he decided to start with $1$ Chefland rupee and he would keep choosing smallest possible denominations upto $N$ coins. Since chef is busy with his cooking, can you find out the $N$ denomination of coins chef would have to take to the bank? Also find the total sum of money of those $N$ coins.
-----Input:-----
- First line has a single integer $T$ i.e. number of testcases.
- $T$ lines followed, would have a single integer $N$ i.e. the number of coins the chef is taking.
-----Output:-----
- Output for $i$-th testcase ($1 ≤ i ≤ T$) would have 2 lines.
- First line would contain $N$ integers i.e. the denomination of coins chef would deposit to the bank.
- Second line would contain a single integer i.e. the sum of all the coins chef would deposit.
-----Constraints:-----
- $1 ≤ T ≤ 700$
- $1 ≤ N ≤ 700$
-----Subtasks:-----
- $20$ points: $1 ≤ T, N ≤ 80$
- $70$ points: $1 ≤ T, N ≤ 500$
- $10$ points: $1 ≤ T, N ≤ 700$
-----Sample Input:-----
4
1
2
3
4
-----Sample Output:-----
1
1
1 2
3
1 2 4
7
1 2 4 8
15
-----Explanation:-----
For testcase 1: First coin is stated to be 1, hence for $N$ = 1, 1 is the answer.
For testcase 2: Since chef chooses the lowest possible denomination for each $i$-th coin upto $N$ coins, second coin would be 2. Only sum possible with N = 1 would be 1+1 = 2. For N = 2, $\{1+2, 2+2\}$ $\neq$ $2$.
For testcase 3: With first two coins being 1 and 2, next coin couldn't be 3 because 3+1 = 2+2, but $\{4+1, 4+2, 4+4\}$ $\neq$ $\{1+1, 1+2, 2+2\}$
|
from array import *
def main():
t=int(input())
if 1<=t<=700:
s=array("i",[])
ql=array("i",[])
for x in range(t):
ql.append(int(input()))
n=max(ql)
if 1<=n<=700:
l=array("i",[1])
i=2
a=c=set()
b={2}
while len(l)<n:
if i-1 in l:
c=c.union(a.union(b))
d=set()
for j in l:
d=d.union({i+j})
if len(c.intersection({2*i}.union(d)))==0:
b=d
a={2*i}
l.append(i)
i=i+1
prev=0
for j in l:
s.append(prev+j)
prev=prev+j
for j in ql:
for i in range(j):
print(l[i],end=" ")
print()
print(s[j-1])
main()
|
from array import *
def main():
t=int(input())
if 1<=t<=700:
s=array("i",[])
ql=array("i",[])
for x in range(t):
ql.append(int(input()))
n=max(ql)
if 1<=n<=700:
l=array("i",[1])
i=2
a=c=set()
b={2}
while len(l)<n:
if i-1 in l:
c=c.union(a.union(b))
d=set()
for j in l:
d=d.union({i+j})
if len(c.intersection({2*i}.union(d)))==0:
b=d
a={2*i}
l.append(i)
i=i+1
prev=0
for j in l:
s.append(prev+j)
prev=prev+j
for j in ql:
for i in range(j):
print(l[i],end=" ")
print()
print(s[j-1])
main()
|
train
|
APPS_structured
|
There are $X$ people participating in a quiz competition and their IDs have been numbered from $1$ to $X$ (both inclusive). Beth needs to form a team among these $X$ participants. She has been given an integer $Y$. She can choose participants whose ID numbers are divisible by $Y$.
Now that the team is formed, Beth wants to know the strength of her team. The strength of a team is the sum of all the last digits of the team members’ ID numbers.
Can you help Beth in finding the strength of her team?
-----Input:-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. $T$ lines follow
- The first line of each test case contains $X$ and $Y$.
-----Output:-----
- For each test case print the strength of Beth's team
-----Constraints-----
- $1 \leq T \leq 1000$
- $1 \leq X,Y \leq 10^{20}$
-----Sample Input:-----
2
10 3
15 5
-----Sample Output:-----
18
10
-----EXPLANATION:-----
- Example case 1: ID numbers divisible by 3 are 3,6,9 and the sum of the last digits are 3+6+9=18
|
t=int(input())
for i in range(t):
x,y=list(map(int,input().split()))
sum=0
for j in range(int(x/y)+1):
sum=sum+(j*y)%10
print(sum)
|
t=int(input())
for i in range(t):
x,y=list(map(int,input().split()))
sum=0
for j in range(int(x/y)+1):
sum=sum+(j*y)%10
print(sum)
|
train
|
APPS_structured
|
There is a room with n bulbs, numbered from 1 to n, arranged in a row from left to right. Initially, all the bulbs are turned off.
At moment k (for k from 0 to n - 1), we turn on the light[k] bulb. A bulb change color to blue only if it is on and all the previous bulbs (to the left) are turned on too.
Return the number of moments in which all turned on bulbs are blue.
Example 1:
Input: light = [2,1,3,5,4]
Output: 3
Explanation: All bulbs turned on, are blue at the moment 1, 2 and 4.
Example 2:
Input: light = [3,2,4,1,5]
Output: 2
Explanation: All bulbs turned on, are blue at the moment 3, and 4 (index-0).
Example 3:
Input: light = [4,1,2,3]
Output: 1
Explanation: All bulbs turned on, are blue at the moment 3 (index-0).
Bulb 4th changes to blue at the moment 3.
Example 4:
Input: light = [2,1,4,3,6,5]
Output: 3
Example 5:
Input: light = [1,2,3,4,5,6]
Output: 6
Constraints:
n == light.length
1 <= n <= 5 * 10^4
light is a permutation of [1, 2, ..., n]
|
class Solution:
def numTimesAllBlue(self, light: List[int]) -> int:
len_lis = len(light)
lis = [[] for x in range(len_lis+2)]
tot = 0
for i in range(len_lis):
if(light[i] > 1 and lis[light[i]-1] and light[i] < len_lis and lis[light[i]+1]):
end = lis[light[i]+1][1]
start = lis[light[i]-1][0]
elif(light[i] > 1 and lis[light[i]-1]):
start = lis[light[i]-1][0]
end = light[i]
elif(light[i] < len_lis and lis[light[i]+1]):
start = light[i]
end = lis[light[i]+1][1]
else:
start = light[i]
end = light[i]
if(end-start == i and start == 1):
tot += 1
lis[end] = [start, end]
lis[start] = [start, end]
#print(lis)
return tot
|
class Solution:
def numTimesAllBlue(self, light: List[int]) -> int:
len_lis = len(light)
lis = [[] for x in range(len_lis+2)]
tot = 0
for i in range(len_lis):
if(light[i] > 1 and lis[light[i]-1] and light[i] < len_lis and lis[light[i]+1]):
end = lis[light[i]+1][1]
start = lis[light[i]-1][0]
elif(light[i] > 1 and lis[light[i]-1]):
start = lis[light[i]-1][0]
end = light[i]
elif(light[i] < len_lis and lis[light[i]+1]):
start = light[i]
end = lis[light[i]+1][1]
else:
start = light[i]
end = light[i]
if(end-start == i and start == 1):
tot += 1
lis[end] = [start, end]
lis[start] = [start, end]
#print(lis)
return tot
|
train
|
APPS_structured
|
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
|
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x==0:
return 0
if x>0:
sign=1
else:
sign=-1
x=0-x
bits=[]
for i in range (10):
bits.append(x%10)
x=x//10
print (bits)
left_i=0
right_i=9
for i in range (10):
if bits[i]==0:
left_i=left_i+1
else:
break
for i in range (9,-1,-1):
if bits[i]==0:
right_i=right_i-1
else:
break
print (left_i,right_i)
factor=1
result=0
for i in range (right_i,left_i-1,-1):
result=result+factor*bits[i]
factor=factor*10
result=result*sign
if result>2147483647 or result<-2147483648:
return 0
else:
return result
|
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x==0:
return 0
if x>0:
sign=1
else:
sign=-1
x=0-x
bits=[]
for i in range (10):
bits.append(x%10)
x=x//10
print (bits)
left_i=0
right_i=9
for i in range (10):
if bits[i]==0:
left_i=left_i+1
else:
break
for i in range (9,-1,-1):
if bits[i]==0:
right_i=right_i-1
else:
break
print (left_i,right_i)
factor=1
result=0
for i in range (right_i,left_i-1,-1):
result=result+factor*bits[i]
factor=factor*10
result=result*sign
if result>2147483647 or result<-2147483648:
return 0
else:
return result
|
train
|
APPS_structured
|
-----Problem-----
Nikki's latest work is writing a story of letters. However, she finds writing story so boring that, after working for three hours, she realized that all she has written are M long words consisting entirely of letters A and B. Having accepted that she will never finish the story in time, Nikki has decided to at least have some fun with it by counting bubbly words.
Now Nikki is connecting pairs of identical letters (A with A, B with B) by drawing lines above the word. A given word is bubbly if each letter can be connected to exactly one other letter in such a way that no two lines intersect. So here is your task. Help Nikki count how many words are bubbly.
-----Input-----
-
The first line of input contains the positive integer M, the number of words written down by Nikki.
-
Each of the following M lines contains a single word consisting of letters A and B, with length
between 2 and 10^5, inclusive. The sum of lengths of all words doesn't exceed 10^6.
-----Output-----
The first and only line of output must contain the number of bubbly words.
-----Constraints-----
-
1 ≤ M ≤ 100
-----Sample Input-----
3
ABAB
AABB
ABBA
-----Sample Output-----
2
-----Explanation-----
-
ABAB - It is not bubbly as A(indexed 1) will connect to A(indexed 3) by a line and when we try to connect B(indexed 2) with B(indexed 4) by a line then it will intersect with the line b/w A and A.
-
AABB - It is bubbly as line b/w A and A will not intersect with the line b/w B and B.
-
ABBA -It is also bubbly as lines will not intersect. We can draw line b/w A and A above the line b/w B and B.
p { text-align:justify }
|
def check(s):
arr=[s[0]]
l=len(s)
f1=0
for i in range(1,l):
if arr==[]: arr.append(s[i])
elif arr[-1]!=s[i]:arr.append(s[i])
else: del arr[-1]
if arr==[]: return True
else: return False
count = 0
for t in range(eval(input())):
s=input().strip()
if check(s): count+=1
print(count)
|
def check(s):
arr=[s[0]]
l=len(s)
f1=0
for i in range(1,l):
if arr==[]: arr.append(s[i])
elif arr[-1]!=s[i]:arr.append(s[i])
else: del arr[-1]
if arr==[]: return True
else: return False
count = 0
for t in range(eval(input())):
s=input().strip()
if check(s): count+=1
print(count)
|
train
|
APPS_structured
|
We need a function ```count_sel()``` that receives an array or list of integers (positive and negative) and may give us the following information in the order and structure presented bellow:
```[(1), (2), (3), [[(4)], 5]]```
(1) - Total amount of received integers.
(2) - Total amount of different values the array has.
(3) - Total amount of values that occur only once.
(4) and (5) both in a list
(4) - It is (or they are) the element(s) that has (or have) the maximum occurrence. If there are more than one, the elements should be sorted (by their value obviously)
(5) - Maximum occurrence of the integer(s)
Let's see some cases
```python
____ count_sel([-3, -2, -1, 3, 4, -5, -5, 5, -1, -5]) ----> [10, 7, 5, [[-5], 3]]
(1) - The list has ten elements (10 numbers)
(2) - We have seven different values: -5, -3, -2, -1, 3, 4, 5 (7 values)
(3) - The numbers that occur only once: -3, -2, 3, 4, 5 (5 values)
(4) and (5) - The number -5 occurs three times (3 occurrences)
____ count_sel([4, 4, 2, -3, 1, 4, 3, 2, 0, -5, 2, -2, -2, -5]) ----> [14, 8, 4, [[2, 4], 3]]
```
Enjoy it and happy coding!!
|
from collections import defaultdict, Counter
def count_sel(nums):
cnt = Counter(nums)
d = defaultdict(list)
total = 0
unique = 0
for k, v in cnt.items():
d[v].append(k)
total += v
unique += 1
maximum = max(d)
return [total, unique, len(d[1]), [sorted(d[maximum]), maximum]]
|
from collections import defaultdict, Counter
def count_sel(nums):
cnt = Counter(nums)
d = defaultdict(list)
total = 0
unique = 0
for k, v in cnt.items():
d[v].append(k)
total += v
unique += 1
maximum = max(d)
return [total, unique, len(d[1]), [sorted(d[maximum]), maximum]]
|
train
|
APPS_structured
|
This problem takes its name by arguably the most important event in the life of the ancient historian Josephus: according to his tale, he and his 40 soldiers were trapped in a cave by the Romans during a siege.
Refusing to surrender to the enemy, they instead opted for mass suicide, with a twist: **they formed a circle and proceeded to kill one man every three, until one last man was left (and that it was supposed to kill himself to end the act)**.
Well, Josephus and another man were the last two and, as we now know every detail of the story, you may have correctly guessed that they didn't exactly follow through the original idea.
You are now to create a function that returns a Josephus permutation, taking as parameters the initial *array/list of items* to be permuted as if they were in a circle and counted out every *k* places until none remained.
**Tips and notes:** it helps to start counting from 1 up to n, instead of the usual range 0..n-1; k will always be >=1.
For example, with n=7 and k=3 `josephus(7,3)` should act this way.
```
[1,2,3,4,5,6,7] - initial sequence
[1,2,4,5,6,7] => 3 is counted out and goes into the result [3]
[1,2,4,5,7] => 6 is counted out and goes into the result [3,6]
[1,4,5,7] => 2 is counted out and goes into the result [3,6,2]
[1,4,5] => 7 is counted out and goes into the result [3,6,2,7]
[1,4] => 5 is counted out and goes into the result [3,6,2,7,5]
[4] => 1 is counted out and goes into the result [3,6,2,7,5,1]
[] => 4 is counted out and goes into the result [3,6,2,7,5,1,4]
```
So our final result is:
```
josephus([1,2,3,4,5,6,7],3)==[3,6,2,7,5,1,4]
```
For more info, browse the Josephus Permutation page on wikipedia; related kata: Josephus Survivor.
Also, [live game demo](https://iguacel.github.io/josephus/) by [OmniZoetrope](https://www.codewars.com/users/OmniZoetrope).
|
from collections import deque
def josephus(items,k):
q = deque(items)
return [[q.rotate(1-k), q.popleft()][1] for _ in items]
|
from collections import deque
def josephus(items,k):
q = deque(items)
return [[q.rotate(1-k), q.popleft()][1] for _ in items]
|
train
|
APPS_structured
|
Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.
There are $k$ boxes numbered from $1$ to $k$. The $i$-th box contains $n_i$ integer numbers. The integers can be negative. All of the integers are distinct.
Ujan is lazy, so he will do the following reordering of the numbers exactly once. He will pick a single integer from each of the boxes, $k$ integers in total. Then he will insert the chosen numbers — one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box.
Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be?
-----Input-----
The first line contains a single integer $k$ ($1 \leq k \leq 15$), the number of boxes.
The $i$-th of the next $k$ lines first contains a single integer $n_i$ ($1 \leq n_i \leq 5\,000$), the number of integers in box $i$. Then the same line contains $n_i$ integers $a_{i,1}, \ldots, a_{i,n_i}$ ($|a_{i,j}| \leq 10^9$), the integers in the $i$-th box.
It is guaranteed that all $a_{i,j}$ are distinct.
-----Output-----
If Ujan cannot achieve his goal, output "No" in a single line. Otherwise in the first line output "Yes", and then output $k$ lines. The $i$-th of these lines should contain two integers $c_i$ and $p_i$. This means that Ujan should pick the integer $c_i$ from the $i$-th box and place it in the $p_i$-th box afterwards.
If there are multiple solutions, output any of those.
You can print each letter in any case (upper or lower).
-----Examples-----
Input
4
3 1 7 4
2 3 2
2 8 5
1 10
Output
Yes
7 2
2 3
5 1
10 4
Input
2
2 3 -2
2 -1 5
Output
No
Input
2
2 -10 10
2 0 -20
Output
Yes
-10 2
-20 1
-----Note-----
In the first sample, Ujan can put the number $7$ in the $2$nd box, the number $2$ in the $3$rd box, the number $5$ in the $1$st box and keep the number $10$ in the same $4$th box. Then the boxes will contain numbers $\{1,5,4\}$, $\{3, 7\}$, $\{8,2\}$ and $\{10\}$. The sum in each box then is equal to $10$.
In the second sample, it is not possible to pick and redistribute the numbers in the required way.
In the third sample, one can swap the numbers $-20$ and $-10$, making the sum in each box equal to $-10$.
|
def main():
k = int(input())
n = []
a = []
for i in range(k):
line = [int(x) for x in input().split()]
ni = line[0]
ai = []
n.append(ni)
a.append(ai)
for j in range(ni):
ai.append(line[1 + j])
answer, c, p = solve(k, n, a)
if answer:
print("Yes")
for i in range(k):
print(c[i], p[i] + 1)
else:
print("No")
def solve(k, n, a):
asum, sums = calc_sums(k, n, a)
if asum % k != 0:
return False, None, None
tsum = asum / k
num_map = build_num_map(k, n, a)
masks = [None]*(1 << k)
answer = [False]*(1 << k)
left = [0]*(1 << k)
right = [0]*(1 << k)
for i in range(k):
for j in range(n[i]):
found, mask, path = find_cycle(i, j, i, j, k, n, a, sums, tsum, num_map, 0, dict())
if found:
answer[mask] = True
masks[mask] = path
for mask_right in range(1 << k):
if not masks[mask_right]:
continue
zeroes_count = 0
for u in range(k):
if (1 << u) > mask_right:
break
if (mask_right & (1 << u)) == 0:
zeroes_count += 1
for mask_mask in range(1 << zeroes_count):
mask_left = 0
c = 0
for u in range(k):
if (1 << u) > mask_right:
break
if (mask_right & (1 << u)) == 0:
if (mask_mask & (1 << c)) != 0:
mask_left = mask_left | (1 << u)
c += 1
joint_mask = mask_left | mask_right
if answer[mask_left] and not answer[joint_mask]:
answer[joint_mask] = True
left[joint_mask] = mask_left
right[joint_mask] = mask_right
if joint_mask == ((1 << k) - 1):
return build_answer(k, masks, left, right)
if answer[(1 << k) - 1]:
return build_answer(k, masks, left, right)
return False, None, None
def build_answer(k, masks, left, right):
c = [-1] * k
p = [-1] * k
pos = (1 << k) - 1
while not masks[pos]:
for key, val in list(masks[right[pos]].items()):
c[key] = val[0]
p[key] = val[1]
pos = left[pos]
for key, val in list(masks[pos].items()):
c[key] = val[0]
p[key] = val[1]
return True, c, p
def build_num_map(k, n, a):
result = dict()
for i in range(k):
for j in range(n[i]):
result[a[i][j]] = (i, j)
return result
def find_cycle(i_origin, j_origin, i, j, k, n, a, sums, tsum, num_map, mask, path):
if (mask & (1 << i)) != 0:
if i == i_origin and j == j_origin:
return True, mask, path
else:
return False, None, None
mask = mask | (1 << i)
a_needed = tsum - (sums[i] - a[i][j])
if a_needed not in num_map:
return False, None, None
i_next, j_next = num_map[a_needed]
path[i_next] = (a[i_next][j_next], i)
return find_cycle(i_origin, j_origin, i_next, j_next, k, n, a, sums, tsum, num_map, mask, path)
def calc_sums(k, n, a):
sums = [0] * k
for i in range(k):
for j in range(n[i]):
sums[i] = sums[i] + a[i][j]
asum = 0
for i in range(k):
asum = asum + sums[i]
return asum, sums
def __starting_point():
main()
__starting_point()
|
def main():
k = int(input())
n = []
a = []
for i in range(k):
line = [int(x) for x in input().split()]
ni = line[0]
ai = []
n.append(ni)
a.append(ai)
for j in range(ni):
ai.append(line[1 + j])
answer, c, p = solve(k, n, a)
if answer:
print("Yes")
for i in range(k):
print(c[i], p[i] + 1)
else:
print("No")
def solve(k, n, a):
asum, sums = calc_sums(k, n, a)
if asum % k != 0:
return False, None, None
tsum = asum / k
num_map = build_num_map(k, n, a)
masks = [None]*(1 << k)
answer = [False]*(1 << k)
left = [0]*(1 << k)
right = [0]*(1 << k)
for i in range(k):
for j in range(n[i]):
found, mask, path = find_cycle(i, j, i, j, k, n, a, sums, tsum, num_map, 0, dict())
if found:
answer[mask] = True
masks[mask] = path
for mask_right in range(1 << k):
if not masks[mask_right]:
continue
zeroes_count = 0
for u in range(k):
if (1 << u) > mask_right:
break
if (mask_right & (1 << u)) == 0:
zeroes_count += 1
for mask_mask in range(1 << zeroes_count):
mask_left = 0
c = 0
for u in range(k):
if (1 << u) > mask_right:
break
if (mask_right & (1 << u)) == 0:
if (mask_mask & (1 << c)) != 0:
mask_left = mask_left | (1 << u)
c += 1
joint_mask = mask_left | mask_right
if answer[mask_left] and not answer[joint_mask]:
answer[joint_mask] = True
left[joint_mask] = mask_left
right[joint_mask] = mask_right
if joint_mask == ((1 << k) - 1):
return build_answer(k, masks, left, right)
if answer[(1 << k) - 1]:
return build_answer(k, masks, left, right)
return False, None, None
def build_answer(k, masks, left, right):
c = [-1] * k
p = [-1] * k
pos = (1 << k) - 1
while not masks[pos]:
for key, val in list(masks[right[pos]].items()):
c[key] = val[0]
p[key] = val[1]
pos = left[pos]
for key, val in list(masks[pos].items()):
c[key] = val[0]
p[key] = val[1]
return True, c, p
def build_num_map(k, n, a):
result = dict()
for i in range(k):
for j in range(n[i]):
result[a[i][j]] = (i, j)
return result
def find_cycle(i_origin, j_origin, i, j, k, n, a, sums, tsum, num_map, mask, path):
if (mask & (1 << i)) != 0:
if i == i_origin and j == j_origin:
return True, mask, path
else:
return False, None, None
mask = mask | (1 << i)
a_needed = tsum - (sums[i] - a[i][j])
if a_needed not in num_map:
return False, None, None
i_next, j_next = num_map[a_needed]
path[i_next] = (a[i_next][j_next], i)
return find_cycle(i_origin, j_origin, i_next, j_next, k, n, a, sums, tsum, num_map, mask, path)
def calc_sums(k, n, a):
sums = [0] * k
for i in range(k):
for j in range(n[i]):
sums[i] = sums[i] + a[i][j]
asum = 0
for i in range(k):
asum = asum + sums[i]
return asum, sums
def __starting_point():
main()
__starting_point()
|
train
|
APPS_structured
|
You are given a tree (connected graph without cycles) consisting of $n$ vertices. The tree is unrooted — it is just a connected undirected graph without cycles.
In one move, you can choose exactly $k$ leaves (leaf is such a vertex that is connected to only one another vertex) connected to the same vertex and remove them with edges incident to them. I.e. you choose such leaves $u_1, u_2, \dots, u_k$ that there are edges $(u_1, v)$, $(u_2, v)$, $\dots$, $(u_k, v)$ and remove these leaves and these edges.
Your task is to find the maximum number of moves you can perform if you remove leaves optimally.
You have to answer $t$ independent test cases.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 2 \cdot 10^4$) — the number of test cases. Then $t$ test cases follow.
The first line of the test case contains two integers $n$ and $k$ ($2 \le n \le 2 \cdot 10^5$; $1 \le k < n$) — the number of vertices in the tree and the number of leaves you remove in one move, respectively. The next $n-1$ lines describe edges. The $i$-th edge is represented as two integers $x_i$ and $y_i$ ($1 \le x_i, y_i \le n$), where $x_i$ and $y_i$ are vertices the $i$-th edge connects. It is guaranteed that the given set of edges forms a tree.
It is guaranteed that the sum of $n$ does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$).
-----Output-----
For each test case, print the answer — the maximum number of moves you can perform if you remove leaves optimally.
-----Example-----
Input
4
8 3
1 2
1 5
7 6
6 8
3 1
6 4
6 1
10 3
1 2
1 10
2 3
1 5
1 6
2 4
7 10
10 9
8 10
7 2
3 1
4 5
3 6
7 4
1 2
1 4
5 1
1 2
2 3
4 3
5 3
Output
2
3
3
4
-----Note-----
The picture corresponding to the first test case of the example:
[Image]
There you can remove vertices $2$, $5$ and $3$ during the first move and vertices $1$, $7$ and $4$ during the second move.
The picture corresponding to the second test case of the example:
[Image]
There you can remove vertices $7$, $8$ and $9$ during the first move, then vertices $5$, $6$ and $10$ during the second move and vertices $1$, $3$ and $4$ during the third move.
The picture corresponding to the third test case of the example:
$\text{of}$
There you can remove vertices $5$ and $7$ during the first move, then vertices $2$ and $4$ during the second move and vertices $1$ and $6$ during the third move.
|
def crop_set(s, n):
new = set()
it = iter(s)
for i in range(n):
new.add(next(it))
return new
class Vertex:
__slots__ = ("vertexes", "leaves", "graph")
def __init__(self, graph):
self.vertexes = set()
self.leaves = 0
self.graph = graph
def try_to_leave(self):
if len(self.vertexes) + self.leaves == 1:
if self.vertexes:
parent = self.vertexes.pop()
parent.vertexes.remove(self)
parent.leaves += 1
parent.update()
self.vertexes.add(parent)
def update(self):
self.graph[self] = self.leaves
class Tree:
def __init__(self, n, k):
self.k = k
self.lc = [set() for _ in range(n // k + 1)]
self.dlc = dict()
self.max = 0
def add_vertex(self, v):
self.dlc[v] = 0
self.lc[0].add(v)
v.update()
def __setitem__(self, key, value):
value = value // self.k
if self.max == self.dlc[key] > value:
self.lc[self.max].discard(key)
while not self.lc[self.max]:
self.max -= 1
else:
self.lc[self.dlc[key]].discard(key)
if value > self.max:
self.max = value
self.dlc[key] = value
self.lc[value].add(key)
def to_int_decrement(s):
return int(s) - 1
def solve():
n, k = list(map(int, input().split()))
tree = Tree(n, k)
graph = [Vertex(tree) for _ in range(n)]
for _ in range(n - 1):
a, b = list(map(to_int_decrement, input().split()))
graph[a].vertexes.add(graph[b])
graph[b].vertexes.add(graph[a])
if k == 1:
print(n - 1)
return
for v in graph:
tree.add_vertex(v)
for v in graph:
v.try_to_leave()
c = 0
while tree.max > 0:
v = tree.lc[tree.max].pop()
c += v.leaves // k
v.leaves -= v.leaves // k * k
v.try_to_leave()
v.update()
print(c)
for _ in range(int(input())):
solve()
|
def crop_set(s, n):
new = set()
it = iter(s)
for i in range(n):
new.add(next(it))
return new
class Vertex:
__slots__ = ("vertexes", "leaves", "graph")
def __init__(self, graph):
self.vertexes = set()
self.leaves = 0
self.graph = graph
def try_to_leave(self):
if len(self.vertexes) + self.leaves == 1:
if self.vertexes:
parent = self.vertexes.pop()
parent.vertexes.remove(self)
parent.leaves += 1
parent.update()
self.vertexes.add(parent)
def update(self):
self.graph[self] = self.leaves
class Tree:
def __init__(self, n, k):
self.k = k
self.lc = [set() for _ in range(n // k + 1)]
self.dlc = dict()
self.max = 0
def add_vertex(self, v):
self.dlc[v] = 0
self.lc[0].add(v)
v.update()
def __setitem__(self, key, value):
value = value // self.k
if self.max == self.dlc[key] > value:
self.lc[self.max].discard(key)
while not self.lc[self.max]:
self.max -= 1
else:
self.lc[self.dlc[key]].discard(key)
if value > self.max:
self.max = value
self.dlc[key] = value
self.lc[value].add(key)
def to_int_decrement(s):
return int(s) - 1
def solve():
n, k = list(map(int, input().split()))
tree = Tree(n, k)
graph = [Vertex(tree) for _ in range(n)]
for _ in range(n - 1):
a, b = list(map(to_int_decrement, input().split()))
graph[a].vertexes.add(graph[b])
graph[b].vertexes.add(graph[a])
if k == 1:
print(n - 1)
return
for v in graph:
tree.add_vertex(v)
for v in graph:
v.try_to_leave()
c = 0
while tree.max > 0:
v = tree.lc[tree.max].pop()
c += v.leaves // k
v.leaves -= v.leaves // k * k
v.try_to_leave()
v.update()
print(c)
for _ in range(int(input())):
solve()
|
train
|
APPS_structured
|
Given a string s, return the last substring of s in lexicographical order.
Example 1:
Input: "abab"
Output: "bab"
Explanation: The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "bab".
Example 2:
Input: "leetcode"
Output: "tcode"
Note:
1 <= s.length <= 4 * 10^5
s contains only lowercase English letters.
|
class Solution:
def lastSubstring(self, s: str) -> str:
if not s: return None
## get max char from s
maxC, N = max(s),len(s)
## get max char indexs to append into inds
## only store the first ind for consecutive max chars
inds = [i for i in range(N) if s[i]==maxC and (i==0 or s[i-1]!=maxC)]
maxind = inds[0] # starting index of the max substring
## using for loop to compare with each substring lead by max char
for i in range(1,len(inds)):
curind = inds[i] # start index of current substring
if self.compare(s[curind:], s[maxind:]):
maxind = curind
return s[maxind:]
def compare(self, s1, s2):
i = 0
while i < len(s1):
if s1[i] > s2[i]:
return True
elif s1[i] < s2[i]:
return False
i += 1
return False
|
class Solution:
def lastSubstring(self, s: str) -> str:
if not s: return None
## get max char from s
maxC, N = max(s),len(s)
## get max char indexs to append into inds
## only store the first ind for consecutive max chars
inds = [i for i in range(N) if s[i]==maxC and (i==0 or s[i-1]!=maxC)]
maxind = inds[0] # starting index of the max substring
## using for loop to compare with each substring lead by max char
for i in range(1,len(inds)):
curind = inds[i] # start index of current substring
if self.compare(s[curind:], s[maxind:]):
maxind = curind
return s[maxind:]
def compare(self, s1, s2):
i = 0
while i < len(s1):
if s1[i] > s2[i]:
return True
elif s1[i] < s2[i]:
return False
i += 1
return False
|
train
|
APPS_structured
|
Baby is getting his frst tooth. This means more sleepless nights, but with the fun of feeling round his gums and trying to guess which will be first out!
Probably best have a sweepstake with your friends - because you have the best chance of knowing. You can feel the gums and see where the raised bits are - most raised, most likely tooth to come through first!
Given an array of numbers (t) to represent baby's gums, you need to return the index of the lump that is most pronounced.
The most pronounced lump is the one that has the biggest differential to its surrounding values. e.g.:
```
[1, 2, 4] = 2
index 0 has a differential of -1 to its right (it is lower so the figure is negative)
index 1 has a differential of +1 to its left, and -2 to its right. Total is -1.
index 2 has a differential of +2 to its left, and nothing to its right,
```
If there is no distinct highest value (more than one occurence of the largest differential), return -1.
|
def first_tooth(some_list):
answer_list = []
if len(some_list) == 1:
return some_list.index(max(some_list))
else:
answer_list.append(some_list[0] - some_list[1])
for i in range(1, len(some_list) - 1):
answer_list.append((some_list[i] - some_list[i - 1]) + (some_list[i] - some_list[i + 1]))
answer_list.append(some_list[len(some_list) - 1] - some_list[len(some_list) - 2])
if answer_list.count(max(answer_list)) > 1:
return -1
return answer_list.index(max(answer_list))
|
def first_tooth(some_list):
answer_list = []
if len(some_list) == 1:
return some_list.index(max(some_list))
else:
answer_list.append(some_list[0] - some_list[1])
for i in range(1, len(some_list) - 1):
answer_list.append((some_list[i] - some_list[i - 1]) + (some_list[i] - some_list[i + 1]))
answer_list.append(some_list[len(some_list) - 1] - some_list[len(some_list) - 2])
if answer_list.count(max(answer_list)) > 1:
return -1
return answer_list.index(max(answer_list))
|
train
|
APPS_structured
|
Given an integer `n`, find two integers `a` and `b` such that:
```Pearl
A) a >= 0 and b >= 0
B) a + b = n
C) DigitSum(a) + Digitsum(b) is maximum of all possibilities.
```
You will return the digitSum(a) + digitsum(b).
```
For example:
solve(29) = 11. If we take 15 + 14 = 29 and digitSum = 1 + 5 + 1 + 4 = 11. There is no larger outcome.
```
`n` will not exceed `10e10`.
More examples in test cases.
Good luck!
|
def solve(param):
a = int('0' + '9' * (len(str(param)) - 1))
return sum(int(d) for d in str(a) + str(param - a))
|
def solve(param):
a = int('0' + '9' * (len(str(param)) - 1))
return sum(int(d) for d in str(a) + str(param - a))
|
train
|
APPS_structured
|
Given the array queries of positive integers between 1 and m, you have to process all queries[i] (from i=0 to i=queries.length-1) according to the following rules:
In the beginning, you have the permutation P=[1,2,3,...,m].
For the current i, find the position of queries[i] in the permutation P (indexing from 0) and then move this at the beginning of the permutation P. Notice that the position of queries[i] in P is the result for queries[i].
Return an array containing the result for the given queries.
Example 1:
Input: queries = [3,1,2,1], m = 5
Output: [2,1,2,1]
Explanation: The queries are processed as follow:
For i=0: queries[i]=3, P=[1,2,3,4,5], position of 3 in P is 2, then we move 3 to the beginning of P resulting in P=[3,1,2,4,5].
For i=1: queries[i]=1, P=[3,1,2,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,3,2,4,5].
For i=2: queries[i]=2, P=[1,3,2,4,5], position of 2 in P is 2, then we move 2 to the beginning of P resulting in P=[2,1,3,4,5].
For i=3: queries[i]=1, P=[2,1,3,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,2,3,4,5].
Therefore, the array containing the result is [2,1,2,1].
Example 2:
Input: queries = [4,1,2,2], m = 4
Output: [3,1,2,0]
Example 3:
Input: queries = [7,5,5,8,3], m = 8
Output: [6,5,0,7,5]
Constraints:
1 <= m <= 10^3
1 <= queries.length <= m
1 <= queries[i] <= m
|
class Solution:
def processQueries(self, queries: List[int], m: int) -> List[int]:
A = list(range(1, m + 1))
res = []
for target in queries:
for i, num in enumerate(A):
if num == target:
res.append(i)
index = i
break
element = A[index]
A.pop(index)
A.insert(0, element)
return res
|
class Solution:
def processQueries(self, queries: List[int], m: int) -> List[int]:
A = list(range(1, m + 1))
res = []
for target in queries:
for i, num in enumerate(A):
if num == target:
res.append(i)
index = i
break
element = A[index]
A.pop(index)
A.insert(0, element)
return res
|
train
|
APPS_structured
|
Two integers A and B are the inputs. Write a program to find GCD and LCM of A and B.
-----Input-----
The first line contains an integer T, total number of testcases. Then follow T lines, each line contains an integer A and B.
-----Output-----
Display the GCD and LCM of A and B separated by space respectively. The answer for each test case must be displayed in a new line.
-----Constraints-----
- 1 ≤ T ≤ 1000
- 1 ≤ A,B ≤ 1000000
-----Example-----
Input
3
120 140
10213 312
10 30
Output
20 840
1 3186456
10 30
|
# cook your dish here
import math
T = int(input())
while(T>0):
A,B = map(int,input().split())
hcf = math.gcd(A,B)
lcm = (A*B)//hcf
print(hcf,lcm)
T = T - 1
|
# cook your dish here
import math
T = int(input())
while(T>0):
A,B = map(int,input().split())
hcf = math.gcd(A,B)
lcm = (A*B)//hcf
print(hcf,lcm)
T = T - 1
|
train
|
APPS_structured
|
Define a method ```hello``` that ```returns``` "Hello, Name!" to a given ```name```, or says Hello, World! if name is not given (or passed as an empty String).
Assuming that ```name``` is a ```String``` and it checks for user typos to return a name with a first capital letter (Xxxx).
Examples:
|
hello = lambda n='', d='World': "Hello, %s!" % (n or d).title()
|
hello = lambda n='', d='World': "Hello, %s!" % (n or d).title()
|
train
|
APPS_structured
|
# The President's phone is broken
He is not very happy.
The only letters still working are uppercase ```E```, ```F```, ```I```, ```R```, ```U```, ```Y```.
An angry tweet is sent to the department responsible for presidential phone maintenance.
# Kata Task
Decipher the tweet by looking for words with known meanings.
* ```FIRE``` = *"You are fired!"*
* ```FURY``` = *"I am furious."*
If no known words are found, or unexpected letters are encountered, then it must be a *"Fake tweet."*
# Notes
* The tweet reads left-to-right.
* Any letters not spelling words ```FIRE``` or ```FURY``` are just ignored
* If multiple of the same words are found in a row then plural rules apply -
* ```FIRE``` x 1 = *"You are fired!"*
* ```FIRE``` x 2 = *"You and you are fired!"*
* ```FIRE``` x 3 = *"You and you and you are fired!"*
* etc...
* ```FURY``` x 1 = *"I am furious."*
* ```FURY``` x 2 = *"I am really furious."*
* ```FURY``` x 3 = *"I am really really furious."*
* etc...
# Examples
* ex1. FURYYYFIREYYFIRE = *"I am furious. You and you are fired!"*
* ex2. FIREYYFURYYFURYYFURRYFIRE = *"You are fired! I am really furious. You are fired!"*
* ex3. FYRYFIRUFIRUFURE = *"Fake tweet."*
----
DM :-)
|
import itertools
import re
MEANINGS = {
'FIRE': [lambda i: "You are fired!", lambda i: f"You{' and you' * i} are fired!"],
'FURY': [lambda i: "I am furious.", lambda i: f"I am{' really' * i} furious."],
}
def fire_and_fury(tweet):
if re.search('[^EFIRUY]', tweet):
tweet = ''
return ' '.join((
MEANINGS[key][n > 1](n-1)
for key, grp in itertools.groupby(re.findall('FIRE|FURY', tweet))
for n in [sum(1 for _ in grp)]
)) or 'Fake tweet.'
|
import itertools
import re
MEANINGS = {
'FIRE': [lambda i: "You are fired!", lambda i: f"You{' and you' * i} are fired!"],
'FURY': [lambda i: "I am furious.", lambda i: f"I am{' really' * i} furious."],
}
def fire_and_fury(tweet):
if re.search('[^EFIRUY]', tweet):
tweet = ''
return ' '.join((
MEANINGS[key][n > 1](n-1)
for key, grp in itertools.groupby(re.findall('FIRE|FURY', tweet))
for n in [sum(1 for _ in grp)]
)) or 'Fake tweet.'
|
train
|
APPS_structured
|
**Principal Diagonal** -- The principal diagonal in a matrix identifies those elements of the matrix running from North-West to South-East.
**Secondary Diagonal** -- the secondary diagonal of a matrix identifies those elements of the matrix running from North-East to South-West.
For example:
```
matrix: [1, 2, 3]
[4, 5, 6]
[7, 8, 9]
principal diagonal: [1, 5, 9]
secondary diagonal: [3, 5, 7]
```
## Task
Your task is to find which diagonal is "larger": which diagonal has a bigger sum of their elements.
* If the principal diagonal is larger, return `"Principal Diagonal win!"`
* If the secondary diagonal is larger, return `"Secondary Diagonal win!"`
* If they are equal, return `"Draw!"`
**Note:** You will always receive matrices of the same dimension.
|
def diagonal(matrix):
if sum(matrix[i][i] for i in range(len(matrix))) > sum(matrix[i][len(matrix)-1-i] for i in range(len(matrix))): return "Principal Diagonal win!"
elif sum(matrix[i][i] for i in range(len(matrix))) < sum(matrix[i][len(matrix)-1-i] for i in range(len(matrix))): return "Secondary Diagonal win!"
else: return "Draw!"
|
def diagonal(matrix):
if sum(matrix[i][i] for i in range(len(matrix))) > sum(matrix[i][len(matrix)-1-i] for i in range(len(matrix))): return "Principal Diagonal win!"
elif sum(matrix[i][i] for i in range(len(matrix))) < sum(matrix[i][len(matrix)-1-i] for i in range(len(matrix))): return "Secondary Diagonal win!"
else: return "Draw!"
|
train
|
APPS_structured
|
Given an integer as input, can you round it to the next (meaning, "higher") multiple of 5?
Examples:
input: output:
0 -> 0
2 -> 5
3 -> 5
12 -> 15
21 -> 25
30 -> 30
-2 -> 0
-5 -> -5
etc.
Input may be any positive or negative integer (including 0).
You can assume that all inputs are valid integers.
|
def round_to_next5(n):
return (round((n/5)+0.49)*5)
|
def round_to_next5(n):
return (round((n/5)+0.49)*5)
|
train
|
APPS_structured
|
The Chef has one long loaf of bread of length 1. He wants to cut it into as many little loaves as he can. But he wants to adhere to the following rule: At any moment, the length of the longest loaf which he possesses may not be larger than the length of shortest one, times some constant factor. Every time, he is only allowed to cut exactly one loaf into two shorter ones.
-----Input-----
One floating-point number, 1 ≤ k ≤ 1.999, meaning the stated constant factor. The number will have at most 3 digits after the decimal point.
-----Output-----
First, you should output one number n, the maximal achievable number of loaves for the given value of the constant factor. Then, you should output any proof that this number of loaves is in fact achievable: n-1 descriptions of cutting, using the following notation. At each step, you print two numbers: first, the index of the loaf that you want to cut into two parts; second, the length of the newly created loaf (cut off from the original one). It is assumed that the starting loaf has index 0. Each newly created loaf will be given the lowest possible free integer index (so, at the ith step this will be i). Each time, the size of size of the original loaf will be decreased by the size of the newly created loaf.
-----Example-----
Input:
1.5
Output:
4
0 0.4
0 0.3
1 0.2
|
import sys
from math import log
k = float(sys.stdin.readline())
answer = int(log(2.0, 2.0/k))
print(2*answer)
m = 2 ** (1.0/answer)
# m = 2.0/k
thesum = 0
for i in range(answer):
thesum += m**i
# print [m**i/thesum for i in xrange(answer)]
loaves = [1]
def maxIndex(list):
max = -1
mi = -1
for i, x in enumerate(list):
if x > max:
max = x
mi = i
return mi
desired = [m**i/thesum for i in range(answer)]
desired.reverse()
# print desired
cuts = []
while len(desired) > 1:
cuts.append(desired[-1])
lastsum = desired[-1] + desired[-2]
del desired[-2:]
desired[0:0] = [lastsum]
# print cuts
while cuts:
length = cuts.pop()
i = maxIndex(loaves)
print(i, length)
loaves[i] -= length
loaves.append(length)
# print loaves
# print loaves
for i in range(answer):
i = maxIndex(loaves[:answer])
x = loaves[i]/2.0
print(i, x)
loaves.append(x)
loaves[i] -= x
# print loaves
|
import sys
from math import log
k = float(sys.stdin.readline())
answer = int(log(2.0, 2.0/k))
print(2*answer)
m = 2 ** (1.0/answer)
# m = 2.0/k
thesum = 0
for i in range(answer):
thesum += m**i
# print [m**i/thesum for i in xrange(answer)]
loaves = [1]
def maxIndex(list):
max = -1
mi = -1
for i, x in enumerate(list):
if x > max:
max = x
mi = i
return mi
desired = [m**i/thesum for i in range(answer)]
desired.reverse()
# print desired
cuts = []
while len(desired) > 1:
cuts.append(desired[-1])
lastsum = desired[-1] + desired[-2]
del desired[-2:]
desired[0:0] = [lastsum]
# print cuts
while cuts:
length = cuts.pop()
i = maxIndex(loaves)
print(i, length)
loaves[i] -= length
loaves.append(length)
# print loaves
# print loaves
for i in range(answer):
i = maxIndex(loaves[:answer])
x = loaves[i]/2.0
print(i, x)
loaves.append(x)
loaves[i] -= x
# print loaves
|
train
|
APPS_structured
|
Write a function that receives two strings and returns n, where n is equal to the number of characters we should shift the first string forward to match the second.
For instance, take the strings "fatigue" and "tiguefa". In this case, the first string has been rotated 5 characters forward to produce the second string, so 5 would be returned.
If the second string isn't a valid rotation of the first string, the method returns -1.
Examples:
```
"coffee", "eecoff" => 2
"eecoff", "coffee" => 4
"moose", "Moose" => -1
"isn't", "'tisn" => 2
"Esham", "Esham" => 0
"dog", "god" => -1
```
For Swift, your function should return an Int?. So rather than returning -1 when the second string isn't a valid rotation of the first, return nil.
|
def shifted_diff(first, second):
for i in range(len(first)):
if first == second[i:] + second[:i]:
return i
return -1
|
def shifted_diff(first, second):
for i in range(len(first)):
if first == second[i:] + second[:i]:
return i
return -1
|
train
|
APPS_structured
|
# Task
Round the given number `n` to the nearest multiple of `m`.
If `n` is exactly in the middle of 2 multiples of m, return `n` instead.
# Example
For `n = 20, m = 3`, the output should be `21`.
For `n = 19, m = 3`, the output should be `18`.
For `n = 50, m = 100`, the output should be `50`.
# Input/Output
- `[input]` integer `n`
`1 ≤ n < 10^9.`
- `[input]` integer `m`
`3 ≤ m < 109`.
- `[output]` an integer
|
from math import gcd, ceil
def rounding(n,m):
return round(n/m)*m if n != ((n//m)*m + ceil(n/m)*m)/2 else n
|
from math import gcd, ceil
def rounding(n,m):
return round(n/m)*m if n != ((n//m)*m + ceil(n/m)*m)/2 else n
|
train
|
APPS_structured
|
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid.
A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell.
Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell.
Return true if any cycle of the same value exists in grid, otherwise, return false.
Example 1:
Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]]
Output: true
Explanation: There are two valid cycles shown in different colors in the image below:
Example 2:
Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]]
Output: true
Explanation: There is only one valid cycle highlighted in the image below:
Example 3:
Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]]
Output: false
Constraints:
m == grid.length
n == grid[i].length
1 <= m <= 500
1 <= n <= 500
grid consists only of lowercase English letters.
|
class UnionFind:
def __init__(self, n):
self.parents = [i for i in range(n)]
def find(self, i):
if self.parents[i] == i:
return i
self.parents[i] = self.find(self.parents[i])
return self.parents[i]
def unite(self, a, b):
pa = self.find(a)
pb = self.find(b)
self.parents[pb] = pa
return
def same(self, a, b):
pa = self.find(a)
pb = self.find(b)
return pa==pb
class Solution:
def containsCycle(self, grid: List[List[str]]) -> bool:
dx = [ 1, 0]
dy = [ 0, 1]
N = len(grid)
M = len(grid[0])
ALL = N*M
# print(\"size\", N, M, ALL)
tree = UnionFind(ALL)
for i in range(N):
for j in range(M):
for k in range(2):
if 0<=i +dx[k] <N and 0<= j+dy[k]<M:
if grid[i][j] == grid[i+dx[k]][j+dy[k]]:
# print(i, j, k)
# print((i+dx[k])*M+j+dy[k])
if tree.same(i*M+j, (i+dx[k])*M+j+dy[k]):
return True
tree.unite(i*M+j, (i+dx[k])*M+j+dy[k])
return False
|
class UnionFind:
def __init__(self, n):
self.parents = [i for i in range(n)]
def find(self, i):
if self.parents[i] == i:
return i
self.parents[i] = self.find(self.parents[i])
return self.parents[i]
def unite(self, a, b):
pa = self.find(a)
pb = self.find(b)
self.parents[pb] = pa
return
def same(self, a, b):
pa = self.find(a)
pb = self.find(b)
return pa==pb
class Solution:
def containsCycle(self, grid: List[List[str]]) -> bool:
dx = [ 1, 0]
dy = [ 0, 1]
N = len(grid)
M = len(grid[0])
ALL = N*M
# print(\"size\", N, M, ALL)
tree = UnionFind(ALL)
for i in range(N):
for j in range(M):
for k in range(2):
if 0<=i +dx[k] <N and 0<= j+dy[k]<M:
if grid[i][j] == grid[i+dx[k]][j+dy[k]]:
# print(i, j, k)
# print((i+dx[k])*M+j+dy[k])
if tree.same(i*M+j, (i+dx[k])*M+j+dy[k]):
return True
tree.unite(i*M+j, (i+dx[k])*M+j+dy[k])
return False
|
train
|
APPS_structured
|
-----Problem Statement-----
Harry Potter has one biscuit and zero rupee in his pocket. He will perform the following operations exactly $K$ times in total, in the order he likes:
- Hit his pocket, which magically increases the number of biscuits by one.
- Exchange $A$ biscuits to $1$ rupee.
- Exchange $1$ rupee to $B$ biscuits.
Find the maximum possible number of biscuits in Harry's pocket after $K$ operations.
-----Input-----
Input is given in the following format:
K A B
-----Output-----
Print the maximum possible number of biscuits in Harry's pocket after $K$operations.
-----Constraints-----
- $1 \leq K, A, B \leq 10^9$
- $K$, $A$ and are integers.
-----Sample Input-----
4 2 6
-----Sample Output-----
7
-----EXPLANATION-----
The number of biscuits in Harry's pocket after $K$ operations is maximized as follows:
- Hit his pocket. Now he has $2$ biscuits and $0$ rupee.
- Exchange $2$ biscuits to $1$ rupee in his pocket .Now he has $0$ biscuits and $1$ rupee.
- Hit his pocket. Now he has $1$ biscuits and $1$ rupee.
- Exchange $1$ rupee to $6$ biscuits. his pocket. Now he has $7$ biscuits and $0$ rupee.
|
k, a, b = map(int, input().split())
if (b-a) <= 2: print(k+1)
else:
count = a
k = k-(a-1)
count += (b-a)*(k>>1)
count += k&1
print(count)
|
k, a, b = map(int, input().split())
if (b-a) <= 2: print(k+1)
else:
count = a
k = k-(a-1)
count += (b-a)*(k>>1)
count += k&1
print(count)
|
train
|
APPS_structured
|
We are given head, the head node of a linked list containing unique integer values.
We are also given the list G, a subset of the values in the linked list.
Return the number of connected components in G, where two values are connected if they appear consecutively in the linked list.
Example 1:
Input:
head: 0->1->2->3
G = [0, 1, 3]
Output: 2
Explanation:
0 and 1 are connected, so [0, 1] and [3] are the two connected components.
Example 2:
Input:
head: 0->1->2->3->4
G = [0, 3, 1, 4]
Output: 2
Explanation:
0 and 1 are connected, 3 and 4 are connected, so [0, 1] and [3, 4] are the two connected components.
Note:
If N is the length of the linked list given by head, 1 <= N <= 10000.
The value of each node in the linked list will be in the range [0, N - 1].
1 <= G.length <= 10000.
G is a subset of all values in the linked list.
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def numComponents(self, head: ListNode, G: List[int]) -> int:
normal_list = []
while head:
normal_list.append(head.val)
head = head.next
print(\"normal_list: \", normal_list)
G.sort()
print(\"G: \", G)
groups = 0
stack = []
group_started = False
# traverse normal_list
while len(normal_list) > 0:
a = normal_list.pop(0)
if a in G:
group_started = True
else:
if group_started == True:
groups += 1
group_started = False
if group_started == True:
groups += 1
return groups
# i = 0
# while i < len(normal_list):
# while i < len(normal_list) and normal_list[i] != G[i]:
# G.insert(i, \"\")
# i+=1
# i+=1
# print(\"G: \", G)
# groups = 0
# g = 0
# groups_started = False
# while g < len(G):
# if G[g] != '':
# groups_started = True
# else:
# if groups_started == True:
# groups += 1
# groups_started = False
# g+=1
# if groups_started == True:
# groups +=1 # for the last one
# print(\"groups: \", groups)
# return groups
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def numComponents(self, head: ListNode, G: List[int]) -> int:
normal_list = []
while head:
normal_list.append(head.val)
head = head.next
print(\"normal_list: \", normal_list)
G.sort()
print(\"G: \", G)
groups = 0
stack = []
group_started = False
# traverse normal_list
while len(normal_list) > 0:
a = normal_list.pop(0)
if a in G:
group_started = True
else:
if group_started == True:
groups += 1
group_started = False
if group_started == True:
groups += 1
return groups
# i = 0
# while i < len(normal_list):
# while i < len(normal_list) and normal_list[i] != G[i]:
# G.insert(i, \"\")
# i+=1
# i+=1
# print(\"G: \", G)
# groups = 0
# g = 0
# groups_started = False
# while g < len(G):
# if G[g] != '':
# groups_started = True
# else:
# if groups_started == True:
# groups += 1
# groups_started = False
# g+=1
# if groups_started == True:
# groups +=1 # for the last one
# print(\"groups: \", groups)
# return groups
|
train
|
APPS_structured
|
Autobots are instructed by Optimus Prime to mobilize in the form of a rectangular shape with each Autobot on each vertex of the rectangle region on a -”deployment area” (which may consist of one or more regions). This is done so as to take care of the inner rectangular area called “region”. However the rule states-“no two regions may overlap”. You have been asked to remove some regions from the “deployment area” so the remaining regions do not obscure each other. To keep the disturbance to the minimum level, you should remove the minimum number of regions to achieve this goal. You may not remove a region and place it in another position; all regions you leave in “deployment area” must be in their original position.
When you examined the “deployment area”, you noticed something very nice. Every region was placed on the deployment area by placing each autobot in the four corners. This was done in a very courteous manner since each autobot is guarding only the region it is holding.
The reason Optimus Prime wants your help because you are good at taking down a single region without disturbing the rest, even if that region is obscured by many others.
-----Input-----
The first line consists of a single integer T indicating the number of test cases (about 25).
Each test case consists begins with a single integer n indicating the number of regions. The next n lines consist of 4 integers x0, x1, y0, and y1 satisfying x0 < x1 and y0 < y1. This means the region covers all points (x,y) satisfying x0 <= x <= x1 and y0 <= y <= y1.
As stated before hand, no corner of any region will intersect any other region anywhere. That is, if (x,y) is a corner point of one region and another region is described by x0, x1, y0, and y1, then we do not have x0 <= x <= x1 and y0 <= y <= y1.
Bounds: 1 <= n <= 100 and each integer in a region description fits in a signed 32 bit integer.
-----Output-----
The output for each test case is a single line containing a single integer that is the maximum number of regions that can be left on the wall such that no two regions share a common point in the deployment area.
-----Example-----
Input:
1
4
0 4 0 4
1 3 1 2
2 3 1 3
3 4 1 3
Output:
2
|
print
|
print
|
train
|
APPS_structured
|
Berland year consists of $m$ months with $d$ days each. Months are numbered from $1$ to $m$. Berland week consists of $w$ days. The first day of the year is also the first day of the week. Note that the last week of the year might be shorter than $w$ days.
A pair $(x, y)$ such that $x < y$ is ambiguous if day $x$ of month $y$ is the same day of the week as day $y$ of month $x$.
Count the number of ambiguous pairs.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 1000$) — the number of testcases.
Each of the next $t$ lines contains three integers $m$, $d$ and $w$ ($1 \le m, d, w \le 10^9$) — the number of months in a year, the number of days in a month and the number of days in a week.
-----Output-----
Print $t$ integers — for each testcase output the number of pairs $(x, y)$ such that $x < y$ and day $x$ of month $y$ is the same day of the week as day $y$ of month $x$.
-----Example-----
Input
5
6 7 4
10 7 12
12 30 7
1 1 1
3247834 10298779 625324
Output
6
9
5
0
116461800
-----Note-----
Here are the pairs for the first test case: $$
|
from math import gcd
for _ in range(int(input())):
m, d, w = list(map(int, input().split()))
if d == 1:
print(0)
else:
w1 = w // gcd(w, d - 1)
md = min(m, d)
# sum(max(md - w1 * n, 0) for n in 1..inf)
# sum(md - w1 * n for n in 1..md // w1)
mdd_w1 = md // w1
print((md * 2 - w1 - mdd_w1 * w1) * mdd_w1 // 2)
|
from math import gcd
for _ in range(int(input())):
m, d, w = list(map(int, input().split()))
if d == 1:
print(0)
else:
w1 = w // gcd(w, d - 1)
md = min(m, d)
# sum(max(md - w1 * n, 0) for n in 1..inf)
# sum(md - w1 * n for n in 1..md // w1)
mdd_w1 = md // w1
print((md * 2 - w1 - mdd_w1 * w1) * mdd_w1 // 2)
|
train
|
APPS_structured
|
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
Note: A leaf is a node with no children.
Example:
Input: [1,2,3]
1
/ \
2 3
Output: 25
Explanation:
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Therefore, sum = 12 + 13 = 25.
Example 2:
Input: [4,9,0,5,1]
4
/ \
9 0
/ \
5 1
Output: 1026
Explanation:
The root-to-leaf path 4->9->5 represents the number 495.
The root-to-leaf path 4->9->1 represents the number 491.
The root-to-leaf path 4->0 represents the number 40.
Therefore, sum = 495 + 491 + 40 = 1026.
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from copy import deepcopy
class Solution:
def __init__(self):
self.treeSum = 0
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.tree(root, [])
return self.treeSum
def tree(self, node, path):
if not node:
return False
path.append(str(node.val))
print(path, node.val)
l = self.tree(node.left, copy.deepcopy(path))
r = self.tree(node.right, copy.deepcopy(path))
if not l and not r:
self.treeSum += int(''.join(path))
return True
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from copy import deepcopy
class Solution:
def __init__(self):
self.treeSum = 0
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.tree(root, [])
return self.treeSum
def tree(self, node, path):
if not node:
return False
path.append(str(node.val))
print(path, node.val)
l = self.tree(node.left, copy.deepcopy(path))
r = self.tree(node.right, copy.deepcopy(path))
if not l and not r:
self.treeSum += int(''.join(path))
return True
|
train
|
APPS_structured
|
# Task
Given an array of integers, sum consecutive even numbers and consecutive odd numbers. Repeat the process while it can be done and return the length of the final array.
# Example
For `arr = [2, 1, 2, 2, 6, 5, 0, 2, 0, 5, 5, 7, 7, 4, 3, 3, 9]`
The result should be `6`.
```
[2, 1, 2, 2, 6, 5, 0, 2, 0, 5, 5, 7, 7, 4, 3, 3, 9] -->
2+2+6 0+2+0 5+5+7+7 3+3+9
[2, 1, 10, 5, 2, 24, 4, 15 ] -->
2+24+4
[2, 1, 10, 5, 30, 15 ]
The length of final array is 6
```
# Input/Output
- `[input]` integer array `arr`
A non-empty array,
`1 ≤ arr.length ≤ 1000`
`0 ≤ arr[i] ≤ 1000`
- `[output]` an integer
The length of the final array
|
from itertools import groupby
def sum_groups(arr):
nums = list(arr)
while True:
tmp = [sum(g) for _, g in groupby(nums, key=lambda a: a % 2)]
if nums == tmp:
return len(nums)
nums = tmp
|
from itertools import groupby
def sum_groups(arr):
nums = list(arr)
while True:
tmp = [sum(g) for _, g in groupby(nums, key=lambda a: a % 2)]
if nums == tmp:
return len(nums)
nums = tmp
|
train
|
APPS_structured
|
> [Run-length encoding](https://en.wikipedia.org/w/index.php?title=Run-length_encoding) (RLE) is a very simple form of data compression in which runs of data (that is, sequences in which the same data value occurs in many consecutive data elements) are stored as a single data value and count, rather than as the original run. Wikipedia
## Task
Your task is to write such a run-length encoding. For a given string, return a list (or array) of pairs (or arrays)
[
(i1, s1),
(i2, s2),
…,
(in, sn)
], such that one can reconstruct the original string by replicating the character sx ix times and concatening all those strings. Your run-length encoding should be minimal, ie. for all i the values si and si+1 should differ.
## Examples
As the article states, RLE is a _very_ simple form of data compression. It's only suitable for runs of data, as one can see in the following example:
```python
run_length_encoding("hello world!")
//=> [[1,'h'], [1,'e'], [2,'l'], [1,'o'], [1,' '], [1,'w'], [1,'o'], [1,'r'], [1,'l'], [1,'d'], [1,'!']]
```
It's very effective if the same data value occurs in many consecutive data elements:
```python
run_length_encoding("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbb")
# => [[34,'a'], [3,'b']]
```
|
import re
def run_length_encoding(s):
return [[len(l), e] for l, e in re.findall( r'((.)\2*)', s )]
|
import re
def run_length_encoding(s):
return [[len(l), e] for l, e in re.findall( r'((.)\2*)', s )]
|
train
|
APPS_structured
|
You were given a string of integer temperature values. Create a function `lowest_temp(t)` and return the lowest value or `None/null/Nothing` if the string is empty.
|
def lowest_temp(t):
if t:
return min([int(x) for x in t.split()])
else:
return None
|
def lowest_temp(t):
if t:
return min([int(x) for x in t.split()])
else:
return None
|
train
|
APPS_structured
|
Sebi lives in Chefland where the government is extremely corrupt that usually makes fool out of public by announcing eye catching but non-sustainable schemes. Recently there was a move to increase tourism in the country that was highly lauded. Sebi wants to examine whether the move has some potential or is a hogwash as usual.
The Chefland is a city with very old road infrastructure. The city has N tourist places. All the places are reachable from each other. The corrupt administrators of the city constructed as few roads as possible just ensuring that all the places are reachable from each other, and those too have now gone old with potholes every here and there. Upon this, there is a toll tax for each road too, which you have to pay once for using that road. Once you pay the tax for a road, you can visit it again as many times as possible.
The tourists coming to Chefland usually want to see all the N nice places. They usually have visit in their own vehicle and stay for few days. Also, they are usually not very rich, they want to pay as less toll tax as possible. For promoting tourism, the government offered their citizens a scheme. It was announced that citizens can choose any two places and the government will build a high class road between those two places and that too without any toll tax. Note that citizens may choose to have a high class road between two cities which already have an old road between them.
Sebi is very sceptical of the claims of the announcement. So, he wants to understand the expected toll tax a tourist has to pay to tour the entire city considering that the citizens of Chefland vote for the two cities for constructing high road uniformly randomly. Can you please him in finding this?
-----Input-----
There is a single test case per test file.
The first line of the input contains an integer N denoting the number of tourist spots in Chefland.
Each of the he next N - 1 lines contains three space separated integers u, v, c, denoting that there is a road between tourist spot u and v which has a toll tax of c Rs.
-----Output-----
Output a single line containing the expected toll tax a tourist has to pay for visiting all the N spots after the construction of new road. Your answer will be considered correct if it has an absolute error less than or equal to 1e-2.
-----Constraints-----
- 2 ≤ N ≤ 105
- 1 ≤ u, v ≤ N
- 0 ≤ c ≤ 106
-----Example-----
Input:
3
1 2 3
1 3 2
Output:
2.333333
-----Explanation-----
Assume that the citizens construct the high class road between city 1 and 2. A tourist can visit all the places by just paying a toll tax of 2 Rs.
If the high class road is constructed between city 1 and 3. All the places then can be visited by just paying a toll tax of 3 Rs.
If the cities 2 and 3 are connected by the high class road. All the places can be visited by paying a toll tax of 2Rs.
Hence expected Rs. that a tourist has to pay in toll tax will be (2 + 3 + 2) / 3 = 7 / 3 = 2.333333
|
# cook your dish here
def find(n):
if parent[n] != n:
parent[n] = find(parent[n])
return parent[n]
def merge(a, b):
a, b = find(a), find(b)
if rank[a] > rank[b]:
parent[b] = a
size[a] += size[b]
else:
parent[a] = b
size[b] += size[a]
if rank[a] == rank[b]:
rank[b] += 1
n = int(input())
size = {}
rank = {}
parent = {}
edges = []
for i in range(n):
size[i] = 1
parent[i] = i
rank[i] = 1
for i in range(n - 1):
a, b, c = list(map(int, input().split()))
a -= 1
b -= 1
edges.append([c, a, b])
edges.sort()
S = T = C = 0
for c, a, b in edges:
a = find(a)
b = find(b)
# update values
S += size[a] * size[b] * c
T += size[a] * size[b]
C += c
merge(a, b)
print(C - (S/T))
|
# cook your dish here
def find(n):
if parent[n] != n:
parent[n] = find(parent[n])
return parent[n]
def merge(a, b):
a, b = find(a), find(b)
if rank[a] > rank[b]:
parent[b] = a
size[a] += size[b]
else:
parent[a] = b
size[b] += size[a]
if rank[a] == rank[b]:
rank[b] += 1
n = int(input())
size = {}
rank = {}
parent = {}
edges = []
for i in range(n):
size[i] = 1
parent[i] = i
rank[i] = 1
for i in range(n - 1):
a, b, c = list(map(int, input().split()))
a -= 1
b -= 1
edges.append([c, a, b])
edges.sort()
S = T = C = 0
for c, a, b in edges:
a = find(a)
b = find(b)
# update values
S += size[a] * size[b] * c
T += size[a] * size[b]
C += c
merge(a, b)
print(C - (S/T))
|
train
|
APPS_structured
|
Our AAA company is in need of some software to help with logistics: you will be given the width and height of a map, a list of x coordinates and a list of y coordinates of the supply points, starting to count from the top left corner of the map as 0.
Your goal is to return a two dimensional array/list with every item having the value of the distance of the square itself from the closest supply point expressed as a simple integer.
Quick examples:
```python
logistic_map(3,3,[0],[0])
#returns
#[[0,1,2],
# [1,2,3],
# [2,3,4]]
logistic_map(5,2,[0,4],[0,0])
#returns
#[[0,1,2,1,0],
# [1,2,3,2,1]]
```
Remember that our company is operating with trucks, not drones, so you can simply use Manhattan distance. If supply points are present, they are going to be within the boundaries of the map; if no supply point is present on the map, just return `None`/`nil`/`null` in every cell.
```python
logistic_map(2,2,[],[])
#returns
#[[None,None],
# [None,None]]
```
**Note:** this one is taken (and a bit complicated) from a problem a real world AAA company [whose name I won't tell here] used in their interview. It was done by a friend of mine. It is nothing that difficult and I assume it is their own version of the FizzBuzz problem, but consider candidates were given about 30 mins to solve it.
|
def logistic_map(width,height,xs,ys):
# kind of a brute force solution but hey
supply_stops = zip(*[xs,ys])
points = [[None for x in range(width)] for x in range(height)]
for s in supply_stops:
for i in range(width):
for j in range(height):
d_cur = abs(s[0] - i) + abs(s[1] - j)
d_pnt = points[j][i]
if (d_pnt == None) or (d_cur < d_pnt):
points[j][i] = d_cur
return points
|
def logistic_map(width,height,xs,ys):
# kind of a brute force solution but hey
supply_stops = zip(*[xs,ys])
points = [[None for x in range(width)] for x in range(height)]
for s in supply_stops:
for i in range(width):
for j in range(height):
d_cur = abs(s[0] - i) + abs(s[1] - j)
d_pnt = points[j][i]
if (d_pnt == None) or (d_cur < d_pnt):
points[j][i] = d_cur
return points
|
train
|
APPS_structured
|
Given an array (ints) of n integers, find three integers in arr such that the sum is closest to a given number (num), target.
Return the sum of the three integers.
You may assume that each input would have exactly one solution.
Example:
Note: your solution should not modify the input array.
|
import itertools
def closest_sum(ints, num):
res = ints[:3]
comb = list(itertools.combinations(ints, 3))
for i in comb:
if abs(num-sum(i)) < abs(num-sum(res)):
res = [_ for _ in i]
return sum(res)
|
import itertools
def closest_sum(ints, num):
res = ints[:3]
comb = list(itertools.combinations(ints, 3))
for i in comb:
if abs(num-sum(i)) < abs(num-sum(res)):
res = [_ for _ in i]
return sum(res)
|
train
|
APPS_structured
|
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.
Consider a set consisting of k (0 ≤ k < n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.
Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (10^9 + 7).
-----Input-----
The first line contains an integer n (2 ≤ n ≤ 10^5) — the number of tree vertices.
The second line contains the description of the tree: n - 1 integers p_0, p_1, ..., p_{n} - 2 (0 ≤ p_{i} ≤ i). Where p_{i} means that there is an edge connecting vertex (i + 1) of the tree and vertex p_{i}. Consider tree vertices are numbered from 0 to n - 1.
The third line contains the description of the colors of the vertices: n integers x_0, x_1, ..., x_{n} - 1 (x_{i} is either 0 or 1). If x_{i} is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.
-----Output-----
Output a single integer — the number of ways to split the tree modulo 1000000007 (10^9 + 7).
-----Examples-----
Input
3
0 0
0 1 1
Output
2
Input
6
0 1 1 0 4
1 1 0 0 1 0
Output
1
Input
10
0 1 2 1 4 4 4 0 8
0 0 0 1 0 1 1 0 0 1
Output
27
|
MOD = 1000000007
n = int(input())
p = [int(x) for x in input().split()]
x = [int(x) for x in input().split()]
children = [[] for x in range(n)]
for i in range(1,n):
children[p[i-1]].append(i)
#print(children)
count = [(0,0) for i in range(n)]
for i in reversed(list(range(n))):
prod = 1
for ch in children[i]:
prod *= count[ch][0]+count[ch][1]
if x[i]:
count[i] = (0,prod % MOD)
else:
tot = 0
for ch in children[i]:
cur = count[ch][1]*prod // (count[ch][0]+count[ch][1])
tot += cur
count[i] = (prod % MOD, tot % MOD)
print(count[0][1])
|
MOD = 1000000007
n = int(input())
p = [int(x) for x in input().split()]
x = [int(x) for x in input().split()]
children = [[] for x in range(n)]
for i in range(1,n):
children[p[i-1]].append(i)
#print(children)
count = [(0,0) for i in range(n)]
for i in reversed(list(range(n))):
prod = 1
for ch in children[i]:
prod *= count[ch][0]+count[ch][1]
if x[i]:
count[i] = (0,prod % MOD)
else:
tot = 0
for ch in children[i]:
cur = count[ch][1]*prod // (count[ch][0]+count[ch][1])
tot += cur
count[i] = (prod % MOD, tot % MOD)
print(count[0][1])
|
train
|
APPS_structured
|
A [sequence or a series](http://world.mathigon.org/Sequences), in mathematics, is a string of objects, like numbers, that follow a particular pattern. The individual elements in a sequence are called terms. A simple example is `3, 6, 9, 12, 15, 18, 21, ...`, where the pattern is: _"add 3 to the previous term"_.
In this kata, we will be using a more complicated sequence: `0, 1, 3, 6, 10, 15, 21, 28, ...`
This sequence is generated with the pattern: _"the nth term is the sum of numbers from 0 to n, inclusive"_.
```
[ 0, 1, 3, 6, ...]
0 0+1 0+1+2 0+1+2+3
```
## Your Task
Complete the function that takes an integer `n` and returns a list/array of length `abs(n) + 1` of the arithmetic series explained above. When`n < 0` return the sequence with negative terms.
## Examples
```
5 --> [0, 1, 3, 6, 10, 15]
-5 --> [0, -1, -3, -6, -10, -15]
7 --> [0, 1, 3, 6, 10, 15, 21, 28]
```
|
from itertools import accumulate
def sum_of_n(n):
if n >= 0:
return list(accumulate(range(n+1)))
return list(accumulate(range(0, n-1, -1)))
|
from itertools import accumulate
def sum_of_n(n):
if n >= 0:
return list(accumulate(range(n+1)))
return list(accumulate(range(0, n-1, -1)))
|
train
|
APPS_structured
|
Introduction
Brainfuck is one of the most well-known esoteric programming languages. But it can be hard to understand any code longer that 5 characters. In this kata you have to solve that problem.
Description
In this kata you have to write a function which will do 3 tasks:
Optimize the given Brainfuck code.
Check it for mistakes.
Translate the given Brainfuck programming code into C programming code.
More formally about each of the tasks:
Your function has to remove from the source code all useless command sequences such as: '+-', '<>', '[]'. Also it must erase all characters except +-<>,.[].
Example:
"++--+." -> "+."
"[][+++]" -> "[+++]"
"<>><" -> ""
If the source code contains unpaired braces, your function should return "Error!" string.
Your function must generate a string of the C programming code as follows:
Sequences of the X commands + or - must be replaced by \*p += X;\n or \*p -= X;\n.
Example:
"++++++++++" -> "\*p += 10;\n"
"------" -> "\*p -= 6;\n"
Sequences of the Y commands > or < must be replaced by p += Y;\n or p -= Y;\n.
Example:
">>>>>>>>>>" -> "p += 10;\n"
"<<<<<<" -> "p -= 6;\n"
. command must be replaced by putchar(\*p);\n.
Example:
".." -> "putchar(\*p);\nputchar(\*p);\n"
, command must be replaced by \*p = getchar();\n.
Example:
"," -> "\*p = getchar();\n"
[ command must be replaced by if (\*p) do {\n. ] command must be replaced by } while (\*p);\n.
Example:
"[>>]" ->
if (\*p) do {\n
p += 2;\n
} while (\*p);\n
Each command in the code block must be shifted 2 spaces to the right accordingly to the previous code block.
Example:
"[>>[<<]]" ->
if (\*p) do {\n
p += 2;\n
if (\*p) do {\n
p -= 2;\n
} while (\*p);\n
} while (\*p);\n
Examples
Input:
+++++[>++++.<-]
Output:
*p += 5;
if (*p) do {
p += 1;
*p += 4;
putchar(*p);
p -= 1;
*p -= 1;
} while (*p);
|
import re
class Token(object):
ARITH = 1
POINTER = 2
GETCHAR = 3
PUTCHAR = 4
OPEN = 5
CLOSE = 6
def __init__(self, mode=None, indent=None, value=None):
self.mode = mode
self.value = value
self.indent = indent
def __str__(self):
if self.mode == self.ARITH:
sign = '+' if self.value > 0 else '-'
return '{}*p {}= {};\n'.format(self.indent, sign, abs(self.value))
if self.mode == self.POINTER:
sign = '+' if self.value > 0 else '-'
return '{}p {}= {};\n'.format(self.indent, sign, abs(self.value))
if self.mode == self.GETCHAR:
return self.indent + '*p = getchar();\n'
if self.mode == self.PUTCHAR:
return self.indent + 'putchar(*p);\n'
if self.mode == self.OPEN:
return self.indent + 'if (*p) do {\n'
if self.mode == self.CLOSE:
return self.indent + '} while (*p);\n'
return ''
class BF(object):
ARITH = 1
POINTER = 2
GETCHAR = 3
PUTCHAR = 4
OPEN = 5
CLOSE = 6
def __init__(self, source_code):
self.indent = ''
self.source_code = source_code
self.tokens = [Token()]
self.error = False
def convert_to_c(self):
try:
for c in self.source_code:
self.convert_one_char(c)
except ValueError:
return 'Error!'
if self.indent:
return 'Error!'
return ''.join(map(str, self.tokens))
def convert_one_char(self, c):
if c in '+-':
if self.tokens[-1].mode != self.ARITH:
self.tokens.append(Token(self.ARITH, self.indent, 0))
if c == '+':
self.tokens[-1].value += 1
else:
self.tokens[-1].value -= 1
if not self.tokens[-1].value:
del self.tokens[-1]
elif c in '><':
if self.tokens[-1].mode != self.POINTER:
self.tokens.append(Token(self.POINTER, self.indent, 0))
if c == '>':
self.tokens[-1].value += 1
else:
self.tokens[-1].value -= 1
if not self.tokens[-1].value:
del self.tokens[-1]
elif c == ',':
self.tokens.append(Token(self.GETCHAR, self.indent, 0))
elif c == '.':
self.tokens.append(Token(self.PUTCHAR, self.indent, 0))
elif c == '[':
self.tokens.append(Token(self.OPEN, self.indent, 0))
self.indent += ' '
elif c == ']':
if not self.indent:
raise ValueError
self.indent = self.indent[:-2]
if self.tokens[-1].mode == self.OPEN:
del self.tokens[-1]
else:
self.tokens.append(Token(self.CLOSE, self.indent, 0))
def brainfuck_to_c(source_code):
bf = BF(source_code)
return bf.convert_to_c()
|
import re
class Token(object):
ARITH = 1
POINTER = 2
GETCHAR = 3
PUTCHAR = 4
OPEN = 5
CLOSE = 6
def __init__(self, mode=None, indent=None, value=None):
self.mode = mode
self.value = value
self.indent = indent
def __str__(self):
if self.mode == self.ARITH:
sign = '+' if self.value > 0 else '-'
return '{}*p {}= {};\n'.format(self.indent, sign, abs(self.value))
if self.mode == self.POINTER:
sign = '+' if self.value > 0 else '-'
return '{}p {}= {};\n'.format(self.indent, sign, abs(self.value))
if self.mode == self.GETCHAR:
return self.indent + '*p = getchar();\n'
if self.mode == self.PUTCHAR:
return self.indent + 'putchar(*p);\n'
if self.mode == self.OPEN:
return self.indent + 'if (*p) do {\n'
if self.mode == self.CLOSE:
return self.indent + '} while (*p);\n'
return ''
class BF(object):
ARITH = 1
POINTER = 2
GETCHAR = 3
PUTCHAR = 4
OPEN = 5
CLOSE = 6
def __init__(self, source_code):
self.indent = ''
self.source_code = source_code
self.tokens = [Token()]
self.error = False
def convert_to_c(self):
try:
for c in self.source_code:
self.convert_one_char(c)
except ValueError:
return 'Error!'
if self.indent:
return 'Error!'
return ''.join(map(str, self.tokens))
def convert_one_char(self, c):
if c in '+-':
if self.tokens[-1].mode != self.ARITH:
self.tokens.append(Token(self.ARITH, self.indent, 0))
if c == '+':
self.tokens[-1].value += 1
else:
self.tokens[-1].value -= 1
if not self.tokens[-1].value:
del self.tokens[-1]
elif c in '><':
if self.tokens[-1].mode != self.POINTER:
self.tokens.append(Token(self.POINTER, self.indent, 0))
if c == '>':
self.tokens[-1].value += 1
else:
self.tokens[-1].value -= 1
if not self.tokens[-1].value:
del self.tokens[-1]
elif c == ',':
self.tokens.append(Token(self.GETCHAR, self.indent, 0))
elif c == '.':
self.tokens.append(Token(self.PUTCHAR, self.indent, 0))
elif c == '[':
self.tokens.append(Token(self.OPEN, self.indent, 0))
self.indent += ' '
elif c == ']':
if not self.indent:
raise ValueError
self.indent = self.indent[:-2]
if self.tokens[-1].mode == self.OPEN:
del self.tokens[-1]
else:
self.tokens.append(Token(self.CLOSE, self.indent, 0))
def brainfuck_to_c(source_code):
bf = BF(source_code)
return bf.convert_to_c()
|
train
|
APPS_structured
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.